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.
24 import java.io.InputStream;
25 import java.util.List;
27 import jalview.api.AlignViewportI;
28 import jalview.datamodel.Alignment;
29 import jalview.datamodel.AlignmentAnnotation;
30 import jalview.datamodel.AlignmentI;
31 import jalview.datamodel.AlignmentView;
32 import jalview.datamodel.SequenceGroup;
33 import jalview.util.MessageManager;
36 * A low level class for alignment and feature IO with alignment formatting
37 * methods used by both applet and application for generating flat alignment
38 * files. It also holds the lists of magic format names that the applet and
39 * application will allow the user to read or write files with.
44 public class AppletFormatAdapter
46 private AlignViewportI viewport;
48 public static String FILE = "File";
50 public static String URL = "URL";
52 public static String PASTE = "Paste";
54 public static String CLASSLOADER = "ClassLoader";
57 * add jalview-derived non-secondary structure annotation from PDB structure
59 boolean annotFromStructure = false;
62 * add secondary structure from PDB data with built-in algorithms
64 boolean localSecondaryStruct = false;
67 * process PDB data with web services
69 boolean serviceSecondaryStruct = false;
71 private AlignFile alignFile = null;
76 * character used to write newlines
78 protected String newline = System.getProperty("line.separator");
81 * List of valid format strings used in the isValidFormat method
83 public static final String[] READABLE_FORMATS = new String[]
84 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
85 "PDB", "JnetFile", "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC,
89 * List of readable format file extensions by application in order
90 * corresponding to READABLE_FNAMES
92 public static final String[] READABLE_EXTENSIONS = new String[]
93 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
94 "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, "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);
314 al = new Alignment(alignFile.getSeqsAsArray());
316 alignFile.addAnnotations(al);
319 } catch (Exception e)
322 System.err.println("Failed to read alignment using the '" + format
323 + "' reader.\n" + e);
325 if (e.getMessage() != null
326 && e.getMessage().startsWith(INVALID_CHARACTERS))
328 throw new java.io.IOException(e.getMessage());
331 // Finally test if the user has pasted just the sequence, no id
332 if (type.equalsIgnoreCase("Paste"))
336 // Possible sequence is just residues with no label
337 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
338 Alignment al = new Alignment(alignFile.getSeqsAsArray());
340 alignFile.addSeqGroups(al);
341 alignFile.addAnnotations(al);
344 } catch (Exception ex)
346 if (ex.toString().startsWith(INVALID_CHARACTERS))
348 throw new java.io.IOException(e.getMessage());
351 ex.printStackTrace();
355 // If we get to this stage, the format was not supported
356 throw new java.io.IOException(SUPPORTED_FORMATS);
361 * Constructs the correct filetype parser for an already open datasource
364 * an existing datasource
366 * File format of data that will be provided by datasource
368 * @return DOCUMENT ME!
370 public AlignmentI readFromFile(FileParse source, String format)
371 throws java.io.IOException
373 // TODO: generalise mapping between format string and io. class instances
374 // using Constructor.invoke reflection
375 // This is exactly the same as the readFile method except we substitute
376 // 'inFile, type' with 'source'
377 this.inFile = source.getInFile();
378 String type = source.type;
382 if (format.equals("FASTA"))
384 alignFile = new FastaFile(source);
386 else if (format.equals("MSF"))
388 alignFile = new MSFfile(source);
390 else if (format.equals("PileUp"))
392 alignFile = new PileUpfile(source);
394 else if (format.equals("CLUSTAL"))
396 alignFile = new ClustalFile(source);
398 else if (format.equals("BLC"))
400 alignFile = new BLCFile(source);
402 else if (format.equals("PIR"))
404 alignFile = new PIRFile(source);
406 else if (format.equals("PFAM"))
408 alignFile = new PfamFile(source);
410 else if (format.equals("JnetFile"))
412 alignFile = new JPredFile(source);
413 ((JPredFile) alignFile).removeNonSequences();
415 else if (format.equals("PDB"))
417 alignFile = new MCview.PDBfile(annotFromStructure,
418 localSecondaryStruct, serviceSecondaryStruct, source);
420 else if (format.equals("STH"))
422 alignFile = new StockholmFile(source);
424 else if (format.equals("RNAML"))
426 alignFile = new RnamlFile(source);
428 else if (format.equals("SimpleBLAST"))
430 alignFile = new SimpleBlastFile(source);
432 else if (format.equals(PhylipFile.FILE_DESC))
434 alignFile = new PhylipFile(source);
436 else if (format.equals(JSONFile.FILE_DESC))
438 alignFile = new JSONFile(source);
439 // ((JSONFile) afile).setViewport(viewport);
440 al = new Alignment(alignFile.getSeqsAsArray());
441 alignFile.addAnnotations(al);
442 alignFile.addSeqGroups(al);
445 else if (format.equals(HtmlFile.FILE_DESC))
447 alignFile = new HtmlFile(source);
449 al = new Alignment(alignFile.getSeqsAsArray());
450 alignFile.addAnnotations(al);
453 } catch (Exception e)
456 System.err.println("Failed to read alignment using the '" + format
457 + "' reader.\n" + e);
459 if (e.getMessage() != null
460 && e.getMessage().startsWith(INVALID_CHARACTERS))
462 throw new java.io.IOException(e.getMessage());
465 // Finally test if the user has pasted just the sequence, no id
466 if (type.equalsIgnoreCase("Paste"))
470 // Possible sequence is just residues with no label
471 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
472 Alignment al = new Alignment(alignFile.getSeqsAsArray());
473 alignFile.addAnnotations(al);
474 alignFile.addSeqGroups(al);
477 } catch (Exception ex)
479 if (ex.toString().startsWith(INVALID_CHARACTERS))
481 throw new java.io.IOException(e.getMessage());
484 ex.printStackTrace();
488 // If we get to this stage, the format was not supported
489 throw new java.io.IOException(SUPPORTED_FORMATS);
495 * create an alignment flatfile from a Jalview alignment view
499 * @param selectedOnly
500 * @return flatfile in a string
502 public String formatSequences(String format, boolean jvsuffix,
503 AlignViewportI av, boolean selectedOnly)
506 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
507 AlignmentI aselview = selvew.getVisibleAlignment(av
509 List<AlignmentAnnotation> ala = (av
510 .getVisibleAlignmentAnnotation(selectedOnly));
513 for (AlignmentAnnotation aa : ala)
515 aselview.addAnnotation(aa);
519 return formatSequences(format, aselview, jvsuffix);
523 * Construct an output class for an alignment in a particular filetype TODO:
524 * allow caller to detect errors and warnings encountered when generating
528 * string name of alignment format
530 * the alignment to be written out
532 * passed to AlnFile class controls whether /START-END is added to
535 * @return alignment flat file contents
537 public String formatSequences(String format, AlignmentI alignment,
542 AlignFile afile = null;
543 if (format.equalsIgnoreCase("FASTA"))
545 afile = new FastaFile();
547 else if (format.equalsIgnoreCase("MSF"))
549 afile = new MSFfile();
551 else if (format.equalsIgnoreCase("PileUp"))
553 afile = new PileUpfile();
555 else if (format.equalsIgnoreCase("CLUSTAL"))
557 afile = new ClustalFile();
559 else if (format.equalsIgnoreCase("BLC"))
561 afile = new BLCFile();
563 else if (format.equalsIgnoreCase("PIR"))
565 afile = new PIRFile();
567 else if (format.equalsIgnoreCase("PFAM"))
569 afile = new PfamFile();
571 else if (format.equalsIgnoreCase("STH"))
573 afile = new StockholmFile(alignment);
575 else if (format.equalsIgnoreCase("AMSA"))
577 afile = new AMSAFile(alignment);
579 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
581 afile = new PhylipFile();
583 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
585 afile = new JSONFile();
586 afile.setViewport(viewport);
587 // Add groups to AlignFile
588 afile.seqGroups = alignment.getGroups();
590 // Add non auto calculated annotation to AlignFile
591 for (AlignmentAnnotation annot : alignment.getAlignmentAnnotation())
593 if (annot != null && !annot.autoCalculated)
595 if (annot.label.equals("PDB.CATempFactor"))
599 afile.annotations.add(annot);
603 else if (format.equalsIgnoreCase("RNAML"))
605 afile = new RnamlFile();
610 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
612 afile.setNewlineString(newline);
613 afile.addJVSuffix(jvsuffix);
615 afile.setSeqs(alignment.getSequencesArray());
618 String afileresp = afile.print();
619 if (afile.hasWarningMessage())
621 System.err.println("Warning raised when writing as " + format
622 + " : " + afile.getWarningMessage());
625 } catch (Exception e)
627 System.err.println("Failed to write alignment as a '" + format
635 public static String checkProtocol(String file)
637 String protocol = FILE;
638 String ft = file.toLowerCase().trim();
639 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
640 || ft.indexOf("file:") == 0)
647 public static void main(String[] args)
650 while (i < args.length)
652 File f = new File(args[i]);
657 System.out.println("Reading file: " + f);
658 AppletFormatAdapter afa = new AppletFormatAdapter();
659 Runtime r = Runtime.getRuntime();
661 long memf = -r.totalMemory() + r.freeMemory();
662 long t1 = -System.currentTimeMillis();
663 Alignment al = afa.readFile(args[i], FILE,
664 new IdentifyFile().Identify(args[i], FILE));
665 t1 += System.currentTimeMillis();
667 memf += r.totalMemory() - r.freeMemory();
670 System.out.println("Alignment contains " + al.getHeight()
671 + " sequences and " + al.getWidth() + " columns.");
674 System.out.println(new AppletFormatAdapter().formatSequences(
676 } catch (Exception e)
679 .println("Couln't format the alignment for output as a FASTA file.");
680 e.printStackTrace(System.err);
685 System.out.println("Couldn't read alignment");
687 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
689 .println("Difference between free memory now and before is "
690 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
691 } catch (Exception e)
693 System.err.println("Exception when dealing with " + i
694 + "'th argument: " + args[i] + "\n" + e);
699 System.err.println("Ignoring argument '" + args[i] + "' (" + i
700 + "'th)- not a readable file.");
707 * try to discover how to access the given file as a valid datasource that
708 * will be identified as the given type.
712 * @return protocol that yields the data parsable as the given type
714 public static String resolveProtocol(String file, String format)
716 return resolveProtocol(file, format, false);
719 public static String resolveProtocol(String file, String format,
722 // TODO: test thoroughly!
723 String protocol = null;
726 System.out.println("resolving datasource started with:\n>>file\n"
727 + file + ">>endfile");
730 // This might throw a security exception in certain browsers
731 // Netscape Communicator for instance.
735 InputStream is = System.getSecurityManager().getClass()
736 .getResourceAsStream("/" + file);
744 System.err.println("Resource '" + file + "' was "
745 + (rtn ? "" : "not") + " located by classloader.");
750 protocol = AppletFormatAdapter.CLASSLOADER;
753 } catch (Exception ex)
756 .println("Exception checking resources: " + file + " " + ex);
759 if (file.indexOf("://") > -1)
761 protocol = AppletFormatAdapter.URL;
765 // skipping codebase prepend check.
766 protocol = AppletFormatAdapter.FILE;
773 System.out.println("Trying to get contents of resource as "
776 fp = new FileParse(file, protocol);
785 System.out.println("Successful.");
788 } catch (Exception e)
792 System.err.println("Exception when accessing content: " + e);
800 System.out.println("Accessing as paste.");
802 protocol = AppletFormatAdapter.PASTE;
806 fp = new FileParse(file, protocol);
811 } catch (Exception e)
813 System.err.println("Failed to access content as paste!");
822 if (format == null || format.length() == 0)
830 String idformat = new jalview.io.IdentifyFile().Identify(file,
832 if (idformat == null)
836 System.out.println("Format not identified. Inaccessible file.");
842 System.out.println("Format identified as " + idformat
843 + "and expected as " + format);
845 if (idformat.equals(format))
849 System.out.println("Protocol identified as " + protocol);
858 .println("File deemed not accessible via " + protocol);
863 } catch (Exception e)
867 System.err.println("File deemed not accessible via " + protocol);
877 public AlignFile getAlignFile()
882 public void setAlignFile(AlignFile alignFile)
884 this.alignFile = alignFile;