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.ext.jmol.JmolParser;
31 import jalview.structure.StructureImportSettings;
32 import jalview.util.MessageManager;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.util.List;
40 * A low level class for alignment and feature IO with alignment formatting
41 * methods used by both applet and application for generating flat alignment
42 * files. It also holds the lists of magic format names that the applet and
43 * application will allow the user to read or write files with.
48 public class AppletFormatAdapter
50 private AlignmentViewPanel viewpanel;
52 public static String FILE = "File";
54 public static String URL = "URL";
56 public static String PASTE = "Paste";
58 public static String CLASSLOADER = "ClassLoader";
61 * add jalview-derived non-secondary structure annotation from PDB structure
63 boolean annotFromStructure = false;
66 * add secondary structure from PDB data with built-in algorithms
68 boolean localSecondaryStruct = false;
71 * process PDB data with web services
73 boolean serviceSecondaryStruct = false;
75 private AlignFile alignFile = null;
80 * character used to write newlines
82 protected String newline = System.getProperty("line.separator");
84 private AlignExportSettingI exportSettings;
87 * List of valid format strings used in the isValidFormat method
89 public static final String[] READABLE_FORMATS = new String[] { "BLC",
90 "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH", "PDB",
91 "JnetFile", "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC,
92 IdentifyFile.FeaturesFile, "HTML", "mmCIF" };
95 * List of readable format file extensions by application in order
96 * corresponding to READABLE_FNAMES
98 public static final String[] READABLE_EXTENSIONS = new String[] {
99 "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
100 "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT, JSONFile.FILE_EXT,
101 ".gff2,gff3", "jar,jvp", HtmlFile.FILE_EXT, "cif" };
104 * List of readable formats by application in order corresponding to
105 * READABLE_EXTENSIONS
107 public static final String[] READABLE_FNAMES = new String[] { "Fasta",
108 "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm", "RNAML",
109 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.FeaturesFile,
110 "Jalview", HtmlFile.FILE_DESC, "mmCIF" };
113 * List of valid format strings for use by callers of the formatSequences
116 public static final String[] WRITEABLE_FORMATS = new String[] { "BLC",
117 "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA", "STH",
118 PhylipFile.FILE_DESC, JSONFile.FILE_DESC };
121 * List of extensions corresponding to file format types in WRITABLE_FNAMES
122 * that are writable by the application.
124 public static final String[] WRITABLE_EXTENSIONS = new String[] {
125 "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
126 "sto,stk", PhylipFile.FILE_EXT, JSONFile.FILE_EXT, "jvp" };
129 * List of writable formats by the application. Order must correspond with the
130 * WRITABLE_EXTENSIONS list of formats.
132 public static final String[] WRITABLE_FNAMES = new String[] { "Fasta",
133 "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
134 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, "Jalview" };
136 public static String INVALID_CHARACTERS = "Contains invalid characters";
138 // TODO: make these messages dynamic
139 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
140 + prettyPrint(READABLE_FORMATS);
142 public AppletFormatAdapter()
146 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
148 this.viewpanel = viewpanel;
151 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
152 AlignExportSettingI settings)
154 viewpanel = alignPanel;
155 exportSettings = settings;
161 * @return grammatically correct(ish) list consisting of els elements.
163 public static String prettyPrint(String[] els)
165 StringBuffer list = new StringBuffer();
166 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
171 list.append(" and " + els[els.length - 1] + ".");
172 return list.toString();
175 public void setNewlineString(String nl)
180 public String getNewlineString()
186 * check that this format is valid for reading
189 * a format string to be compared with READABLE_FORMATS
190 * @return true if format is readable
192 public static final boolean isValidFormat(String format)
194 return isValidFormat(format, false);
198 * validate format is valid for IO
201 * a format string to be compared with either READABLE_FORMATS or
204 * when true, format is checked for containment in WRITEABLE_FORMATS
205 * @return true if format is valid
207 public static final boolean isValidFormat(String format,
214 boolean valid = false;
215 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
217 for (String element : format_list)
219 if (element.equalsIgnoreCase(format))
229 * Constructs the correct filetype parser for a characterised datasource
236 * File format of data provided by datasource
238 * @return DOCUMENT ME!
240 public AlignmentI readFile(String inFile, String type, String format)
241 throws java.io.IOException
243 // TODO: generalise mapping between format string and io. class instances
244 // using Constructor.invoke reflection
245 this.inFile = inFile;
248 if (format.equals("FASTA"))
250 alignFile = new FastaFile(inFile, type);
252 else if (format.equals("MSF"))
254 alignFile = new MSFfile(inFile, type);
256 else if (format.equals("PileUp"))
258 alignFile = new PileUpfile(inFile, type);
260 else if (format.equals("CLUSTAL"))
262 alignFile = new ClustalFile(inFile, type);
264 else if (format.equals("BLC"))
266 alignFile = new BLCFile(inFile, type);
268 else if (format.equals("PIR"))
270 alignFile = new PIRFile(inFile, type);
272 else if (format.equals("PFAM"))
274 alignFile = new PfamFile(inFile, type);
276 else if (format.equals("JnetFile"))
278 alignFile = new JPredFile(inFile, type);
279 ((JPredFile) alignFile).removeNonSequences();
281 else if (format.equals("PDB") || format.equalsIgnoreCase("mmCIF"))
283 StructureImportSettings.addSettings(annotFromStructure,
284 localSecondaryStruct, serviceSecondaryStruct);
285 alignFile = new JmolParser(inFile, type);
286 ((StructureFile) alignFile).setDbRefType(format);
288 else if (format.equals("STH"))
290 alignFile = new StockholmFile(inFile, type);
292 else if (format.equals("SimpleBLAST"))
294 alignFile = new SimpleBlastFile(inFile, type);
296 else if (format.equals(PhylipFile.FILE_DESC))
298 alignFile = new PhylipFile(inFile, type);
300 else if (format.equals(JSONFile.FILE_DESC))
302 alignFile = new JSONFile(inFile, type);
304 else if (format.equals(HtmlFile.FILE_DESC))
306 alignFile = new HtmlFile(inFile, type);
308 else if (format.equals("RNAML"))
310 alignFile = new RnamlFile(inFile, type);
312 else if (format.equals(IdentifyFile.FeaturesFile))
314 alignFile = new FeaturesFile(true, inFile, type);
316 return buildAlignmentFrom(alignFile);
317 } catch (Exception e)
320 System.err.println("Failed to read alignment using the '" + format
321 + "' reader.\n" + e);
323 if (e.getMessage() != null
324 && e.getMessage().startsWith(INVALID_CHARACTERS))
326 throw new java.io.IOException(e.getMessage());
329 // Finally test if the user has pasted just the sequence, no id
330 if (type.equalsIgnoreCase("Paste"))
334 // Possible sequence is just residues with no label
335 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
336 return buildAlignmentFrom(alignFile);
338 } catch (Exception ex)
340 if (ex.toString().startsWith(INVALID_CHARACTERS))
342 throw new java.io.IOException(e.getMessage());
345 ex.printStackTrace();
348 if (format.equalsIgnoreCase("HTML"))
350 throw new IOException(e.getMessage());
352 // If we get to this stage, the format was not supported
353 throw new java.io.IOException(SUPPORTED_FORMATS);
358 * Constructs the correct filetype parser for an already open datasource
361 * an existing datasource
363 * File format of data that will be provided by datasource
365 * @return DOCUMENT ME!
367 public AlignmentI readFromFile(FileParse source, String format)
368 throws java.io.IOException
370 // TODO: generalise mapping between format string and io. class instances
371 // using Constructor.invoke reflection
372 // This is exactly the same as the readFile method except we substitute
373 // 'inFile, type' with 'source'
374 this.inFile = source.getInFile();
375 String type = source.type;
378 if (format.equals("FASTA"))
380 alignFile = new FastaFile(source);
382 else if (format.equals("MSF"))
384 alignFile = new MSFfile(source);
386 else if (format.equals("PileUp"))
388 alignFile = new PileUpfile(source);
390 else if (format.equals("CLUSTAL"))
392 alignFile = new ClustalFile(source);
394 else if (format.equals("BLC"))
396 alignFile = new BLCFile(source);
398 else if (format.equals("PIR"))
400 alignFile = new PIRFile(source);
402 else if (format.equals("PFAM"))
404 alignFile = new PfamFile(source);
406 else if (format.equals("JnetFile"))
408 alignFile = new JPredFile(source);
409 ((JPredFile) alignFile).removeNonSequences();
411 else if (format.equals("PDB"))
413 // TODO obtain config value from preference settings
414 boolean isParseWithJMOL = false;
417 StructureImportSettings.addSettings(annotFromStructure,
418 localSecondaryStruct, serviceSecondaryStruct);
419 alignFile = new JmolParser(source);
423 StructureImportSettings.setShowSeqFeatures(true);
424 alignFile = new MCview.PDBfile(annotFromStructure,
425 localSecondaryStruct, serviceSecondaryStruct, source);
427 ((StructureFile) alignFile).setDbRefType(Type.PDB);
429 else if (format.equalsIgnoreCase("mmCIF"))
431 StructureImportSettings.addSettings(annotFromStructure,
432 localSecondaryStruct, serviceSecondaryStruct);
433 alignFile = new JmolParser(source);
434 ((StructureFile) alignFile).setDbRefType(Type.MMCIF);
436 else if (format.equals("STH"))
438 alignFile = new StockholmFile(source);
440 else if (format.equals("RNAML"))
442 alignFile = new RnamlFile(source);
444 else if (format.equals("SimpleBLAST"))
446 alignFile = new SimpleBlastFile(source);
448 else if (format.equals(PhylipFile.FILE_DESC))
450 alignFile = new PhylipFile(source);
452 else if (format.equals(IdentifyFile.FeaturesFile))
454 alignFile = new FeaturesFile(inFile, type);
456 else if (format.equals(JSONFile.FILE_DESC))
458 alignFile = new JSONFile(source);
460 else if (format.equals(HtmlFile.FILE_DESC))
462 alignFile = new HtmlFile(source);
465 return buildAlignmentFrom(alignFile);
467 } catch (Exception e)
470 System.err.println("Failed to read alignment using the '" + format
471 + "' reader.\n" + e);
473 if (e.getMessage() != null
474 && e.getMessage().startsWith(INVALID_CHARACTERS))
476 throw new java.io.IOException(e.getMessage());
479 // Finally test if the user has pasted just the sequence, no id
480 if (type.equalsIgnoreCase("Paste"))
484 // Possible sequence is just residues with no label
485 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
486 return buildAlignmentFrom(alignFile);
488 } catch (Exception ex)
490 if (ex.toString().startsWith(INVALID_CHARACTERS))
492 throw new java.io.IOException(e.getMessage());
495 ex.printStackTrace();
499 // If we get to this stage, the format was not supported
500 throw new java.io.IOException(SUPPORTED_FORMATS);
505 * boilerplate method to handle data from an AlignFile and construct a new
506 * alignment or import to an existing alignment
509 * @return AlignmentI instance ready to pass to a UI constructor
511 private AlignmentI buildAlignmentFrom(AlignFile alignFile2)
513 // Standard boilerplate for creating alignment from parser
514 // alignFile.configureForView(viewpanel);
516 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
518 alignFile.addAnnotations(al);
520 alignFile.addGroups(al);
526 * create an alignment flatfile from a Jalview alignment view
531 * @param selectedOnly
532 * @return flatfile in a string
534 public String formatSequences(String format, boolean jvsuffix,
535 AlignmentViewPanel ap, boolean selectedOnly)
538 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
539 selectedOnly, false);
540 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
542 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
543 .getVisibleAlignmentAnnotation(selectedOnly));
546 for (AlignmentAnnotation aa : ala)
548 aselview.addAnnotation(aa);
552 return formatSequences(format, aselview, jvsuffix);
556 * Construct an output class for an alignment in a particular filetype TODO:
557 * allow caller to detect errors and warnings encountered when generating
561 * string name of alignment format
563 * the alignment to be written out
565 * passed to AlnFile class controls whether /START-END is added to
568 * @return alignment flat file contents
570 public String formatSequences(String format, AlignmentI alignment,
575 AlignFile afile = null;
576 if (format.equalsIgnoreCase("FASTA"))
578 afile = new FastaFile();
580 else if (format.equalsIgnoreCase("MSF"))
582 afile = new MSFfile();
584 else if (format.equalsIgnoreCase("PileUp"))
586 afile = new PileUpfile();
588 else if (format.equalsIgnoreCase("CLUSTAL"))
590 afile = new ClustalFile();
592 else if (format.equalsIgnoreCase("BLC"))
594 afile = new BLCFile();
596 else if (format.equalsIgnoreCase("PIR"))
598 afile = new PIRFile();
600 else if (format.equalsIgnoreCase("PFAM"))
602 afile = new PfamFile();
604 else if (format.equalsIgnoreCase("STH"))
606 afile = new StockholmFile(alignment);
608 else if (format.equalsIgnoreCase("AMSA"))
610 afile = new AMSAFile(alignment);
612 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
614 afile = new PhylipFile();
616 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
618 afile = new JSONFile();
620 else if (format.equalsIgnoreCase("RNAML"))
622 afile = new RnamlFile();
629 .getString("error.implementation_error_unknown_file_format_string"));
632 afile.setNewlineString(newline);
633 afile.addJVSuffix(jvsuffix);
634 afile.setExportSettings(exportSettings);
635 afile.configureForView(viewpanel);
637 // check whether we were given a specific alignment to export, rather than
638 // the one in the viewpanel
639 if (viewpanel == null || viewpanel.getAlignment() == null
640 || viewpanel.getAlignment() != alignment)
642 afile.setSeqs(alignment.getSequencesArray());
646 afile.setSeqs(viewpanel.getAlignment().getSequencesArray());
649 String afileresp = afile.print();
650 if (afile.hasWarningMessage())
652 System.err.println("Warning raised when writing as " + format
653 + " : " + afile.getWarningMessage());
656 } catch (Exception e)
658 System.err.println("Failed to write alignment as a '" + format
666 public static String checkProtocol(String file)
668 String protocol = FILE;
669 String ft = file.toLowerCase().trim();
670 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
671 || ft.indexOf("file:") == 0)
678 public static void main(String[] args)
681 while (i < args.length)
683 File f = new File(args[i]);
688 System.out.println("Reading file: " + f);
689 AppletFormatAdapter afa = new AppletFormatAdapter();
690 Runtime r = Runtime.getRuntime();
692 long memf = -r.totalMemory() + r.freeMemory();
693 long t1 = -System.currentTimeMillis();
694 AlignmentI al = afa.readFile(args[i], FILE,
695 new IdentifyFile().identify(args[i], FILE));
696 t1 += System.currentTimeMillis();
698 memf += r.totalMemory() - r.freeMemory();
701 System.out.println("Alignment contains " + al.getHeight()
702 + " sequences and " + al.getWidth() + " columns.");
705 System.out.println(new AppletFormatAdapter().formatSequences(
707 } catch (Exception e)
710 .println("Couln't format the alignment for output as a FASTA file.");
711 e.printStackTrace(System.err);
716 System.out.println("Couldn't read alignment");
718 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
720 .println("Difference between free memory now and before is "
721 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
722 } catch (Exception e)
724 System.err.println("Exception when dealing with " + i
725 + "'th argument: " + args[i] + "\n" + e);
730 System.err.println("Ignoring argument '" + args[i] + "' (" + i
731 + "'th)- not a readable file.");
738 * try to discover how to access the given file as a valid datasource that
739 * will be identified as the given type.
743 * @return protocol that yields the data parsable as the given type
745 public static String resolveProtocol(String file, String format)
747 return resolveProtocol(file, format, false);
750 public static String resolveProtocol(String file, String format,
753 // TODO: test thoroughly!
754 String protocol = null;
757 System.out.println("resolving datasource started with:\n>>file\n"
758 + file + ">>endfile");
761 // This might throw a security exception in certain browsers
762 // Netscape Communicator for instance.
766 InputStream is = System.getSecurityManager().getClass()
767 .getResourceAsStream("/" + file);
775 System.err.println("Resource '" + file + "' was "
776 + (rtn ? "" : "not") + " located by classloader.");
781 protocol = AppletFormatAdapter.CLASSLOADER;
784 } catch (Exception ex)
787 .println("Exception checking resources: " + file + " " + ex);
790 if (file.indexOf("://") > -1)
792 protocol = AppletFormatAdapter.URL;
796 // skipping codebase prepend check.
797 protocol = AppletFormatAdapter.FILE;
804 System.out.println("Trying to get contents of resource as "
807 fp = new FileParse(file, protocol);
816 System.out.println("Successful.");
819 } catch (Exception e)
823 System.err.println("Exception when accessing content: " + e);
831 System.out.println("Accessing as paste.");
833 protocol = AppletFormatAdapter.PASTE;
837 fp = new FileParse(file, protocol);
842 } catch (Exception e)
844 System.err.println("Failed to access content as paste!");
853 if (format == null || format.length() == 0)
861 String idformat = new jalview.io.IdentifyFile().identify(file,
863 if (idformat == null)
867 System.out.println("Format not identified. Inaccessible file.");
873 System.out.println("Format identified as " + idformat
874 + "and expected as " + format);
876 if (idformat.equals(format))
880 System.out.println("Protocol identified as " + protocol);
889 .println("File deemed not accessible via " + protocol);
894 } catch (Exception e)
898 System.err.println("File deemed not accessible via " + protocol);
908 public AlignFile getAlignFile()
913 public void setAlignFile(AlignFile alignFile)
915 this.alignFile = alignFile;