2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.api.AlignExportSettingI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.AlignmentView;
29 import jalview.datamodel.SeqDistanceContactMatrix;
30 import jalview.datamodel.PDBEntry.Type;
31 import jalview.datamodel.SequenceI;
32 import jalview.ext.jmol.JmolParser;
33 import jalview.structure.StructureImportSettings;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.util.List;
41 * A low level class for alignment and feature IO with alignment formatting
42 * methods used by both applet and application for generating flat alignment
43 * files. It also holds the lists of magic format names that the applet and
44 * application will allow the user to read or write files with.
49 public class AppletFormatAdapter
51 private AlignmentViewPanel viewpanel;
54 * add jalview-derived non-secondary structure annotation from PDB structure
56 boolean annotFromStructure = false;
59 * add secondary structure from PDB data with built-in algorithms
61 boolean localSecondaryStruct = false;
64 * process PDB data with web services
66 boolean serviceSecondaryStruct = false;
68 private AlignmentFileReaderI alignFile = null;
73 * character used to write newlines
75 protected String newline = System.getProperty("line.separator");
77 private AlignExportSettingI exportSettings;
79 public static String INVALID_CHARACTERS = "Contains invalid characters";
82 * Returns an error message with a list of supported readable file formats
86 public static String getSupportedFormats()
88 return "Formats currently supported are\n"
89 + prettyPrint(FileFormats.getInstance().getReadableFormats());
91 public AppletFormatAdapter()
95 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
97 this.viewpanel = viewpanel;
100 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
101 AlignExportSettingI settings)
103 viewpanel = alignPanel;
104 exportSettings = settings;
108 * Formats a grammatically correct(ish) list consisting of the given objects
113 public static String prettyPrint(List<? extends Object> things)
115 StringBuffer list = new StringBuffer();
116 for (int i = 0, iSize = things.size() - 1; i < iSize; i++)
118 list.append(things.get(i).toString());
121 // could i18n 'and' here
122 list.append(" and " + things.get(things.size() - 1).toString() + ".");
123 return list.toString();
126 public void setNewlineString(String nl)
131 public String getNewlineString()
137 * Constructs the correct filetype parser for a characterised datasource
147 public AlignmentI readFile(String file, DataSourceType sourceType,
148 FileFormatI fileFormat) throws IOException
153 if (fileFormat.isStructureFile())
155 String structureParser = StructureImportSettings
156 .getDefaultPDBFileParser();
157 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
158 StructureImportSettings.StructureParser.JMOL_PARSER
160 StructureImportSettings.addSettings(annotFromStructure,
161 localSecondaryStruct, serviceSecondaryStruct);
164 alignFile = new JmolParser(inFile, sourceType);
168 // todo is MCview parsing obsolete yet? JAL-2120
169 StructureImportSettings.setShowSeqFeatures(true);
170 alignFile = new MCview.PDBfile(annotFromStructure,
171 localSecondaryStruct, serviceSecondaryStruct, inFile,
174 ((StructureFile) alignFile).setDbRefType(FileFormat.PDB
175 .equals(fileFormat) ? Type.PDB : Type.MMCIF);
179 // alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
180 alignFile = fileFormat.getReader(new FileParse(inFile,
183 return buildAlignmentFromFile();
184 } catch (Exception e)
187 System.err.println("Failed to read alignment using the '"
188 + fileFormat + "' reader.\n" + e);
190 if (e.getMessage() != null
191 && e.getMessage().startsWith(INVALID_CHARACTERS))
193 throw new IOException(e.getMessage());
196 // Finally test if the user has pasted just the sequence, no id
197 if (sourceType == DataSourceType.PASTE)
201 // Possible sequence is just residues with no label
202 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
203 DataSourceType.PASTE);
204 return buildAlignmentFromFile();
206 } catch (Exception ex)
208 if (ex.toString().startsWith(INVALID_CHARACTERS))
210 throw new IOException(e.getMessage());
213 ex.printStackTrace();
216 if (FileFormat.Html.equals(fileFormat))
218 throw new IOException(e.getMessage());
221 throw new FileFormatException(getSupportedFormats());
225 * Constructs the correct filetype parser for an already open datasource
228 * an existing datasource
230 * File format of data that will be provided by datasource
234 public AlignmentI readFromFile(FileParse source, FileFormatI format)
237 this.inFile = source.getInFile();
238 DataSourceType type = source.dataSourceType;
241 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
243 // TODO obtain config value from preference settings
244 boolean isParseWithJMOL = false;
247 StructureImportSettings.addSettings(annotFromStructure,
248 localSecondaryStruct, serviceSecondaryStruct);
249 alignFile = new JmolParser(source);
253 StructureImportSettings.setShowSeqFeatures(true);
254 alignFile = new MCview.PDBfile(annotFromStructure,
255 localSecondaryStruct, serviceSecondaryStruct, source);
257 ((StructureFile) alignFile).setDbRefType(Type.PDB);
261 alignFile = format.getReader(source);
264 return buildAlignmentFromFile();
266 } catch (Exception e)
269 System.err.println("Failed to read alignment using the '" + format
270 + "' reader.\n" + e);
272 if (e.getMessage() != null
273 && e.getMessage().startsWith(INVALID_CHARACTERS))
275 throw new FileFormatException(e.getMessage());
278 // Finally test if the user has pasted just the sequence, no id
279 if (type == DataSourceType.PASTE)
283 // Possible sequence is just residues with no label
284 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
285 DataSourceType.PASTE);
286 return buildAlignmentFromFile();
288 } catch (Exception ex)
290 if (ex.toString().startsWith(INVALID_CHARACTERS))
292 throw new IOException(e.getMessage());
295 ex.printStackTrace();
299 // If we get to this stage, the format was not supported
300 throw new FileFormatException(getSupportedFormats());
305 * boilerplate method to handle data from an AlignFile and construct a new
306 * alignment or import to an existing alignment
308 * @return AlignmentI instance ready to pass to a UI constructor
310 private AlignmentI buildAlignmentFromFile()
312 // Standard boilerplate for creating alignment from parser
313 // alignFile.configureForView(viewpanel);
315 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
317 alignFile.addAnnotations(al);
319 alignFile.addGroups(al);
321 al.addContactList(new SeqDistanceContactMatrix(al.getWidth()));
327 * create an alignment flatfile from a Jalview alignment view
332 * @param selectedOnly
333 * @return flatfile in a string
335 public String formatSequences(FileFormatI format, boolean jvsuffix,
336 AlignmentViewPanel ap, boolean selectedOnly)
339 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
340 selectedOnly, false);
341 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
343 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
344 .getVisibleAlignmentAnnotation(selectedOnly));
347 for (AlignmentAnnotation aa : ala)
349 aselview.addAnnotation(aa);
353 return formatSequences(format, aselview, jvsuffix);
357 * Construct an output class for an alignment in a particular filetype TODO:
358 * allow caller to detect errors and warnings encountered when generating
362 * string name of alignment format
364 * the alignment to be written out
366 * passed to AlnFile class controls whether /START-END is added to
369 * @return alignment flat file contents
371 public String formatSequences(FileFormatI format, AlignmentI alignment,
376 AlignmentFileWriterI afile = format.getWriter(alignment);
378 afile.setNewlineString(newline);
379 afile.setExportSettings(exportSettings);
380 afile.configureForView(viewpanel);
382 // check whether we were given a specific alignment to export, rather than
383 // the one in the viewpanel
384 SequenceI[] seqs = null;
385 if (viewpanel == null || viewpanel.getAlignment() == null
386 || viewpanel.getAlignment() != alignment)
388 seqs = alignment.getSequencesArray();
392 seqs = viewpanel.getAlignment().getSequencesArray();
395 String afileresp = afile.print(seqs, jvsuffix);
396 if (afile.hasWarningMessage())
398 System.err.println("Warning raised when writing as " + format
399 + " : " + afile.getWarningMessage());
402 } catch (Exception e)
404 System.err.println("Failed to write alignment as a '"
414 * Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
418 * @return the protocol for the input data
420 public static DataSourceType checkProtocol(String data)
422 DataSourceType protocol = DataSourceType.PASTE;
423 String ft = data.toLowerCase().trim();
424 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
425 || ft.indexOf("file:") == 0)
427 protocol = DataSourceType.URL;
429 else if (new File(data).exists())
431 protocol = DataSourceType.FILE;
436 public static void main(String[] args)
439 while (i < args.length)
441 File f = new File(args[i]);
446 System.out.println("Reading file: " + f);
447 AppletFormatAdapter afa = new AppletFormatAdapter();
448 Runtime r = Runtime.getRuntime();
450 long memf = -r.totalMemory() + r.freeMemory();
451 long t1 = -System.currentTimeMillis();
453 .readFile(args[i], DataSourceType.FILE,
454 new IdentifyFile().identify(args[i],
455 DataSourceType.FILE));
456 t1 += System.currentTimeMillis();
458 memf += r.totalMemory() - r.freeMemory();
461 System.out.println("Alignment contains " + al.getHeight()
462 + " sequences and " + al.getWidth() + " columns.");
465 System.out.println(new AppletFormatAdapter().formatSequences(
466 FileFormat.Fasta, al, true));
467 } catch (Exception e)
470 .println("Couln't format the alignment for output as a FASTA file.");
471 e.printStackTrace(System.err);
476 System.out.println("Couldn't read alignment");
478 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
480 .println("Difference between free memory now and before is "
481 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
482 } catch (Exception e)
484 System.err.println("Exception when dealing with " + i
485 + "'th argument: " + args[i] + "\n" + e);
490 System.err.println("Ignoring argument '" + args[i] + "' (" + i
491 + "'th)- not a readable file.");
498 * try to discover how to access the given file as a valid datasource that
499 * will be identified as the given type.
503 * @return protocol that yields the data parsable as the given type
505 public static DataSourceType resolveProtocol(String file,
508 return resolveProtocol(file, format, false);
511 public static DataSourceType resolveProtocol(String file,
512 FileFormatI format, boolean debug)
514 // TODO: test thoroughly!
515 DataSourceType protocol = null;
518 System.out.println("resolving datasource started with:\n>>file\n"
519 + file + ">>endfile");
522 // This might throw a security exception in certain browsers
523 // Netscape Communicator for instance.
527 InputStream is = System.getSecurityManager().getClass()
528 .getResourceAsStream("/" + file);
536 System.err.println("Resource '" + file + "' was "
537 + (rtn ? "" : "not") + " located by classloader.");
541 protocol = DataSourceType.CLASSLOADER;
544 } catch (Exception ex)
547 .println("Exception checking resources: " + file + " " + ex);
550 if (file.indexOf("://") > -1)
552 protocol = DataSourceType.URL;
556 // skipping codebase prepend check.
557 protocol = DataSourceType.FILE;
564 System.out.println("Trying to get contents of resource as "
567 fp = new FileParse(file, protocol);
576 System.out.println("Successful.");
579 } catch (Exception e)
583 System.err.println("Exception when accessing content: " + e);
591 System.out.println("Accessing as paste.");
593 protocol = DataSourceType.PASTE;
597 fp = new FileParse(file, protocol);
602 } catch (Exception e)
604 System.err.println("Failed to access content as paste!");
621 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
622 if (idformat == null)
626 System.out.println("Format not identified. Inaccessible file.");
632 System.out.println("Format identified as " + idformat
633 + "and expected as " + format);
635 if (idformat.equals(format))
639 System.out.println("Protocol identified as " + protocol);
648 .println("File deemed not accessible via " + protocol);
653 } catch (Exception e)
657 System.err.println("File deemed not accessible via " + protocol);
665 public AlignmentFileReaderI getAlignFile()