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, IdentifyFile.GFF3File,
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,
96 "jar,jvp", HtmlFile.FILE_EXT };
99 * List of readable formats by application in order corresponding to
100 * READABLE_EXTENSIONS
102 public static final String[] READABLE_FNAMES = new String[]
103 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm",
104 "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.GFF3File, "Jalview",
105 HtmlFile.FILE_DESC };
108 * List of valid format strings for use by callers of the formatSequences
111 public static final String[] WRITEABLE_FORMATS = new String[]
112 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
113 "STH", PhylipFile.FILE_DESC, JSONFile.FILE_DESC };
116 * List of extensions corresponding to file format types in WRITABLE_FNAMES
117 * that are writable by the application.
119 public static final String[] WRITABLE_EXTENSIONS = new String[]
120 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
121 "sto,stk", PhylipFile.FILE_EXT, JSONFile.FILE_EXT, "jvp" };
124 * List of writable formats by the application. Order must correspond with the
125 * WRITABLE_EXTENSIONS list of formats.
127 public static final String[] WRITABLE_FNAMES = new String[]
128 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
129 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, "Jalview" };
131 public static String INVALID_CHARACTERS = "Contains invalid characters";
133 // TODO: make these messages dynamic
134 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
135 + prettyPrint(READABLE_FORMATS);
137 public AppletFormatAdapter()
141 public AppletFormatAdapter(AlignViewportI viewport)
143 this.viewport = viewport;
149 * @return grammatically correct(ish) list consisting of els elements.
151 public static String prettyPrint(String[] els)
153 StringBuffer list = new StringBuffer();
154 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
159 list.append(" and " + els[els.length - 1] + ".");
160 return list.toString();
164 public void setNewlineString(String nl)
169 public String getNewlineString()
175 * check that this format is valid for reading
178 * a format string to be compared with READABLE_FORMATS
179 * @return true if format is readable
181 public static final boolean isValidFormat(String format)
183 return isValidFormat(format, false);
187 * validate format is valid for IO
190 * a format string to be compared with either READABLE_FORMATS or
193 * when true, format is checked for containment in WRITEABLE_FORMATS
194 * @return true if format is valid
196 public static final boolean isValidFormat(String format,
199 boolean valid = false;
200 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
202 for (String element : format_list)
204 if (element.equalsIgnoreCase(format))
214 * Constructs the correct filetype parser for a characterised datasource
221 * File format of data provided by datasource
223 * @return DOCUMENT ME!
225 public Alignment readFile(String inFile, String type, String format)
226 throws java.io.IOException
228 // TODO: generalise mapping between format string and io. class instances
229 // using Constructor.invoke reflection
230 this.inFile = inFile;
234 if (format.equals("FASTA"))
236 alignFile = new FastaFile(inFile, type);
238 else if (format.equals("MSF"))
240 alignFile = new MSFfile(inFile, type);
242 else if (format.equals("PileUp"))
244 alignFile = new PileUpfile(inFile, type);
246 else if (format.equals("CLUSTAL"))
248 alignFile = new ClustalFile(inFile, type);
250 else if (format.equals("BLC"))
252 alignFile = new BLCFile(inFile, type);
254 else if (format.equals("PIR"))
256 alignFile = new PIRFile(inFile, type);
258 else if (format.equals("PFAM"))
260 alignFile = new PfamFile(inFile, type);
262 else if (format.equals("JnetFile"))
264 alignFile = new JPredFile(inFile, type);
265 ((JPredFile) alignFile).removeNonSequences();
267 else if (format.equals("PDB"))
269 alignFile = new MCview.PDBfile(annotFromStructure,
270 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
271 // Uncomment to test Jmol data based PDB processing: JAL-1213
272 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
274 else if (format.equals("STH"))
276 alignFile = new StockholmFile(inFile, type);
278 else if (format.equals("SimpleBLAST"))
280 alignFile = new SimpleBlastFile(inFile, type);
282 else if (format.equals(PhylipFile.FILE_DESC))
284 alignFile = new PhylipFile(inFile, type);
286 else if (format.equals(JSONFile.FILE_DESC))
288 alignFile = new JSONFile(inFile, type);
289 al = new Alignment(alignFile.getSeqsAsArray());
290 alignFile.addAnnotations(al);
291 ((JSONFile) alignFile).setViewport(viewport);
292 for (SequenceGroup sg : alignFile.getSeqGroups())
299 else if (format.equals(HtmlFile.FILE_DESC))
301 alignFile = new HtmlFile(inFile, type);
302 al = new Alignment(alignFile.getSeqsAsArray());
303 alignFile.addAnnotations(al);
304 for (SequenceGroup sg : alignFile.getSeqGroups())
310 else if (format.equals("RNAML"))
312 alignFile = new RnamlFile(inFile, type);
314 else if (format.equals(IdentifyFile.GFF3File))
316 alignFile = new Gff3File(inFile, type);
319 al = new Alignment(alignFile.getSeqsAsArray());
321 alignFile.addAnnotations(al);
324 } catch (Exception e)
327 System.err.println("Failed to read alignment using the '" + format
328 + "' reader.\n" + e);
330 if (e.getMessage() != null
331 && e.getMessage().startsWith(INVALID_CHARACTERS))
333 throw new java.io.IOException(e.getMessage());
336 // Finally test if the user has pasted just the sequence, no id
337 if (type.equalsIgnoreCase("Paste"))
341 // Possible sequence is just residues with no label
342 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
343 Alignment al = new Alignment(alignFile.getSeqsAsArray());
345 alignFile.addSeqGroups(al);
346 alignFile.addAnnotations(al);
349 } catch (Exception ex)
351 if (ex.toString().startsWith(INVALID_CHARACTERS))
353 throw new java.io.IOException(e.getMessage());
356 ex.printStackTrace();
360 // If we get to this stage, the format was not supported
361 throw new java.io.IOException(SUPPORTED_FORMATS);
366 * Constructs the correct filetype parser for an already open datasource
369 * an existing datasource
371 * File format of data that will be provided by datasource
373 * @return DOCUMENT ME!
375 public AlignmentI readFromFile(FileParse source, String format)
376 throws java.io.IOException
378 // TODO: generalise mapping between format string and io. class instances
379 // using Constructor.invoke reflection
380 // This is exactly the same as the readFile method except we substitute
381 // 'inFile, type' with 'source'
382 this.inFile = source.getInFile();
383 String type = source.type;
387 if (format.equals("FASTA"))
389 alignFile = new FastaFile(source);
391 else if (format.equals("MSF"))
393 alignFile = new MSFfile(source);
395 else if (format.equals("PileUp"))
397 alignFile = new PileUpfile(source);
399 else if (format.equals("CLUSTAL"))
401 alignFile = new ClustalFile(source);
403 else if (format.equals("BLC"))
405 alignFile = new BLCFile(source);
407 else if (format.equals("PIR"))
409 alignFile = new PIRFile(source);
411 else if (format.equals("PFAM"))
413 alignFile = new PfamFile(source);
415 else if (format.equals("JnetFile"))
417 alignFile = new JPredFile(source);
418 ((JPredFile) alignFile).removeNonSequences();
420 else if (format.equals("PDB"))
422 alignFile = new MCview.PDBfile(annotFromStructure,
423 localSecondaryStruct, serviceSecondaryStruct, source);
425 else if (format.equals("STH"))
427 alignFile = new StockholmFile(source);
429 else if (format.equals("RNAML"))
431 alignFile = new RnamlFile(source);
433 else if (format.equals("SimpleBLAST"))
435 alignFile = new SimpleBlastFile(source);
437 else if (format.equals(PhylipFile.FILE_DESC))
439 alignFile = new PhylipFile(source);
441 else if (format.equals(IdentifyFile.GFF3File))
443 alignFile = new Gff3File(inFile, type);
445 else if (format.equals(JSONFile.FILE_DESC))
447 alignFile = new JSONFile(source);
448 al = new Alignment(alignFile.getSeqsAsArray());
449 alignFile.addAnnotations(al);
450 alignFile.addSeqGroups(al);
453 else if (format.equals(HtmlFile.FILE_DESC))
455 alignFile = new HtmlFile(source);
457 al = new Alignment(alignFile.getSeqsAsArray());
458 alignFile.addAnnotations(al);
461 } catch (Exception e)
464 System.err.println("Failed to read alignment using the '" + format
465 + "' reader.\n" + e);
467 if (e.getMessage() != null
468 && e.getMessage().startsWith(INVALID_CHARACTERS))
470 throw new java.io.IOException(e.getMessage());
473 // Finally test if the user has pasted just the sequence, no id
474 if (type.equalsIgnoreCase("Paste"))
478 // Possible sequence is just residues with no label
479 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
480 Alignment al = new Alignment(alignFile.getSeqsAsArray());
481 alignFile.addAnnotations(al);
482 alignFile.addSeqGroups(al);
485 } catch (Exception ex)
487 if (ex.toString().startsWith(INVALID_CHARACTERS))
489 throw new java.io.IOException(e.getMessage());
492 ex.printStackTrace();
496 // If we get to this stage, the format was not supported
497 throw new java.io.IOException(SUPPORTED_FORMATS);
503 * create an alignment flatfile from a Jalview alignment view
507 * @param selectedOnly
508 * @return flatfile in a string
510 public String formatSequences(String format, boolean jvsuffix,
511 AlignViewportI av, boolean selectedOnly)
514 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
515 AlignmentI aselview = selvew.getVisibleAlignment(av
517 List<AlignmentAnnotation> ala = (av
518 .getVisibleAlignmentAnnotation(selectedOnly));
521 for (AlignmentAnnotation aa : ala)
523 aselview.addAnnotation(aa);
527 return formatSequences(format, aselview, jvsuffix);
531 * Construct an output class for an alignment in a particular filetype TODO:
532 * allow caller to detect errors and warnings encountered when generating
536 * string name of alignment format
538 * the alignment to be written out
540 * passed to AlnFile class controls whether /START-END is added to
543 * @return alignment flat file contents
545 public String formatSequences(String format, AlignmentI alignment,
550 AlignFile afile = null;
551 if (format.equalsIgnoreCase("FASTA"))
553 afile = new FastaFile();
555 else if (format.equalsIgnoreCase("MSF"))
557 afile = new MSFfile();
559 else if (format.equalsIgnoreCase("PileUp"))
561 afile = new PileUpfile();
563 else if (format.equalsIgnoreCase("CLUSTAL"))
565 afile = new ClustalFile();
567 else if (format.equalsIgnoreCase("BLC"))
569 afile = new BLCFile();
571 else if (format.equalsIgnoreCase("PIR"))
573 afile = new PIRFile();
575 else if (format.equalsIgnoreCase("PFAM"))
577 afile = new PfamFile();
579 else if (format.equalsIgnoreCase("STH"))
581 afile = new StockholmFile(alignment);
583 else if (format.equalsIgnoreCase("AMSA"))
585 afile = new AMSAFile(alignment);
587 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
589 afile = new PhylipFile();
591 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
593 afile = new JSONFile();
594 afile.setViewport(viewport);
595 // Add groups to AlignFile
596 afile.seqGroups = alignment.getGroups();
598 // Add non auto calculated annotation to AlignFile
599 for (AlignmentAnnotation annot : alignment.getAlignmentAnnotation())
601 if (annot != null && !annot.autoCalculated)
603 if (annot.label.equals("PDB.CATempFactor"))
607 afile.annotations.add(annot);
611 else if (format.equalsIgnoreCase("RNAML"))
613 afile = new RnamlFile();
618 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
620 afile.setNewlineString(newline);
621 afile.addJVSuffix(jvsuffix);
623 afile.setSeqs(alignment.getSequencesArray());
626 String afileresp = afile.print();
627 if (afile.hasWarningMessage())
629 System.err.println("Warning raised when writing as " + format
630 + " : " + afile.getWarningMessage());
633 } catch (Exception e)
635 System.err.println("Failed to write alignment as a '" + format
643 public static String checkProtocol(String file)
645 String protocol = FILE;
646 String ft = file.toLowerCase().trim();
647 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
648 || ft.indexOf("file:") == 0)
655 public static void main(String[] args)
658 while (i < args.length)
660 File f = new File(args[i]);
665 System.out.println("Reading file: " + f);
666 AppletFormatAdapter afa = new AppletFormatAdapter();
667 Runtime r = Runtime.getRuntime();
669 long memf = -r.totalMemory() + r.freeMemory();
670 long t1 = -System.currentTimeMillis();
671 Alignment al = afa.readFile(args[i], FILE,
672 new IdentifyFile().Identify(args[i], FILE));
673 t1 += System.currentTimeMillis();
675 memf += r.totalMemory() - r.freeMemory();
678 System.out.println("Alignment contains " + al.getHeight()
679 + " sequences and " + al.getWidth() + " columns.");
682 System.out.println(new AppletFormatAdapter().formatSequences(
684 } catch (Exception e)
687 .println("Couln't format the alignment for output as a FASTA file.");
688 e.printStackTrace(System.err);
693 System.out.println("Couldn't read alignment");
695 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
697 .println("Difference between free memory now and before is "
698 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
699 } catch (Exception e)
701 System.err.println("Exception when dealing with " + i
702 + "'th argument: " + args[i] + "\n" + e);
707 System.err.println("Ignoring argument '" + args[i] + "' (" + i
708 + "'th)- not a readable file.");
715 * try to discover how to access the given file as a valid datasource that
716 * will be identified as the given type.
720 * @return protocol that yields the data parsable as the given type
722 public static String resolveProtocol(String file, String format)
724 return resolveProtocol(file, format, false);
727 public static String resolveProtocol(String file, String format,
730 // TODO: test thoroughly!
731 String protocol = null;
734 System.out.println("resolving datasource started with:\n>>file\n"
735 + file + ">>endfile");
738 // This might throw a security exception in certain browsers
739 // Netscape Communicator for instance.
743 InputStream is = System.getSecurityManager().getClass()
744 .getResourceAsStream("/" + file);
752 System.err.println("Resource '" + file + "' was "
753 + (rtn ? "" : "not") + " located by classloader.");
758 protocol = AppletFormatAdapter.CLASSLOADER;
761 } catch (Exception ex)
764 .println("Exception checking resources: " + file + " " + ex);
767 if (file.indexOf("://") > -1)
769 protocol = AppletFormatAdapter.URL;
773 // skipping codebase prepend check.
774 protocol = AppletFormatAdapter.FILE;
781 System.out.println("Trying to get contents of resource as "
784 fp = new FileParse(file, protocol);
793 System.out.println("Successful.");
796 } catch (Exception e)
800 System.err.println("Exception when accessing content: " + e);
808 System.out.println("Accessing as paste.");
810 protocol = AppletFormatAdapter.PASTE;
814 fp = new FileParse(file, protocol);
819 } catch (Exception e)
821 System.err.println("Failed to access content as paste!");
830 if (format == null || format.length() == 0)
838 String idformat = new jalview.io.IdentifyFile().Identify(file,
840 if (idformat == null)
844 System.out.println("Format not identified. Inaccessible file.");
850 System.out.println("Format identified as " + idformat
851 + "and expected as " + format);
853 if (idformat.equals(format))
857 System.out.println("Protocol identified as " + protocol);
866 .println("File deemed not accessible via " + protocol);
871 } catch (Exception e)
875 System.err.println("File deemed not accessible via " + protocol);
885 public AlignFile getAlignFile()
890 public void setAlignFile(AlignFile alignFile)
892 this.alignFile = alignFile;