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.structure.StructureImportSettings;
30 import jalview.util.MessageManager;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.util.List;
38 * A low level class for alignment and feature IO with alignment formatting
39 * methods used by both applet and application for generating flat alignment
40 * files. It also holds the lists of magic format names that the applet and
41 * application will allow the user to read or write files with.
46 public class AppletFormatAdapter
48 private AlignmentViewPanel viewpanel;
50 public static String FILE = "File";
52 public static String URL = "URL";
54 public static String PASTE = "Paste";
56 public static String CLASSLOADER = "ClassLoader";
59 * add jalview-derived non-secondary structure annotation from PDB structure
61 boolean annotFromStructure = false;
64 * add secondary structure from PDB data with built-in algorithms
66 boolean localSecondaryStruct = false;
69 * process PDB data with web services
71 boolean serviceSecondaryStruct = false;
73 private AlignFile alignFile = null;
78 * character used to write newlines
80 protected String newline = System.getProperty("line.separator");
82 private AlignExportSettingI exportSettings;
85 * List of valid format strings used in the isValidFormat method
87 public static final String[] READABLE_FORMATS = new String[] { "BLC",
88 "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH", "PDB",
89 "JnetFile", "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC,
90 IdentifyFile.FeaturesFile, "HTML", "mmCIF" };
93 * List of readable format file extensions by application in order
94 * corresponding to READABLE_FNAMES
96 public static final String[] READABLE_EXTENSIONS = new String[] {
97 "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
98 "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT, JSONFile.FILE_EXT,
99 ".gff2,gff3", "jar,jvp", HtmlFile.FILE_EXT, "cif" };
102 * List of readable formats by application in order corresponding to
103 * READABLE_EXTENSIONS
105 public static final String[] READABLE_FNAMES = new String[] { "Fasta",
106 "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm", "RNAML",
107 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.FeaturesFile,
108 "Jalview", HtmlFile.FILE_DESC, "mmCIF" };
111 * List of valid format strings for use by callers of the formatSequences
114 public static final String[] WRITEABLE_FORMATS = new String[] { "BLC",
115 "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA", "STH",
116 PhylipFile.FILE_DESC, JSONFile.FILE_DESC };
119 * List of extensions corresponding to file format types in WRITABLE_FNAMES
120 * that are writable by the application.
122 public static final String[] WRITABLE_EXTENSIONS = new String[] {
123 "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
124 "sto,stk", PhylipFile.FILE_EXT, JSONFile.FILE_EXT, "jvp" };
127 * List of writable formats by the application. Order must correspond with the
128 * WRITABLE_EXTENSIONS list of formats.
130 public static final String[] WRITABLE_FNAMES = new String[] { "Fasta",
131 "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
132 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, "Jalview" };
134 public static String INVALID_CHARACTERS = "Contains invalid characters";
136 // TODO: make these messages dynamic
137 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
138 + prettyPrint(READABLE_FORMATS);
140 public AppletFormatAdapter()
144 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
146 this.viewpanel = viewpanel;
149 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
150 AlignExportSettingI settings)
152 viewpanel = alignPanel;
153 exportSettings = settings;
159 * @return grammatically correct(ish) list consisting of els elements.
161 public static String prettyPrint(String[] els)
163 StringBuffer list = new StringBuffer();
164 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
169 list.append(" and " + els[els.length - 1] + ".");
170 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 // TODO obtain config value from preference settings.
282 // Set value to 'true' to test PDB processing with Jmol: JAL-1213
283 boolean isParseWithJMOL = StructureImportSettings
284 .getDefaultPDBFileParser().equalsIgnoreCase(
285 StructureImportSettings.JMOL_PARSER);
288 StructureImportSettings.addSettings(annotFromStructure,
289 localSecondaryStruct, serviceSecondaryStruct);
290 alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
291 localSecondaryStruct, serviceSecondaryStruct, inFile,
296 StructureImportSettings.addSettings(annotFromStructure,
297 localSecondaryStruct, serviceSecondaryStruct);
298 StructureImportSettings.setShowSeqFeatures(true);
299 alignFile = new MCview.PDBfile(annotFromStructure,
300 localSecondaryStruct, serviceSecondaryStruct, inFile,
303 ((StructureFile) alignFile).setDbRefType(format);
305 else if (format.equals("mmCIF"))
307 StructureImportSettings.addSettings(annotFromStructure,
308 localSecondaryStruct, serviceSecondaryStruct);
309 alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
310 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
311 ((StructureFile) alignFile).setDbRefType(format);
313 else if (format.equals("STH"))
315 alignFile = new StockholmFile(inFile, type);
317 else if (format.equals("SimpleBLAST"))
319 alignFile = new SimpleBlastFile(inFile, type);
321 else if (format.equals(PhylipFile.FILE_DESC))
323 alignFile = new PhylipFile(inFile, type);
325 else if (format.equals(JSONFile.FILE_DESC))
327 alignFile = new JSONFile(inFile, type);
329 else if (format.equals(HtmlFile.FILE_DESC))
331 alignFile = new HtmlFile(inFile, type);
333 else if (format.equals("RNAML"))
335 alignFile = new RnamlFile(inFile, type);
337 else if (format.equals(IdentifyFile.FeaturesFile))
339 alignFile = new FeaturesFile(true, inFile, type);
341 return buildAlignmentFrom(alignFile);
342 } catch (Exception e)
345 System.err.println("Failed to read alignment using the '" + format
346 + "' reader.\n" + e);
348 if (e.getMessage() != null
349 && e.getMessage().startsWith(INVALID_CHARACTERS))
351 throw new java.io.IOException(e.getMessage());
354 // Finally test if the user has pasted just the sequence, no id
355 if (type.equalsIgnoreCase("Paste"))
359 // Possible sequence is just residues with no label
360 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
361 return buildAlignmentFrom(alignFile);
363 } catch (Exception ex)
365 if (ex.toString().startsWith(INVALID_CHARACTERS))
367 throw new java.io.IOException(e.getMessage());
370 ex.printStackTrace();
373 if (format.equalsIgnoreCase("HTML"))
375 throw new IOException(e.getMessage());
377 // If we get to this stage, the format was not supported
378 throw new java.io.IOException(SUPPORTED_FORMATS);
383 * Constructs the correct filetype parser for an already open datasource
386 * an existing datasource
388 * File format of data that will be provided by datasource
390 * @return DOCUMENT ME!
392 public AlignmentI readFromFile(FileParse source, String format)
393 throws java.io.IOException
395 // TODO: generalise mapping between format string and io. class instances
396 // using Constructor.invoke reflection
397 // This is exactly the same as the readFile method except we substitute
398 // 'inFile, type' with 'source'
399 this.inFile = source.getInFile();
400 String type = source.type;
403 if (format.equals("FASTA"))
405 alignFile = new FastaFile(source);
407 else if (format.equals("MSF"))
409 alignFile = new MSFfile(source);
411 else if (format.equals("PileUp"))
413 alignFile = new PileUpfile(source);
415 else if (format.equals("CLUSTAL"))
417 alignFile = new ClustalFile(source);
419 else if (format.equals("BLC"))
421 alignFile = new BLCFile(source);
423 else if (format.equals("PIR"))
425 alignFile = new PIRFile(source);
427 else if (format.equals("PFAM"))
429 alignFile = new PfamFile(source);
431 else if (format.equals("JnetFile"))
433 alignFile = new JPredFile(source);
434 ((JPredFile) alignFile).removeNonSequences();
436 else if (format.equals("PDB"))
438 // TODO obtain config value from preference settings
439 boolean isParseWithJMOL = false;
442 StructureImportSettings.addSettings(annotFromStructure,
443 localSecondaryStruct, serviceSecondaryStruct);
444 alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
445 localSecondaryStruct, serviceSecondaryStruct, source);
449 StructureImportSettings.setShowSeqFeatures(true);
450 alignFile = new MCview.PDBfile(annotFromStructure,
451 localSecondaryStruct, serviceSecondaryStruct, source);
453 ((StructureFile) alignFile)
454 .setDbRefType(StructureImportSettings.PDB);
456 else if (format.equals("mmCIF"))
458 StructureImportSettings.addSettings(annotFromStructure,
459 localSecondaryStruct, serviceSecondaryStruct);
460 alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
461 localSecondaryStruct, serviceSecondaryStruct, source);
462 ((StructureFile) alignFile)
463 .setDbRefType(StructureImportSettings.MMCIF);
465 else if (format.equals("STH"))
467 alignFile = new StockholmFile(source);
469 else if (format.equals("RNAML"))
471 alignFile = new RnamlFile(source);
473 else if (format.equals("SimpleBLAST"))
475 alignFile = new SimpleBlastFile(source);
477 else if (format.equals(PhylipFile.FILE_DESC))
479 alignFile = new PhylipFile(source);
481 else if (format.equals(IdentifyFile.FeaturesFile))
483 alignFile = new FeaturesFile(inFile, type);
485 else if (format.equals(JSONFile.FILE_DESC))
487 alignFile = new JSONFile(source);
489 else if (format.equals(HtmlFile.FILE_DESC))
491 alignFile = new HtmlFile(source);
494 return buildAlignmentFrom(alignFile);
496 } catch (Exception e)
499 System.err.println("Failed to read alignment using the '" + format
500 + "' reader.\n" + e);
502 if (e.getMessage() != null
503 && e.getMessage().startsWith(INVALID_CHARACTERS))
505 throw new java.io.IOException(e.getMessage());
508 // Finally test if the user has pasted just the sequence, no id
509 if (type.equalsIgnoreCase("Paste"))
513 // Possible sequence is just residues with no label
514 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
515 return buildAlignmentFrom(alignFile);
517 } catch (Exception ex)
519 if (ex.toString().startsWith(INVALID_CHARACTERS))
521 throw new java.io.IOException(e.getMessage());
524 ex.printStackTrace();
528 // If we get to this stage, the format was not supported
529 throw new java.io.IOException(SUPPORTED_FORMATS);
534 * boilerplate method to handle data from an AlignFile and construct a new
535 * alignment or import to an existing alignment
538 * @return AlignmentI instance ready to pass to a UI constructor
540 private AlignmentI buildAlignmentFrom(AlignFile alignFile2)
542 // Standard boilerplate for creating alignment from parser
543 // alignFile.configureForView(viewpanel);
545 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
547 alignFile.addAnnotations(al);
549 alignFile.addGroups(al);
555 * create an alignment flatfile from a Jalview alignment view
560 * @param selectedOnly
561 * @return flatfile in a string
563 public String formatSequences(String format, boolean jvsuffix,
564 AlignmentViewPanel ap, boolean selectedOnly)
567 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
568 selectedOnly, false);
569 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
571 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
572 .getVisibleAlignmentAnnotation(selectedOnly));
575 for (AlignmentAnnotation aa : ala)
577 aselview.addAnnotation(aa);
581 return formatSequences(format, aselview, jvsuffix);
585 * Construct an output class for an alignment in a particular filetype TODO:
586 * allow caller to detect errors and warnings encountered when generating
590 * string name of alignment format
592 * the alignment to be written out
594 * passed to AlnFile class controls whether /START-END is added to
597 * @return alignment flat file contents
599 public String formatSequences(String format, AlignmentI alignment,
604 AlignFile afile = null;
605 if (format.equalsIgnoreCase("FASTA"))
607 afile = new FastaFile();
609 else if (format.equalsIgnoreCase("MSF"))
611 afile = new MSFfile();
613 else if (format.equalsIgnoreCase("PileUp"))
615 afile = new PileUpfile();
617 else if (format.equalsIgnoreCase("CLUSTAL"))
619 afile = new ClustalFile();
621 else if (format.equalsIgnoreCase("BLC"))
623 afile = new BLCFile();
625 else if (format.equalsIgnoreCase("PIR"))
627 afile = new PIRFile();
629 else if (format.equalsIgnoreCase("PFAM"))
631 afile = new PfamFile();
633 else if (format.equalsIgnoreCase("STH"))
635 afile = new StockholmFile(alignment);
637 else if (format.equalsIgnoreCase("AMSA"))
639 afile = new AMSAFile(alignment);
641 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
643 afile = new PhylipFile();
645 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
647 afile = new JSONFile();
649 else if (format.equalsIgnoreCase("RNAML"))
651 afile = new RnamlFile();
658 .getString("error.implementation_error_unknown_file_format_string"));
661 afile.setNewlineString(newline);
662 afile.addJVSuffix(jvsuffix);
663 afile.setExportSettings(exportSettings);
664 afile.configureForView(viewpanel);
666 // check whether we were given a specific alignment to export, rather than
667 // the one in the viewpanel
668 if (viewpanel == null || viewpanel.getAlignment() == null
669 || viewpanel.getAlignment() != alignment)
671 afile.setSeqs(alignment.getSequencesArray());
675 afile.setSeqs(viewpanel.getAlignment().getSequencesArray());
678 String afileresp = afile.print();
679 if (afile.hasWarningMessage())
681 System.err.println("Warning raised when writing as " + format
682 + " : " + afile.getWarningMessage());
685 } catch (Exception e)
687 System.err.println("Failed to write alignment as a '" + format
695 public static String checkProtocol(String file)
697 String protocol = FILE;
698 String ft = file.toLowerCase().trim();
699 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
700 || ft.indexOf("file:") == 0)
707 public static void main(String[] args)
710 while (i < args.length)
712 File f = new File(args[i]);
717 System.out.println("Reading file: " + f);
718 AppletFormatAdapter afa = new AppletFormatAdapter();
719 Runtime r = Runtime.getRuntime();
721 long memf = -r.totalMemory() + r.freeMemory();
722 long t1 = -System.currentTimeMillis();
723 AlignmentI al = afa.readFile(args[i], FILE,
724 new IdentifyFile().identify(args[i], FILE));
725 t1 += System.currentTimeMillis();
727 memf += r.totalMemory() - r.freeMemory();
730 System.out.println("Alignment contains " + al.getHeight()
731 + " sequences and " + al.getWidth() + " columns.");
734 System.out.println(new AppletFormatAdapter().formatSequences(
736 } catch (Exception e)
739 .println("Couln't format the alignment for output as a FASTA file.");
740 e.printStackTrace(System.err);
745 System.out.println("Couldn't read alignment");
747 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
749 .println("Difference between free memory now and before is "
750 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
751 } catch (Exception e)
753 System.err.println("Exception when dealing with " + i
754 + "'th argument: " + args[i] + "\n" + e);
759 System.err.println("Ignoring argument '" + args[i] + "' (" + i
760 + "'th)- not a readable file.");
767 * try to discover how to access the given file as a valid datasource that
768 * will be identified as the given type.
772 * @return protocol that yields the data parsable as the given type
774 public static String resolveProtocol(String file, String format)
776 return resolveProtocol(file, format, false);
779 public static String resolveProtocol(String file, String format,
782 // TODO: test thoroughly!
783 String protocol = null;
786 System.out.println("resolving datasource started with:\n>>file\n"
787 + file + ">>endfile");
790 // This might throw a security exception in certain browsers
791 // Netscape Communicator for instance.
795 InputStream is = System.getSecurityManager().getClass()
796 .getResourceAsStream("/" + file);
804 System.err.println("Resource '" + file + "' was "
805 + (rtn ? "" : "not") + " located by classloader.");
810 protocol = AppletFormatAdapter.CLASSLOADER;
813 } catch (Exception ex)
816 .println("Exception checking resources: " + file + " " + ex);
819 if (file.indexOf("://") > -1)
821 protocol = AppletFormatAdapter.URL;
825 // skipping codebase prepend check.
826 protocol = AppletFormatAdapter.FILE;
833 System.out.println("Trying to get contents of resource as "
836 fp = new FileParse(file, protocol);
845 System.out.println("Successful.");
848 } catch (Exception e)
852 System.err.println("Exception when accessing content: " + e);
860 System.out.println("Accessing as paste.");
862 protocol = AppletFormatAdapter.PASTE;
866 fp = new FileParse(file, protocol);
871 } catch (Exception e)
873 System.err.println("Failed to access content as paste!");
882 if (format == null || format.length() == 0)
890 String idformat = new jalview.io.IdentifyFile().identify(file,
892 if (idformat == null)
896 System.out.println("Format not identified. Inaccessible file.");
902 System.out.println("Format identified as " + idformat
903 + "and expected as " + format);
905 if (idformat.equals(format))
909 System.out.println("Protocol identified as " + protocol);
918 .println("File deemed not accessible via " + protocol);
923 } catch (Exception e)
927 System.err.println("File deemed not accessible via " + protocol);
937 public AlignFile getAlignFile()
942 public void setAlignFile(AlignFile alignFile)
944 this.alignFile = alignFile;