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.util.MessageManager;
32 import java.io.InputStream;
33 import java.util.List;
36 * A low level class for alignment and feature IO with alignment formatting
37 * methods used by both applet and application for generating flat alignment
38 * files. It also holds the lists of magic format names that the applet and
39 * application will allow the user to read or write files with.
44 public class AppletFormatAdapter
46 private AlignmentViewPanel viewpanel;
48 public static String FILE = "File";
50 public static String URL = "URL";
52 public static String PASTE = "Paste";
54 public static String CLASSLOADER = "ClassLoader";
57 * add jalview-derived non-secondary structure annotation from PDB structure
59 boolean annotFromStructure = false;
62 * add secondary structure from PDB data with built-in algorithms
64 boolean localSecondaryStruct = false;
67 * process PDB data with web services
69 boolean serviceSecondaryStruct = false;
71 private AlignFile alignFile = null;
76 * character used to write newlines
78 protected String newline = System.getProperty("line.separator");
80 private AlignExportSettingI exportSettings;
83 * List of valid format strings used in the isValidFormat method
85 public static final String[] READABLE_FORMATS = new String[]
86 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
87 "PDB", "JnetFile", "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.GFF3File,
91 * List of readable format file extensions by application in order
92 * corresponding to READABLE_FNAMES
94 public static final String[] READABLE_EXTENSIONS = new String[]
95 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
96 "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT, JSONFile.FILE_EXT,
98 "jar,jvp", HtmlFile.FILE_EXT };
101 * List of readable formats by application in order corresponding to
102 * READABLE_EXTENSIONS
104 public static final String[] READABLE_FNAMES = new String[]
105 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm",
106 "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.GFF3File, "Jalview",
107 HtmlFile.FILE_DESC };
110 * List of valid format strings for use by callers of the formatSequences
113 public static final String[] WRITEABLE_FORMATS = new String[]
114 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
115 "STH", PhylipFile.FILE_DESC, JSONFile.FILE_DESC };
118 * List of extensions corresponding to file format types in WRITABLE_FNAMES
119 * that are writable by the application.
121 public static final String[] WRITABLE_EXTENSIONS = new String[]
122 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
123 "sto,stk", PhylipFile.FILE_EXT, JSONFile.FILE_EXT, "jvp" };
126 * List of writable formats by the application. Order must correspond with the
127 * WRITABLE_EXTENSIONS list of formats.
129 public static final String[] WRITABLE_FNAMES = new String[]
130 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
131 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, "Jalview" };
133 public static String INVALID_CHARACTERS = "Contains invalid characters";
135 // TODO: make these messages dynamic
136 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
137 + prettyPrint(READABLE_FORMATS);
139 public AppletFormatAdapter()
143 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
145 this.viewpanel = viewpanel;
148 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
149 AlignExportSettingI settings)
151 viewpanel = alignPanel;
152 exportSettings = settings;
158 * @return grammatically correct(ish) list consisting of els elements.
160 public static String prettyPrint(String[] els)
162 StringBuffer list = new StringBuffer();
163 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
168 list.append(" and " + els[els.length - 1] + ".");
169 return list.toString();
173 public void setNewlineString(String nl)
178 public String getNewlineString()
184 * check that this format is valid for reading
187 * a format string to be compared with READABLE_FORMATS
188 * @return true if format is readable
190 public static final boolean isValidFormat(String format)
192 return isValidFormat(format, false);
196 * validate format is valid for IO
199 * a format string to be compared with either READABLE_FORMATS or
202 * when true, format is checked for containment in WRITEABLE_FORMATS
203 * @return true if format is valid
205 public static final boolean isValidFormat(String format,
212 boolean valid = false;
213 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
215 for (String element : format_list)
217 if (element.equalsIgnoreCase(format))
227 * Constructs the correct filetype parser for a characterised datasource
234 * File format of data provided by datasource
236 * @return DOCUMENT ME!
238 public AlignmentI readFile(String inFile, String type, String format)
239 throws java.io.IOException
241 // TODO: generalise mapping between format string and io. class instances
242 // using Constructor.invoke reflection
243 this.inFile = inFile;
246 if (format.equals("FASTA"))
248 alignFile = new FastaFile(inFile, type);
250 else if (format.equals("MSF"))
252 alignFile = new MSFfile(inFile, type);
254 else if (format.equals("PileUp"))
256 alignFile = new PileUpfile(inFile, type);
258 else if (format.equals("CLUSTAL"))
260 alignFile = new ClustalFile(inFile, type);
262 else if (format.equals("BLC"))
264 alignFile = new BLCFile(inFile, type);
266 else if (format.equals("PIR"))
268 alignFile = new PIRFile(inFile, type);
270 else if (format.equals("PFAM"))
272 alignFile = new PfamFile(inFile, type);
274 else if (format.equals("JnetFile"))
276 alignFile = new JPredFile(inFile, type);
277 ((JPredFile) alignFile).removeNonSequences();
279 else if (format.equals("PDB"))
281 alignFile = new MCview.PDBfile(annotFromStructure,
282 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
283 // Uncomment to test Jmol data based PDB processing: JAL-1213
284 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
286 else if (format.equals("STH"))
288 alignFile = new StockholmFile(inFile, type);
290 else if (format.equals("SimpleBLAST"))
292 alignFile = new SimpleBlastFile(inFile, type);
294 else if (format.equals(PhylipFile.FILE_DESC))
296 alignFile = new PhylipFile(inFile, type);
298 else if (format.equals(JSONFile.FILE_DESC))
300 alignFile = new JSONFile(inFile, type);
302 else if (format.equals(HtmlFile.FILE_DESC))
304 alignFile = new HtmlFile(inFile, type);
306 else if (format.equals("RNAML"))
308 alignFile = new RnamlFile(inFile, type);
310 else if (format.equals(IdentifyFile.GFF3File))
312 alignFile = new Gff3File(inFile, type);
314 return buildAlignmentFrom(alignFile);
315 } catch (Exception e)
318 System.err.println("Failed to read alignment using the '" + format
319 + "' reader.\n" + e);
321 if (e.getMessage() != null
322 && e.getMessage().startsWith(INVALID_CHARACTERS))
324 throw new java.io.IOException(e.getMessage());
327 // Finally test if the user has pasted just the sequence, no id
328 if (type.equalsIgnoreCase("Paste"))
332 // Possible sequence is just residues with no label
333 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
334 return buildAlignmentFrom(alignFile);
336 } catch (Exception ex)
338 if (ex.toString().startsWith(INVALID_CHARACTERS))
340 throw new java.io.IOException(e.getMessage());
343 ex.printStackTrace();
347 // If we get to this stage, the format was not supported
348 throw new java.io.IOException(SUPPORTED_FORMATS);
353 * Constructs the correct filetype parser for an already open datasource
356 * an existing datasource
358 * File format of data that will be provided by datasource
360 * @return DOCUMENT ME!
362 public AlignmentI readFromFile(FileParse source, String format)
363 throws java.io.IOException
365 // TODO: generalise mapping between format string and io. class instances
366 // using Constructor.invoke reflection
367 // This is exactly the same as the readFile method except we substitute
368 // 'inFile, type' with 'source'
369 this.inFile = source.getInFile();
370 String type = source.type;
373 if (format.equals("FASTA"))
375 alignFile = new FastaFile(source);
377 else if (format.equals("MSF"))
379 alignFile = new MSFfile(source);
381 else if (format.equals("PileUp"))
383 alignFile = new PileUpfile(source);
385 else if (format.equals("CLUSTAL"))
387 alignFile = new ClustalFile(source);
389 else if (format.equals("BLC"))
391 alignFile = new BLCFile(source);
393 else if (format.equals("PIR"))
395 alignFile = new PIRFile(source);
397 else if (format.equals("PFAM"))
399 alignFile = new PfamFile(source);
401 else if (format.equals("JnetFile"))
403 alignFile = new JPredFile(source);
404 ((JPredFile) alignFile).removeNonSequences();
406 else if (format.equals("PDB"))
408 alignFile = new MCview.PDBfile(annotFromStructure,
409 localSecondaryStruct, serviceSecondaryStruct, source);
411 else if (format.equals("STH"))
413 alignFile = new StockholmFile(source);
415 else if (format.equals("RNAML"))
417 alignFile = new RnamlFile(source);
419 else if (format.equals("SimpleBLAST"))
421 alignFile = new SimpleBlastFile(source);
423 else if (format.equals(PhylipFile.FILE_DESC))
425 alignFile = new PhylipFile(source);
427 else if (format.equals(IdentifyFile.GFF3File))
429 alignFile = new Gff3File(inFile, type);
431 else if (format.equals(JSONFile.FILE_DESC))
433 alignFile = new JSONFile(source);
435 else if (format.equals(HtmlFile.FILE_DESC))
437 alignFile = new HtmlFile(source);
440 return buildAlignmentFrom(alignFile);
442 } catch (Exception e)
445 System.err.println("Failed to read alignment using the '" + format
446 + "' reader.\n" + e);
448 if (e.getMessage() != null
449 && e.getMessage().startsWith(INVALID_CHARACTERS))
451 throw new java.io.IOException(e.getMessage());
454 // Finally test if the user has pasted just the sequence, no id
455 if (type.equalsIgnoreCase("Paste"))
459 // Possible sequence is just residues with no label
460 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
461 return buildAlignmentFrom(alignFile);
463 } catch (Exception ex)
465 if (ex.toString().startsWith(INVALID_CHARACTERS))
467 throw new java.io.IOException(e.getMessage());
470 ex.printStackTrace();
474 // If we get to this stage, the format was not supported
475 throw new java.io.IOException(SUPPORTED_FORMATS);
481 * boilerplate method to handle data from an AlignFile and construct a new
482 * alignment or import to an existing alignment
485 * @return AlignmentI instance ready to pass to a UI constructor
487 private AlignmentI buildAlignmentFrom(AlignFile alignFile2)
489 // Standard boilerplate for creating alignment from parser
490 // alignFile.configureForView(viewpanel);
492 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
494 alignFile.addAnnotations(al);
496 alignFile.addGroups(al);
502 * create an alignment flatfile from a Jalview alignment view
506 * @param selectedOnly
507 * @return flatfile in a string
509 public String formatSequences(String format, boolean jvsuffix,
510 AlignmentViewPanel ap, boolean selectedOnly)
513 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
514 selectedOnly, false);
515 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
517 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
518 .getVisibleAlignmentAnnotation(selectedOnly));
521 for (AlignmentAnnotation aa : ala)
523 aselview.addAnnotation(aa);
527 return formatSequences(format, aselview, jvsuffix);
531 * Construct an output class for an alignment in a particular filetype TODO:
532 * allow caller to detect errors and warnings encountered when generating
536 * string name of alignment format
538 * the alignment to be written out
540 * passed to AlnFile class controls whether /START-END is added to
543 * @return alignment flat file contents
545 public String formatSequences(String format, AlignmentI alignment,
550 AlignFile afile = null;
551 if (format.equalsIgnoreCase("FASTA"))
553 afile = new FastaFile();
555 else if (format.equalsIgnoreCase("MSF"))
557 afile = new MSFfile();
559 else if (format.equalsIgnoreCase("PileUp"))
561 afile = new PileUpfile();
563 else if (format.equalsIgnoreCase("CLUSTAL"))
565 afile = new ClustalFile();
567 else if (format.equalsIgnoreCase("BLC"))
569 afile = new BLCFile();
571 else if (format.equalsIgnoreCase("PIR"))
573 afile = new PIRFile();
575 else if (format.equalsIgnoreCase("PFAM"))
577 afile = new PfamFile();
579 else if (format.equalsIgnoreCase("STH"))
581 afile = new StockholmFile(alignment);
583 else if (format.equalsIgnoreCase("AMSA"))
585 afile = new AMSAFile(alignment);
587 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
589 afile = new PhylipFile();
591 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
593 afile = new JSONFile();
595 else if (format.equalsIgnoreCase("RNAML"))
597 afile = new RnamlFile();
602 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
605 afile.setNewlineString(newline);
606 afile.addJVSuffix(jvsuffix);
607 afile.setExportSettings(exportSettings);
608 afile.configureForView(viewpanel);
610 // check whether we were given a specific alignment to export, rather than
611 // the one in the viewpanel
612 if (viewpanel == null || viewpanel.getAlignment() == null
613 || viewpanel.getAlignment() != alignment)
615 afile.setSeqs(alignment.getSequencesArray());
619 afile.setSeqs(viewpanel.getAlignment().getSequencesArray());
622 String afileresp = afile.print();
623 if (afile.hasWarningMessage())
625 System.err.println("Warning raised when writing as " + format
626 + " : " + afile.getWarningMessage());
629 } catch (Exception e)
631 System.err.println("Failed to write alignment as a '" + format
639 public static String checkProtocol(String file)
641 String protocol = FILE;
642 String ft = file.toLowerCase().trim();
643 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
644 || ft.indexOf("file:") == 0)
651 public static void main(String[] args)
654 while (i < args.length)
656 File f = new File(args[i]);
661 System.out.println("Reading file: " + f);
662 AppletFormatAdapter afa = new AppletFormatAdapter();
663 Runtime r = Runtime.getRuntime();
665 long memf = -r.totalMemory() + r.freeMemory();
666 long t1 = -System.currentTimeMillis();
667 AlignmentI al = afa.readFile(args[i], FILE,
668 new IdentifyFile().Identify(args[i], FILE));
669 t1 += System.currentTimeMillis();
671 memf += r.totalMemory() - r.freeMemory();
674 System.out.println("Alignment contains " + al.getHeight()
675 + " sequences and " + al.getWidth() + " columns.");
678 System.out.println(new AppletFormatAdapter().formatSequences(
680 } catch (Exception e)
683 .println("Couln't format the alignment for output as a FASTA file.");
684 e.printStackTrace(System.err);
689 System.out.println("Couldn't read alignment");
691 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
693 .println("Difference between free memory now and before is "
694 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
695 } catch (Exception e)
697 System.err.println("Exception when dealing with " + i
698 + "'th argument: " + args[i] + "\n" + e);
703 System.err.println("Ignoring argument '" + args[i] + "' (" + i
704 + "'th)- not a readable file.");
711 * try to discover how to access the given file as a valid datasource that
712 * will be identified as the given type.
716 * @return protocol that yields the data parsable as the given type
718 public static String resolveProtocol(String file, String format)
720 return resolveProtocol(file, format, false);
723 public static String resolveProtocol(String file, String format,
726 // TODO: test thoroughly!
727 String protocol = null;
730 System.out.println("resolving datasource started with:\n>>file\n"
731 + file + ">>endfile");
734 // This might throw a security exception in certain browsers
735 // Netscape Communicator for instance.
739 InputStream is = System.getSecurityManager().getClass()
740 .getResourceAsStream("/" + file);
748 System.err.println("Resource '" + file + "' was "
749 + (rtn ? "" : "not") + " located by classloader.");
754 protocol = AppletFormatAdapter.CLASSLOADER;
757 } catch (Exception ex)
760 .println("Exception checking resources: " + file + " " + ex);
763 if (file.indexOf("://") > -1)
765 protocol = AppletFormatAdapter.URL;
769 // skipping codebase prepend check.
770 protocol = AppletFormatAdapter.FILE;
777 System.out.println("Trying to get contents of resource as "
780 fp = new FileParse(file, protocol);
789 System.out.println("Successful.");
792 } catch (Exception e)
796 System.err.println("Exception when accessing content: " + e);
804 System.out.println("Accessing as paste.");
806 protocol = AppletFormatAdapter.PASTE;
810 fp = new FileParse(file, protocol);
815 } catch (Exception e)
817 System.err.println("Failed to access content as paste!");
826 if (format == null || format.length() == 0)
834 String idformat = new jalview.io.IdentifyFile().Identify(file,
836 if (idformat == null)
840 System.out.println("Format not identified. Inaccessible file.");
846 System.out.println("Format identified as " + idformat
847 + "and expected as " + format);
849 if (idformat.equals(format))
853 System.out.println("Protocol identified as " + protocol);
862 .println("File deemed not accessible via " + protocol);
867 } catch (Exception e)
871 System.err.println("File deemed not accessible via " + protocol);
881 public AlignFile getAlignFile()
886 public void setAlignFile(AlignFile alignFile)
888 this.alignFile = alignFile;