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.StructureViewSettings;
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 = false;
286 StructureViewSettings.addSettings(annotFromStructure,
287 localSecondaryStruct, serviceSecondaryStruct);
288 alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
289 localSecondaryStruct, serviceSecondaryStruct, inFile,
294 StructureViewSettings.setShowSeqFeatures(true);
295 alignFile = new MCview.PDBfile(annotFromStructure,
296 localSecondaryStruct, serviceSecondaryStruct, inFile,
300 else if (format.equals("mmCIF"))
302 StructureViewSettings.addSettings(annotFromStructure,
303 localSecondaryStruct, serviceSecondaryStruct);
304 alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
305 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
307 else if (format.equals("STH"))
309 alignFile = new StockholmFile(inFile, type);
311 else if (format.equals("SimpleBLAST"))
313 alignFile = new SimpleBlastFile(inFile, type);
315 else if (format.equals(PhylipFile.FILE_DESC))
317 alignFile = new PhylipFile(inFile, type);
319 else if (format.equals(JSONFile.FILE_DESC))
321 alignFile = new JSONFile(inFile, type);
323 else if (format.equals(HtmlFile.FILE_DESC))
325 alignFile = new HtmlFile(inFile, type);
327 else if (format.equals("RNAML"))
329 alignFile = new RnamlFile(inFile, type);
331 else if (format.equals(IdentifyFile.FeaturesFile))
333 alignFile = new FeaturesFile(inFile, type);
335 return buildAlignmentFrom(alignFile);
336 } catch (Exception e)
339 System.err.println("Failed to read alignment using the '" + format
340 + "' reader.\n" + e);
342 if (e.getMessage() != null
343 && e.getMessage().startsWith(INVALID_CHARACTERS))
345 throw new java.io.IOException(e.getMessage());
348 // Finally test if the user has pasted just the sequence, no id
349 if (type.equalsIgnoreCase("Paste"))
353 // Possible sequence is just residues with no label
354 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
355 return buildAlignmentFrom(alignFile);
357 } catch (Exception ex)
359 if (ex.toString().startsWith(INVALID_CHARACTERS))
361 throw new java.io.IOException(e.getMessage());
364 ex.printStackTrace();
367 if (format.equalsIgnoreCase("HTML"))
369 throw new IOException(e.getMessage());
371 // If we get to this stage, the format was not supported
372 throw new java.io.IOException(SUPPORTED_FORMATS);
377 * Constructs the correct filetype parser for an already open datasource
380 * an existing datasource
382 * File format of data that will be provided by datasource
384 * @return DOCUMENT ME!
386 public AlignmentI readFromFile(FileParse source, String format)
387 throws java.io.IOException
389 // TODO: generalise mapping between format string and io. class instances
390 // using Constructor.invoke reflection
391 // This is exactly the same as the readFile method except we substitute
392 // 'inFile, type' with 'source'
393 this.inFile = source.getInFile();
394 String type = source.type;
397 if (format.equals("FASTA"))
399 alignFile = new FastaFile(source);
401 else if (format.equals("MSF"))
403 alignFile = new MSFfile(source);
405 else if (format.equals("PileUp"))
407 alignFile = new PileUpfile(source);
409 else if (format.equals("CLUSTAL"))
411 alignFile = new ClustalFile(source);
413 else if (format.equals("BLC"))
415 alignFile = new BLCFile(source);
417 else if (format.equals("PIR"))
419 alignFile = new PIRFile(source);
421 else if (format.equals("PFAM"))
423 alignFile = new PfamFile(source);
425 else if (format.equals("JnetFile"))
427 alignFile = new JPredFile(source);
428 ((JPredFile) alignFile).removeNonSequences();
430 else if (format.equals("PDB"))
432 // TODO obtain config value from preference settings
433 boolean isParseWithJMOL = false;
436 StructureViewSettings.addSettings(annotFromStructure,
437 localSecondaryStruct, serviceSecondaryStruct);
438 alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
439 localSecondaryStruct, serviceSecondaryStruct, source);
443 StructureViewSettings.setShowSeqFeatures(true);
444 alignFile = new MCview.PDBfile(annotFromStructure,
445 localSecondaryStruct, serviceSecondaryStruct, source);
448 else if (format.equals("mmCIF"))
450 StructureViewSettings.addSettings(annotFromStructure,
451 localSecondaryStruct, serviceSecondaryStruct);
452 alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
453 localSecondaryStruct, serviceSecondaryStruct, source);
455 else if (format.equals("STH"))
457 alignFile = new StockholmFile(source);
459 else if (format.equals("RNAML"))
461 alignFile = new RnamlFile(source);
463 else if (format.equals("SimpleBLAST"))
465 alignFile = new SimpleBlastFile(source);
467 else if (format.equals(PhylipFile.FILE_DESC))
469 alignFile = new PhylipFile(source);
471 else if (format.equals(IdentifyFile.FeaturesFile))
473 alignFile = new FeaturesFile(inFile, type);
475 else if (format.equals(JSONFile.FILE_DESC))
477 alignFile = new JSONFile(source);
479 else if (format.equals(HtmlFile.FILE_DESC))
481 alignFile = new HtmlFile(source);
484 return buildAlignmentFrom(alignFile);
486 } catch (Exception e)
489 System.err.println("Failed to read alignment using the '" + format
490 + "' reader.\n" + e);
492 if (e.getMessage() != null
493 && e.getMessage().startsWith(INVALID_CHARACTERS))
495 throw new java.io.IOException(e.getMessage());
498 // Finally test if the user has pasted just the sequence, no id
499 if (type.equalsIgnoreCase("Paste"))
503 // Possible sequence is just residues with no label
504 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
505 return buildAlignmentFrom(alignFile);
507 } catch (Exception ex)
509 if (ex.toString().startsWith(INVALID_CHARACTERS))
511 throw new java.io.IOException(e.getMessage());
514 ex.printStackTrace();
518 // If we get to this stage, the format was not supported
519 throw new java.io.IOException(SUPPORTED_FORMATS);
524 * boilerplate method to handle data from an AlignFile and construct a new
525 * alignment or import to an existing alignment
528 * @return AlignmentI instance ready to pass to a UI constructor
530 private AlignmentI buildAlignmentFrom(AlignFile alignFile2)
532 // Standard boilerplate for creating alignment from parser
533 // alignFile.configureForView(viewpanel);
535 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
537 alignFile.addAnnotations(al);
539 alignFile.addGroups(al);
545 * create an alignment flatfile from a Jalview alignment view
550 * @param selectedOnly
551 * @return flatfile in a string
553 public String formatSequences(String format, boolean jvsuffix,
554 AlignmentViewPanel ap, boolean selectedOnly)
557 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
558 selectedOnly, false);
559 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
561 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
562 .getVisibleAlignmentAnnotation(selectedOnly));
565 for (AlignmentAnnotation aa : ala)
567 aselview.addAnnotation(aa);
571 return formatSequences(format, aselview, jvsuffix);
575 * Construct an output class for an alignment in a particular filetype TODO:
576 * allow caller to detect errors and warnings encountered when generating
580 * string name of alignment format
582 * the alignment to be written out
584 * passed to AlnFile class controls whether /START-END is added to
587 * @return alignment flat file contents
589 public String formatSequences(String format, AlignmentI alignment,
594 AlignFile afile = null;
595 if (format.equalsIgnoreCase("FASTA"))
597 afile = new FastaFile();
599 else if (format.equalsIgnoreCase("MSF"))
601 afile = new MSFfile();
603 else if (format.equalsIgnoreCase("PileUp"))
605 afile = new PileUpfile();
607 else if (format.equalsIgnoreCase("CLUSTAL"))
609 afile = new ClustalFile();
611 else if (format.equalsIgnoreCase("BLC"))
613 afile = new BLCFile();
615 else if (format.equalsIgnoreCase("PIR"))
617 afile = new PIRFile();
619 else if (format.equalsIgnoreCase("PFAM"))
621 afile = new PfamFile();
623 else if (format.equalsIgnoreCase("STH"))
625 afile = new StockholmFile(alignment);
627 else if (format.equalsIgnoreCase("AMSA"))
629 afile = new AMSAFile(alignment);
631 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
633 afile = new PhylipFile();
635 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
637 afile = new JSONFile();
639 else if (format.equalsIgnoreCase("RNAML"))
641 afile = new RnamlFile();
648 .getString("error.implementation_error_unknown_file_format_string"));
651 afile.setNewlineString(newline);
652 afile.addJVSuffix(jvsuffix);
653 afile.setExportSettings(exportSettings);
654 afile.configureForView(viewpanel);
656 // check whether we were given a specific alignment to export, rather than
657 // the one in the viewpanel
658 if (viewpanel == null || viewpanel.getAlignment() == null
659 || viewpanel.getAlignment() != alignment)
661 afile.setSeqs(alignment.getSequencesArray());
665 afile.setSeqs(viewpanel.getAlignment().getSequencesArray());
668 String afileresp = afile.print();
669 if (afile.hasWarningMessage())
671 System.err.println("Warning raised when writing as " + format
672 + " : " + afile.getWarningMessage());
675 } catch (Exception e)
677 System.err.println("Failed to write alignment as a '" + format
685 public static String checkProtocol(String file)
687 String protocol = FILE;
688 String ft = file.toLowerCase().trim();
689 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
690 || ft.indexOf("file:") == 0)
697 public static void main(String[] args)
700 while (i < args.length)
702 File f = new File(args[i]);
707 System.out.println("Reading file: " + f);
708 AppletFormatAdapter afa = new AppletFormatAdapter();
709 Runtime r = Runtime.getRuntime();
711 long memf = -r.totalMemory() + r.freeMemory();
712 long t1 = -System.currentTimeMillis();
713 AlignmentI al = afa.readFile(args[i], FILE,
714 new IdentifyFile().identify(args[i], FILE));
715 t1 += System.currentTimeMillis();
717 memf += r.totalMemory() - r.freeMemory();
720 System.out.println("Alignment contains " + al.getHeight()
721 + " sequences and " + al.getWidth() + " columns.");
724 System.out.println(new AppletFormatAdapter().formatSequences(
726 } catch (Exception e)
729 .println("Couln't format the alignment for output as a FASTA file.");
730 e.printStackTrace(System.err);
735 System.out.println("Couldn't read alignment");
737 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
739 .println("Difference between free memory now and before is "
740 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
741 } catch (Exception e)
743 System.err.println("Exception when dealing with " + i
744 + "'th argument: " + args[i] + "\n" + e);
749 System.err.println("Ignoring argument '" + args[i] + "' (" + i
750 + "'th)- not a readable file.");
757 * try to discover how to access the given file as a valid datasource that
758 * will be identified as the given type.
762 * @return protocol that yields the data parsable as the given type
764 public static String resolveProtocol(String file, String format)
766 return resolveProtocol(file, format, false);
769 public static String resolveProtocol(String file, String format,
772 // TODO: test thoroughly!
773 String protocol = null;
776 System.out.println("resolving datasource started with:\n>>file\n"
777 + file + ">>endfile");
780 // This might throw a security exception in certain browsers
781 // Netscape Communicator for instance.
785 InputStream is = System.getSecurityManager().getClass()
786 .getResourceAsStream("/" + file);
794 System.err.println("Resource '" + file + "' was "
795 + (rtn ? "" : "not") + " located by classloader.");
800 protocol = AppletFormatAdapter.CLASSLOADER;
803 } catch (Exception ex)
806 .println("Exception checking resources: " + file + " " + ex);
809 if (file.indexOf("://") > -1)
811 protocol = AppletFormatAdapter.URL;
815 // skipping codebase prepend check.
816 protocol = AppletFormatAdapter.FILE;
823 System.out.println("Trying to get contents of resource as "
826 fp = new FileParse(file, protocol);
835 System.out.println("Successful.");
838 } catch (Exception e)
842 System.err.println("Exception when accessing content: " + e);
850 System.out.println("Accessing as paste.");
852 protocol = AppletFormatAdapter.PASTE;
856 fp = new FileParse(file, protocol);
861 } catch (Exception e)
863 System.err.println("Failed to access content as paste!");
872 if (format == null || format.length() == 0)
880 String idformat = new jalview.io.IdentifyFile().identify(file,
882 if (idformat == null)
886 System.out.println("Format not identified. Inaccessible file.");
892 System.out.println("Format identified as " + idformat
893 + "and expected as " + format);
895 if (idformat.equals(format))
899 System.out.println("Protocol identified as " + protocol);
908 .println("File deemed not accessible via " + protocol);
913 } catch (Exception e)
917 System.err.println("File deemed not accessible via " + protocol);
927 public AlignFile getAlignFile()
932 public void setAlignFile(AlignFile alignFile)
934 this.alignFile = alignFile;