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.AlignViewportI;
24 import jalview.datamodel.Alignment;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.AlignmentView;
28 import jalview.util.MessageManager;
31 import java.io.InputStream;
32 import java.util.List;
35 * A low level class for alignment and feature IO with alignment formatting
36 * methods used by both applet and application for generating flat alignment
37 * files. It also holds the lists of magic format names that the applet and
38 * application will allow the user to read or write files with.
43 public class AppletFormatAdapter
45 private AlignViewportI viewport;
47 public static String FILE = "File";
49 public static String URL = "URL";
51 public static String PASTE = "Paste";
53 public static String CLASSLOADER = "ClassLoader";
56 * add jalview-derived non-secondary structure annotation from PDB structure
58 boolean annotFromStructure = false;
61 * add secondary structure from PDB data with built-in algorithms
63 boolean localSecondaryStruct = false;
66 * process PDB data with web services
68 boolean serviceSecondaryStruct = false;
70 private AlignFile alignFile = null;
75 * character used to write newlines
77 protected String newline = System.getProperty("line.separator");
80 * List of valid format strings used in the isValidFormat method
82 public static final String[] READABLE_FORMATS = new String[]
83 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
84 "PDB", "JnetFile", "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.GFF3File,
88 * List of readable format file extensions by application in order
89 * corresponding to READABLE_FNAMES
91 public static final String[] READABLE_EXTENSIONS = new String[]
92 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
93 "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT, JSONFile.FILE_EXT,
95 "jar,jvp", HtmlFile.FILE_EXT };
98 * List of readable formats by application in order corresponding to
101 public static final String[] READABLE_FNAMES = new String[]
102 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm",
103 "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.GFF3File, "Jalview",
104 HtmlFile.FILE_DESC };
107 * List of valid format strings for use by callers of the formatSequences
110 public static final String[] WRITEABLE_FORMATS = new String[]
111 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
112 "STH", PhylipFile.FILE_DESC, JSONFile.FILE_DESC };
115 * List of extensions corresponding to file format types in WRITABLE_FNAMES
116 * that are writable by the application.
118 public static final String[] WRITABLE_EXTENSIONS = new String[]
119 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
120 "sto,stk", PhylipFile.FILE_EXT, JSONFile.FILE_EXT, "jvp" };
123 * List of writable formats by the application. Order must correspond with the
124 * WRITABLE_EXTENSIONS list of formats.
126 public static final String[] WRITABLE_FNAMES = new String[]
127 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
128 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, "Jalview" };
130 public static String INVALID_CHARACTERS = "Contains invalid characters";
132 // TODO: make these messages dynamic
133 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
134 + prettyPrint(READABLE_FORMATS);
136 public AppletFormatAdapter()
140 public AppletFormatAdapter(AlignViewportI viewport)
142 this.viewport = viewport;
148 * @return grammatically correct(ish) list consisting of els elements.
150 public static String prettyPrint(String[] els)
152 StringBuffer list = new StringBuffer();
153 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
158 list.append(" and " + els[els.length - 1] + ".");
159 return list.toString();
163 public void setNewlineString(String nl)
168 public String getNewlineString()
174 * check that this format is valid for reading
177 * a format string to be compared with READABLE_FORMATS
178 * @return true if format is readable
180 public static final boolean isValidFormat(String format)
182 return isValidFormat(format, false);
186 * validate format is valid for IO
189 * a format string to be compared with either READABLE_FORMATS or
192 * when true, format is checked for containment in WRITEABLE_FORMATS
193 * @return true if format is valid
195 public static final boolean isValidFormat(String format,
198 boolean valid = false;
199 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
201 for (String element : format_list)
203 if (element.equalsIgnoreCase(format))
213 * Constructs the correct filetype parser for a characterised datasource
220 * File format of data provided by datasource
222 * @return DOCUMENT ME!
224 public Alignment readFile(String inFile, String type, String format)
225 throws java.io.IOException
227 // TODO: generalise mapping between format string and io. class instances
228 // using Constructor.invoke reflection
229 this.inFile = inFile;
233 if (format.equals("FASTA"))
235 alignFile = new FastaFile(inFile, type);
237 else if (format.equals("MSF"))
239 alignFile = new MSFfile(inFile, type);
241 else if (format.equals("PileUp"))
243 alignFile = new PileUpfile(inFile, type);
245 else if (format.equals("CLUSTAL"))
247 alignFile = new ClustalFile(inFile, type);
249 else if (format.equals("BLC"))
251 alignFile = new BLCFile(inFile, type);
253 else if (format.equals("PIR"))
255 alignFile = new PIRFile(inFile, type);
257 else if (format.equals("PFAM"))
259 alignFile = new PfamFile(inFile, type);
261 else if (format.equals("JnetFile"))
263 alignFile = new JPredFile(inFile, type);
264 ((JPredFile) alignFile).removeNonSequences();
266 else if (format.equals("PDB"))
268 alignFile = new MCview.PDBfile(annotFromStructure,
269 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
270 // Uncomment to test Jmol data based PDB processing: JAL-1213
271 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
273 else if (format.equals("STH"))
275 alignFile = new StockholmFile(inFile, type);
277 else if (format.equals("SimpleBLAST"))
279 alignFile = new SimpleBlastFile(inFile, type);
281 else if (format.equals(PhylipFile.FILE_DESC))
283 alignFile = new PhylipFile(inFile, type);
285 else if (format.equals(JSONFile.FILE_DESC))
287 alignFile = new JSONFile(inFile, type);
288 al = new Alignment(alignFile.getSeqsAsArray());
289 alignFile.addAnnotations(al);
290 ((JSONFile) alignFile).setViewport(viewport);
291 for (SequenceGroup sg : alignFile.getSeqGroups())
298 else if (format.equals(HtmlFile.FILE_DESC))
300 alignFile = new HtmlFile(inFile, type);
301 al = new Alignment(alignFile.getSeqsAsArray());
302 alignFile.addAnnotations(al);
303 for (SequenceGroup sg : alignFile.getSeqGroups())
309 else if (format.equals("RNAML"))
311 alignFile = new RnamlFile(inFile, type);
313 else if (format.equals(IdentifyFile.GFF3File))
315 alignFile = new Gff3File(inFile, type);
318 al = new Alignment(alignFile.getSeqsAsArray());
320 alignFile.addAnnotations(al);
323 } catch (Exception e)
326 System.err.println("Failed to read alignment using the '" + format
327 + "' reader.\n" + e);
329 if (e.getMessage() != null
330 && e.getMessage().startsWith(INVALID_CHARACTERS))
332 throw new java.io.IOException(e.getMessage());
335 // Finally test if the user has pasted just the sequence, no id
336 if (type.equalsIgnoreCase("Paste"))
340 // Possible sequence is just residues with no label
341 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
342 Alignment al = new Alignment(alignFile.getSeqsAsArray());
344 alignFile.addSeqGroups(al);
345 alignFile.addAnnotations(al);
348 } catch (Exception ex)
350 if (ex.toString().startsWith(INVALID_CHARACTERS))
352 throw new java.io.IOException(e.getMessage());
355 ex.printStackTrace();
359 // If we get to this stage, the format was not supported
360 throw new java.io.IOException(SUPPORTED_FORMATS);
365 * Constructs the correct filetype parser for an already open datasource
368 * an existing datasource
370 * File format of data that will be provided by datasource
372 * @return DOCUMENT ME!
374 public AlignmentI readFromFile(FileParse source, String format)
375 throws java.io.IOException
377 // TODO: generalise mapping between format string and io. class instances
378 // using Constructor.invoke reflection
379 // This is exactly the same as the readFile method except we substitute
380 // 'inFile, type' with 'source'
381 this.inFile = source.getInFile();
382 String type = source.type;
386 if (format.equals("FASTA"))
388 alignFile = new FastaFile(source);
390 else if (format.equals("MSF"))
392 alignFile = new MSFfile(source);
394 else if (format.equals("PileUp"))
396 alignFile = new PileUpfile(source);
398 else if (format.equals("CLUSTAL"))
400 alignFile = new ClustalFile(source);
402 else if (format.equals("BLC"))
404 alignFile = new BLCFile(source);
406 else if (format.equals("PIR"))
408 alignFile = new PIRFile(source);
410 else if (format.equals("PFAM"))
412 alignFile = new PfamFile(source);
414 else if (format.equals("JnetFile"))
416 alignFile = new JPredFile(source);
417 ((JPredFile) alignFile).removeNonSequences();
419 else if (format.equals("PDB"))
421 alignFile = new MCview.PDBfile(annotFromStructure,
422 localSecondaryStruct, serviceSecondaryStruct, source);
424 else if (format.equals("STH"))
426 alignFile = new StockholmFile(source);
428 else if (format.equals("RNAML"))
430 alignFile = new RnamlFile(source);
432 else if (format.equals("SimpleBLAST"))
434 alignFile = new SimpleBlastFile(source);
436 else if (format.equals(PhylipFile.FILE_DESC))
438 alignFile = new PhylipFile(source);
440 else if (format.equals(IdentifyFile.GFF3File))
442 alignFile = new Gff3File(inFile, type);
444 else if (format.equals(JSONFile.FILE_DESC))
446 alignFile = new JSONFile(source);
447 al = new Alignment(alignFile.getSeqsAsArray());
448 alignFile.addAnnotations(al);
449 alignFile.addSeqGroups(al);
452 else if (format.equals(HtmlFile.FILE_DESC))
454 alignFile = new HtmlFile(source);
456 al = new Alignment(alignFile.getSeqsAsArray());
457 alignFile.addAnnotations(al);
460 } catch (Exception e)
463 System.err.println("Failed to read alignment using the '" + format
464 + "' reader.\n" + e);
466 if (e.getMessage() != null
467 && e.getMessage().startsWith(INVALID_CHARACTERS))
469 throw new java.io.IOException(e.getMessage());
472 // Finally test if the user has pasted just the sequence, no id
473 if (type.equalsIgnoreCase("Paste"))
477 // Possible sequence is just residues with no label
478 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
479 Alignment al = new Alignment(alignFile.getSeqsAsArray());
480 alignFile.addAnnotations(al);
481 alignFile.addSeqGroups(al);
484 } catch (Exception ex)
486 if (ex.toString().startsWith(INVALID_CHARACTERS))
488 throw new java.io.IOException(e.getMessage());
491 ex.printStackTrace();
495 // If we get to this stage, the format was not supported
496 throw new java.io.IOException(SUPPORTED_FORMATS);
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 AlignViewportI av, boolean selectedOnly)
513 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
514 AlignmentI aselview = selvew.getVisibleAlignment(av
516 List<AlignmentAnnotation> ala = (av
517 .getVisibleAlignmentAnnotation(selectedOnly));
520 for (AlignmentAnnotation aa : ala)
522 aselview.addAnnotation(aa);
526 return formatSequences(format, aselview, jvsuffix);
530 * Construct an output class for an alignment in a particular filetype TODO:
531 * allow caller to detect errors and warnings encountered when generating
535 * string name of alignment format
537 * the alignment to be written out
539 * passed to AlnFile class controls whether /START-END is added to
542 * @return alignment flat file contents
544 public String formatSequences(String format, AlignmentI alignment,
549 AlignFile afile = null;
550 if (format.equalsIgnoreCase("FASTA"))
552 afile = new FastaFile();
554 else if (format.equalsIgnoreCase("MSF"))
556 afile = new MSFfile();
558 else if (format.equalsIgnoreCase("PileUp"))
560 afile = new PileUpfile();
562 else if (format.equalsIgnoreCase("CLUSTAL"))
564 afile = new ClustalFile();
566 else if (format.equalsIgnoreCase("BLC"))
568 afile = new BLCFile();
570 else if (format.equalsIgnoreCase("PIR"))
572 afile = new PIRFile();
574 else if (format.equalsIgnoreCase("PFAM"))
576 afile = new PfamFile();
578 else if (format.equalsIgnoreCase("STH"))
580 afile = new StockholmFile(alignment);
582 else if (format.equalsIgnoreCase("AMSA"))
584 afile = new AMSAFile(alignment);
586 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
588 afile = new PhylipFile();
590 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
592 afile = new JSONFile();
593 afile.setViewport(viewport);
594 // Add groups to AlignFile
595 afile.seqGroups = alignment.getGroups();
597 // Add non auto calculated annotation to AlignFile
598 for (AlignmentAnnotation annot : alignment.getAlignmentAnnotation())
600 if (annot != null && !annot.autoCalculated)
602 if (annot.label.equals("PDB.CATempFactor"))
606 afile.annotations.add(annot);
610 else if (format.equalsIgnoreCase("RNAML"))
612 afile = new RnamlFile();
617 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
619 afile.setNewlineString(newline);
620 afile.addJVSuffix(jvsuffix);
622 afile.setSeqs(alignment.getSequencesArray());
625 String afileresp = afile.print();
626 if (afile.hasWarningMessage())
628 System.err.println("Warning raised when writing as " + format
629 + " : " + afile.getWarningMessage());
632 } catch (Exception e)
634 System.err.println("Failed to write alignment as a '" + format
642 public static String checkProtocol(String file)
644 String protocol = FILE;
645 String ft = file.toLowerCase().trim();
646 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
647 || ft.indexOf("file:") == 0)
654 public static void main(String[] args)
657 while (i < args.length)
659 File f = new File(args[i]);
664 System.out.println("Reading file: " + f);
665 AppletFormatAdapter afa = new AppletFormatAdapter();
666 Runtime r = Runtime.getRuntime();
668 long memf = -r.totalMemory() + r.freeMemory();
669 long t1 = -System.currentTimeMillis();
670 Alignment al = afa.readFile(args[i], FILE,
671 new IdentifyFile().Identify(args[i], FILE));
672 t1 += System.currentTimeMillis();
674 memf += r.totalMemory() - r.freeMemory();
677 System.out.println("Alignment contains " + al.getHeight()
678 + " sequences and " + al.getWidth() + " columns.");
681 System.out.println(new AppletFormatAdapter().formatSequences(
683 } catch (Exception e)
686 .println("Couln't format the alignment for output as a FASTA file.");
687 e.printStackTrace(System.err);
692 System.out.println("Couldn't read alignment");
694 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
696 .println("Difference between free memory now and before is "
697 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
698 } catch (Exception e)
700 System.err.println("Exception when dealing with " + i
701 + "'th argument: " + args[i] + "\n" + e);
706 System.err.println("Ignoring argument '" + args[i] + "' (" + i
707 + "'th)- not a readable file.");
714 * try to discover how to access the given file as a valid datasource that
715 * will be identified as the given type.
719 * @return protocol that yields the data parsable as the given type
721 public static String resolveProtocol(String file, String format)
723 return resolveProtocol(file, format, false);
726 public static String resolveProtocol(String file, String format,
729 // TODO: test thoroughly!
730 String protocol = null;
733 System.out.println("resolving datasource started with:\n>>file\n"
734 + file + ">>endfile");
737 // This might throw a security exception in certain browsers
738 // Netscape Communicator for instance.
742 InputStream is = System.getSecurityManager().getClass()
743 .getResourceAsStream("/" + file);
751 System.err.println("Resource '" + file + "' was "
752 + (rtn ? "" : "not") + " located by classloader.");
757 protocol = AppletFormatAdapter.CLASSLOADER;
760 } catch (Exception ex)
763 .println("Exception checking resources: " + file + " " + ex);
766 if (file.indexOf("://") > -1)
768 protocol = AppletFormatAdapter.URL;
772 // skipping codebase prepend check.
773 protocol = AppletFormatAdapter.FILE;
780 System.out.println("Trying to get contents of resource as "
783 fp = new FileParse(file, protocol);
792 System.out.println("Successful.");
795 } catch (Exception e)
799 System.err.println("Exception when accessing content: " + e);
807 System.out.println("Accessing as paste.");
809 protocol = AppletFormatAdapter.PASTE;
813 fp = new FileParse(file, protocol);
818 } catch (Exception e)
820 System.err.println("Failed to access content as paste!");
829 if (format == null || format.length() == 0)
837 String idformat = new jalview.io.IdentifyFile().Identify(file,
839 if (idformat == null)
843 System.out.println("Format not identified. Inaccessible file.");
849 System.out.println("Format identified as " + idformat
850 + "and expected as " + format);
852 if (idformat.equals(format))
856 System.out.println("Protocol identified as " + protocol);
865 .println("File deemed not accessible via " + protocol);
870 } catch (Exception e)
874 System.err.println("File deemed not accessible via " + protocol);
884 public AlignFile getAlignFile()
889 public void setAlignFile(AlignFile alignFile)
891 this.alignFile = alignFile;