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.PDBEntry.Type;
30 import jalview.structure.StructureImportSettings;
31 import jalview.util.MessageManager;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.util.List;
39 * A low level class for alignment and feature IO with alignment formatting
40 * methods used by both applet and application for generating flat alignment
41 * files. It also holds the lists of magic format names that the applet and
42 * application will allow the user to read or write files with.
47 public class AppletFormatAdapter
49 private AlignmentViewPanel viewpanel;
51 public static String FILE = "File";
53 public static String URL = "URL";
55 public static String PASTE = "Paste";
57 public static String CLASSLOADER = "ClassLoader";
60 * add jalview-derived non-secondary structure annotation from PDB structure
62 boolean annotFromStructure = false;
65 * add secondary structure from PDB data with built-in algorithms
67 boolean localSecondaryStruct = false;
70 * process PDB data with web services
72 boolean serviceSecondaryStruct = false;
74 private AlignFile alignFile = null;
79 * character used to write newlines
81 protected String newline = System.getProperty("line.separator");
83 private AlignExportSettingI exportSettings;
86 * List of valid format strings used in the isValidFormat method
88 public static final String[] READABLE_FORMATS = new String[] { "BLC",
89 "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH", "PDB",
90 "JnetFile", "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC,
91 IdentifyFile.FeaturesFile, "HTML", "mmCIF" };
94 * List of readable format file extensions by application in order
95 * corresponding to READABLE_FNAMES
97 public static final String[] READABLE_EXTENSIONS = new String[] {
98 "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
99 "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT, JSONFile.FILE_EXT,
100 ".gff2,gff3", "jar,jvp", HtmlFile.FILE_EXT, "cif" };
103 * List of readable formats by application in order corresponding to
104 * READABLE_EXTENSIONS
106 public static final String[] READABLE_FNAMES = new String[] { "Fasta",
107 "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm", "RNAML",
108 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.FeaturesFile,
109 "Jalview", HtmlFile.FILE_DESC, "mmCIF" };
112 * List of valid format strings for use by callers of the formatSequences
115 public static final String[] WRITEABLE_FORMATS = new String[] { "BLC",
116 "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA", "STH",
117 PhylipFile.FILE_DESC, JSONFile.FILE_DESC };
120 * List of extensions corresponding to file format types in WRITABLE_FNAMES
121 * that are writable by the application.
123 public static final String[] WRITABLE_EXTENSIONS = new String[] {
124 "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
125 "sto,stk", PhylipFile.FILE_EXT, JSONFile.FILE_EXT, "jvp" };
128 * List of writable formats by the application. Order must correspond with the
129 * WRITABLE_EXTENSIONS list of formats.
131 public static final String[] WRITABLE_FNAMES = new String[] { "Fasta",
132 "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
133 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, "Jalview" };
135 public static String INVALID_CHARACTERS = "Contains invalid characters";
137 // TODO: make these messages dynamic
138 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
139 + prettyPrint(READABLE_FORMATS);
141 public AppletFormatAdapter()
145 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
147 this.viewpanel = viewpanel;
150 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
151 AlignExportSettingI settings)
153 viewpanel = alignPanel;
154 exportSettings = settings;
160 * @return grammatically correct(ish) list consisting of els elements.
162 public static String prettyPrint(String[] els)
164 StringBuffer list = new StringBuffer();
165 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
170 list.append(" and " + els[els.length - 1] + ".");
171 return list.toString();
174 public void setNewlineString(String nl)
179 public String getNewlineString()
185 * check that this format is valid for reading
188 * a format string to be compared with READABLE_FORMATS
189 * @return true if format is readable
191 public static final boolean isValidFormat(String format)
193 return isValidFormat(format, false);
197 * validate format is valid for IO
200 * a format string to be compared with either READABLE_FORMATS or
203 * when true, format is checked for containment in WRITEABLE_FORMATS
204 * @return true if format is valid
206 public static final boolean isValidFormat(String format,
213 boolean valid = false;
214 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
216 for (String element : format_list)
218 if (element.equalsIgnoreCase(format))
228 * Constructs the correct filetype parser for a characterised datasource
235 * File format of data provided by datasource
237 * @return DOCUMENT ME!
239 public AlignmentI readFile(String inFile, String type, String format)
240 throws java.io.IOException
242 // TODO: generalise mapping between format string and io. class instances
243 // using Constructor.invoke reflection
244 this.inFile = inFile;
247 if (format.equals("FASTA"))
249 alignFile = new FastaFile(inFile, type);
251 else if (format.equals("MSF"))
253 alignFile = new MSFfile(inFile, type);
255 else if (format.equals("PileUp"))
257 alignFile = new PileUpfile(inFile, type);
259 else if (format.equals("CLUSTAL"))
261 alignFile = new ClustalFile(inFile, type);
263 else if (format.equals("BLC"))
265 alignFile = new BLCFile(inFile, type);
267 else if (format.equals("PIR"))
269 alignFile = new PIRFile(inFile, type);
271 else if (format.equals("PFAM"))
273 alignFile = new PfamFile(inFile, type);
275 else if (format.equals("JnetFile"))
277 alignFile = new JPredFile(inFile, type);
278 ((JPredFile) alignFile).removeNonSequences();
280 else if (format.equals("PDB"))
283 StructureImportSettings.addSettings(annotFromStructure,
284 localSecondaryStruct, serviceSecondaryStruct);
285 alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
286 localSecondaryStruct, serviceSecondaryStruct, inFile,
288 ((StructureFile) alignFile).setDbRefType(format);
290 else if (format.equalsIgnoreCase("mmCIF"))
292 StructureImportSettings.addSettings(annotFromStructure,
293 localSecondaryStruct, serviceSecondaryStruct);
294 alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
295 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
296 ((StructureFile) alignFile).setDbRefType(format);
298 else if (format.equals("STH"))
300 alignFile = new StockholmFile(inFile, type);
302 else if (format.equals("SimpleBLAST"))
304 alignFile = new SimpleBlastFile(inFile, type);
306 else if (format.equals(PhylipFile.FILE_DESC))
308 alignFile = new PhylipFile(inFile, type);
310 else if (format.equals(JSONFile.FILE_DESC))
312 alignFile = new JSONFile(inFile, type);
314 else if (format.equals(HtmlFile.FILE_DESC))
316 alignFile = new HtmlFile(inFile, type);
318 else if (format.equals("RNAML"))
320 alignFile = new RnamlFile(inFile, type);
322 else if (format.equals(IdentifyFile.FeaturesFile))
324 alignFile = new FeaturesFile(true, inFile, type);
326 return buildAlignmentFrom(alignFile);
327 } catch (Exception e)
330 System.err.println("Failed to read alignment using the '" + format
331 + "' reader.\n" + e);
333 if (e.getMessage() != null
334 && e.getMessage().startsWith(INVALID_CHARACTERS))
336 throw new java.io.IOException(e.getMessage());
339 // Finally test if the user has pasted just the sequence, no id
340 if (type.equalsIgnoreCase("Paste"))
344 // Possible sequence is just residues with no label
345 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
346 return buildAlignmentFrom(alignFile);
348 } catch (Exception ex)
350 if (ex.toString().startsWith(INVALID_CHARACTERS))
352 throw new java.io.IOException(e.getMessage());
355 ex.printStackTrace();
358 if (format.equalsIgnoreCase("HTML"))
360 throw new IOException(e.getMessage());
362 // If we get to this stage, the format was not supported
363 throw new java.io.IOException(SUPPORTED_FORMATS);
368 * Constructs the correct filetype parser for an already open datasource
371 * an existing datasource
373 * File format of data that will be provided by datasource
375 * @return DOCUMENT ME!
377 public AlignmentI readFromFile(FileParse source, String format)
378 throws java.io.IOException
380 // TODO: generalise mapping between format string and io. class instances
381 // using Constructor.invoke reflection
382 // This is exactly the same as the readFile method except we substitute
383 // 'inFile, type' with 'source'
384 this.inFile = source.getInFile();
385 String type = source.type;
388 if (format.equals("FASTA"))
390 alignFile = new FastaFile(source);
392 else if (format.equals("MSF"))
394 alignFile = new MSFfile(source);
396 else if (format.equals("PileUp"))
398 alignFile = new PileUpfile(source);
400 else if (format.equals("CLUSTAL"))
402 alignFile = new ClustalFile(source);
404 else if (format.equals("BLC"))
406 alignFile = new BLCFile(source);
408 else if (format.equals("PIR"))
410 alignFile = new PIRFile(source);
412 else if (format.equals("PFAM"))
414 alignFile = new PfamFile(source);
416 else if (format.equals("JnetFile"))
418 alignFile = new JPredFile(source);
419 ((JPredFile) alignFile).removeNonSequences();
421 else if (format.equals("PDB"))
423 // TODO obtain config value from preference settings
424 boolean isParseWithJMOL = false;
427 StructureImportSettings.addSettings(annotFromStructure,
428 localSecondaryStruct, serviceSecondaryStruct);
429 alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
430 localSecondaryStruct, serviceSecondaryStruct, source);
434 StructureImportSettings.setShowSeqFeatures(true);
435 alignFile = new MCview.PDBfile(annotFromStructure,
436 localSecondaryStruct, serviceSecondaryStruct, source);
438 ((StructureFile) alignFile).setDbRefType(Type.PDB);
440 else if (format.equalsIgnoreCase("mmCIF"))
442 StructureImportSettings.addSettings(annotFromStructure,
443 localSecondaryStruct, serviceSecondaryStruct);
444 alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
445 localSecondaryStruct, serviceSecondaryStruct, source);
446 ((StructureFile) alignFile).setDbRefType(Type.MMCIF);
448 else if (format.equals("STH"))
450 alignFile = new StockholmFile(source);
452 else if (format.equals("RNAML"))
454 alignFile = new RnamlFile(source);
456 else if (format.equals("SimpleBLAST"))
458 alignFile = new SimpleBlastFile(source);
460 else if (format.equals(PhylipFile.FILE_DESC))
462 alignFile = new PhylipFile(source);
464 else if (format.equals(IdentifyFile.FeaturesFile))
466 alignFile = new FeaturesFile(inFile, type);
468 else if (format.equals(JSONFile.FILE_DESC))
470 alignFile = new JSONFile(source);
472 else if (format.equals(HtmlFile.FILE_DESC))
474 alignFile = new HtmlFile(source);
477 return buildAlignmentFrom(alignFile);
479 } catch (Exception e)
482 System.err.println("Failed to read alignment using the '" + format
483 + "' reader.\n" + e);
485 if (e.getMessage() != null
486 && e.getMessage().startsWith(INVALID_CHARACTERS))
488 throw new java.io.IOException(e.getMessage());
491 // Finally test if the user has pasted just the sequence, no id
492 if (type.equalsIgnoreCase("Paste"))
496 // Possible sequence is just residues with no label
497 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
498 return buildAlignmentFrom(alignFile);
500 } catch (Exception ex)
502 if (ex.toString().startsWith(INVALID_CHARACTERS))
504 throw new java.io.IOException(e.getMessage());
507 ex.printStackTrace();
511 // If we get to this stage, the format was not supported
512 throw new java.io.IOException(SUPPORTED_FORMATS);
517 * boilerplate method to handle data from an AlignFile and construct a new
518 * alignment or import to an existing alignment
521 * @return AlignmentI instance ready to pass to a UI constructor
523 private AlignmentI buildAlignmentFrom(AlignFile alignFile2)
525 // Standard boilerplate for creating alignment from parser
526 // alignFile.configureForView(viewpanel);
528 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
530 alignFile.addAnnotations(al);
532 alignFile.addGroups(al);
538 * create an alignment flatfile from a Jalview alignment view
543 * @param selectedOnly
544 * @return flatfile in a string
546 public String formatSequences(String format, boolean jvsuffix,
547 AlignmentViewPanel ap, boolean selectedOnly)
550 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
551 selectedOnly, false);
552 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
554 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
555 .getVisibleAlignmentAnnotation(selectedOnly));
558 for (AlignmentAnnotation aa : ala)
560 aselview.addAnnotation(aa);
564 return formatSequences(format, aselview, jvsuffix);
568 * Construct an output class for an alignment in a particular filetype TODO:
569 * allow caller to detect errors and warnings encountered when generating
573 * string name of alignment format
575 * the alignment to be written out
577 * passed to AlnFile class controls whether /START-END is added to
580 * @return alignment flat file contents
582 public String formatSequences(String format, AlignmentI alignment,
587 AlignFile afile = null;
588 if (format.equalsIgnoreCase("FASTA"))
590 afile = new FastaFile();
592 else if (format.equalsIgnoreCase("MSF"))
594 afile = new MSFfile();
596 else if (format.equalsIgnoreCase("PileUp"))
598 afile = new PileUpfile();
600 else if (format.equalsIgnoreCase("CLUSTAL"))
602 afile = new ClustalFile();
604 else if (format.equalsIgnoreCase("BLC"))
606 afile = new BLCFile();
608 else if (format.equalsIgnoreCase("PIR"))
610 afile = new PIRFile();
612 else if (format.equalsIgnoreCase("PFAM"))
614 afile = new PfamFile();
616 else if (format.equalsIgnoreCase("STH"))
618 afile = new StockholmFile(alignment);
620 else if (format.equalsIgnoreCase("AMSA"))
622 afile = new AMSAFile(alignment);
624 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
626 afile = new PhylipFile();
628 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
630 afile = new JSONFile();
632 else if (format.equalsIgnoreCase("RNAML"))
634 afile = new RnamlFile();
641 .getString("error.implementation_error_unknown_file_format_string"));
644 afile.setNewlineString(newline);
645 afile.addJVSuffix(jvsuffix);
646 afile.setExportSettings(exportSettings);
647 afile.configureForView(viewpanel);
649 // check whether we were given a specific alignment to export, rather than
650 // the one in the viewpanel
651 if (viewpanel == null || viewpanel.getAlignment() == null
652 || viewpanel.getAlignment() != alignment)
654 afile.setSeqs(alignment.getSequencesArray());
658 afile.setSeqs(viewpanel.getAlignment().getSequencesArray());
661 String afileresp = afile.print();
662 if (afile.hasWarningMessage())
664 System.err.println("Warning raised when writing as " + format
665 + " : " + afile.getWarningMessage());
668 } catch (Exception e)
670 System.err.println("Failed to write alignment as a '" + format
678 public static String checkProtocol(String file)
680 String protocol = FILE;
681 String ft = file.toLowerCase().trim();
682 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
683 || ft.indexOf("file:") == 0)
690 public static void main(String[] args)
693 while (i < args.length)
695 File f = new File(args[i]);
700 System.out.println("Reading file: " + f);
701 AppletFormatAdapter afa = new AppletFormatAdapter();
702 Runtime r = Runtime.getRuntime();
704 long memf = -r.totalMemory() + r.freeMemory();
705 long t1 = -System.currentTimeMillis();
706 AlignmentI al = afa.readFile(args[i], FILE,
707 new IdentifyFile().identify(args[i], FILE));
708 t1 += System.currentTimeMillis();
710 memf += r.totalMemory() - r.freeMemory();
713 System.out.println("Alignment contains " + al.getHeight()
714 + " sequences and " + al.getWidth() + " columns.");
717 System.out.println(new AppletFormatAdapter().formatSequences(
719 } catch (Exception e)
722 .println("Couln't format the alignment for output as a FASTA file.");
723 e.printStackTrace(System.err);
728 System.out.println("Couldn't read alignment");
730 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
732 .println("Difference between free memory now and before is "
733 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
734 } catch (Exception e)
736 System.err.println("Exception when dealing with " + i
737 + "'th argument: " + args[i] + "\n" + e);
742 System.err.println("Ignoring argument '" + args[i] + "' (" + i
743 + "'th)- not a readable file.");
750 * try to discover how to access the given file as a valid datasource that
751 * will be identified as the given type.
755 * @return protocol that yields the data parsable as the given type
757 public static String resolveProtocol(String file, String format)
759 return resolveProtocol(file, format, false);
762 public static String resolveProtocol(String file, String format,
765 // TODO: test thoroughly!
766 String protocol = null;
769 System.out.println("resolving datasource started with:\n>>file\n"
770 + file + ">>endfile");
773 // This might throw a security exception in certain browsers
774 // Netscape Communicator for instance.
778 InputStream is = System.getSecurityManager().getClass()
779 .getResourceAsStream("/" + file);
787 System.err.println("Resource '" + file + "' was "
788 + (rtn ? "" : "not") + " located by classloader.");
793 protocol = AppletFormatAdapter.CLASSLOADER;
796 } catch (Exception ex)
799 .println("Exception checking resources: " + file + " " + ex);
802 if (file.indexOf("://") > -1)
804 protocol = AppletFormatAdapter.URL;
808 // skipping codebase prepend check.
809 protocol = AppletFormatAdapter.FILE;
816 System.out.println("Trying to get contents of resource as "
819 fp = new FileParse(file, protocol);
828 System.out.println("Successful.");
831 } catch (Exception e)
835 System.err.println("Exception when accessing content: " + e);
843 System.out.println("Accessing as paste.");
845 protocol = AppletFormatAdapter.PASTE;
849 fp = new FileParse(file, protocol);
854 } catch (Exception e)
856 System.err.println("Failed to access content as paste!");
865 if (format == null || format.length() == 0)
873 String idformat = new jalview.io.IdentifyFile().identify(file,
875 if (idformat == null)
879 System.out.println("Format not identified. Inaccessible file.");
885 System.out.println("Format identified as " + idformat
886 + "and expected as " + format);
888 if (idformat.equals(format))
892 System.out.println("Protocol identified as " + protocol);
901 .println("File deemed not accessible via " + protocol);
906 } catch (Exception e)
910 System.err.println("File deemed not accessible via " + protocol);
920 public AlignFile getAlignFile()
925 public void setAlignFile(AlignFile alignFile)
927 this.alignFile = alignFile;