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.datamodel.SequenceGroup;
29 import jalview.util.MessageManager;
32 import java.io.InputStream;
33 import java.util.List;
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())
297 else if (format.equals(HtmlFile.FILE_DESC))
299 alignFile = new HtmlFile(inFile, type);
300 al = new Alignment(alignFile.getSeqsAsArray());
301 alignFile.addAnnotations(al);
302 for (SequenceGroup sg : alignFile.getSeqGroups())
308 else if (format.equals("RNAML"))
310 alignFile = new RnamlFile(inFile, type);
313 al = new Alignment(alignFile.getSeqsAsArray());
315 alignFile.addAnnotations(al);
318 } catch (Exception e)
321 System.err.println("Failed to read alignment using the '" + format
322 + "' reader.\n" + e);
324 if (e.getMessage() != null
325 && e.getMessage().startsWith(INVALID_CHARACTERS))
327 throw new java.io.IOException(e.getMessage());
330 // Finally test if the user has pasted just the sequence, no id
331 if (type.equalsIgnoreCase("Paste"))
335 // Possible sequence is just residues with no label
336 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
337 Alignment al = new Alignment(alignFile.getSeqsAsArray());
339 alignFile.addSeqGroups(al);
340 alignFile.addAnnotations(al);
343 } catch (Exception ex)
345 if (ex.toString().startsWith(INVALID_CHARACTERS))
347 throw new java.io.IOException(e.getMessage());
350 ex.printStackTrace();
354 // If we get to this stage, the format was not supported
355 throw new java.io.IOException(SUPPORTED_FORMATS);
360 * Constructs the correct filetype parser for an already open datasource
363 * an existing datasource
365 * File format of data that will be provided by datasource
367 * @return DOCUMENT ME!
369 public AlignmentI readFromFile(FileParse source, String format)
370 throws java.io.IOException
372 // TODO: generalise mapping between format string and io. class instances
373 // using Constructor.invoke reflection
374 // This is exactly the same as the readFile method except we substitute
375 // 'inFile, type' with 'source'
376 this.inFile = source.getInFile();
377 String type = source.type;
381 if (format.equals("FASTA"))
383 alignFile = new FastaFile(source);
385 else if (format.equals("MSF"))
387 alignFile = new MSFfile(source);
389 else if (format.equals("PileUp"))
391 alignFile = new PileUpfile(source);
393 else if (format.equals("CLUSTAL"))
395 alignFile = new ClustalFile(source);
397 else if (format.equals("BLC"))
399 alignFile = new BLCFile(source);
401 else if (format.equals("PIR"))
403 alignFile = new PIRFile(source);
405 else if (format.equals("PFAM"))
407 alignFile = new PfamFile(source);
409 else if (format.equals("JnetFile"))
411 alignFile = new JPredFile(source);
412 ((JPredFile) alignFile).removeNonSequences();
414 else if (format.equals("PDB"))
416 alignFile = new MCview.PDBfile(annotFromStructure,
417 localSecondaryStruct, serviceSecondaryStruct, source);
419 else if (format.equals("STH"))
421 alignFile = new StockholmFile(source);
423 else if (format.equals("RNAML"))
425 alignFile = new RnamlFile(source);
427 else if (format.equals("SimpleBLAST"))
429 alignFile = new SimpleBlastFile(source);
431 else if (format.equals(PhylipFile.FILE_DESC))
433 alignFile = new PhylipFile(source);
435 else if (format.equals(JSONFile.FILE_DESC))
437 alignFile = new JSONFile(source);
438 // ((JSONFile) afile).setViewport(viewport);
439 al = new Alignment(alignFile.getSeqsAsArray());
440 alignFile.addAnnotations(al);
441 alignFile.addSeqGroups(al);
444 else if (format.equals(HtmlFile.FILE_DESC))
446 alignFile = new HtmlFile(source);
448 al = new Alignment(alignFile.getSeqsAsArray());
449 alignFile.addAnnotations(al);
452 } catch (Exception e)
455 System.err.println("Failed to read alignment using the '" + format
456 + "' reader.\n" + e);
458 if (e.getMessage() != null
459 && e.getMessage().startsWith(INVALID_CHARACTERS))
461 throw new java.io.IOException(e.getMessage());
464 // Finally test if the user has pasted just the sequence, no id
465 if (type.equalsIgnoreCase("Paste"))
469 // Possible sequence is just residues with no label
470 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
471 Alignment al = new Alignment(alignFile.getSeqsAsArray());
472 alignFile.addAnnotations(al);
473 alignFile.addSeqGroups(al);
476 } catch (Exception ex)
478 if (ex.toString().startsWith(INVALID_CHARACTERS))
480 throw new java.io.IOException(e.getMessage());
483 ex.printStackTrace();
487 // If we get to this stage, the format was not supported
488 throw new java.io.IOException(SUPPORTED_FORMATS);
494 * create an alignment flatfile from a Jalview alignment view
498 * @param selectedOnly
499 * @return flatfile in a string
501 public String formatSequences(String format, boolean jvsuffix,
502 AlignViewportI av, boolean selectedOnly)
505 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
506 AlignmentI aselview = selvew.getVisibleAlignment(av
508 List<AlignmentAnnotation> ala = (av
509 .getVisibleAlignmentAnnotation(selectedOnly));
512 for (AlignmentAnnotation aa : ala)
514 aselview.addAnnotation(aa);
518 return formatSequences(format, aselview, jvsuffix);
522 * Construct an output class for an alignment in a particular filetype TODO:
523 * allow caller to detect errors and warnings encountered when generating
527 * string name of alignment format
529 * the alignment to be written out
531 * passed to AlnFile class controls whether /START-END is added to
534 * @return alignment flat file contents
536 public String formatSequences(String format, AlignmentI alignment,
541 AlignFile afile = null;
542 if (format.equalsIgnoreCase("FASTA"))
544 afile = new FastaFile();
546 else if (format.equalsIgnoreCase("MSF"))
548 afile = new MSFfile();
550 else if (format.equalsIgnoreCase("PileUp"))
552 afile = new PileUpfile();
554 else if (format.equalsIgnoreCase("CLUSTAL"))
556 afile = new ClustalFile();
558 else if (format.equalsIgnoreCase("BLC"))
560 afile = new BLCFile();
562 else if (format.equalsIgnoreCase("PIR"))
564 afile = new PIRFile();
566 else if (format.equalsIgnoreCase("PFAM"))
568 afile = new PfamFile();
570 else if (format.equalsIgnoreCase("STH"))
572 afile = new StockholmFile(alignment);
574 else if (format.equalsIgnoreCase("AMSA"))
576 afile = new AMSAFile(alignment);
578 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
580 afile = new PhylipFile();
582 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
584 afile = new JSONFile();
585 afile.setViewport(viewport);
586 // Add groups to AlignFile
587 afile.seqGroups = alignment.getGroups();
589 // Add non auto calculated annotation to AlignFile
590 for (AlignmentAnnotation annot : alignment.getAlignmentAnnotation())
592 if (annot != null && !annot.autoCalculated)
594 if (annot.label.equals("PDB.CATempFactor"))
598 afile.annotations.add(annot);
602 else if (format.equalsIgnoreCase("RNAML"))
604 afile = new RnamlFile();
609 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
611 afile.setNewlineString(newline);
612 afile.addJVSuffix(jvsuffix);
614 afile.setSeqs(alignment.getSequencesArray());
617 String afileresp = afile.print();
618 if (afile.hasWarningMessage())
620 System.err.println("Warning raised when writing as " + format
621 + " : " + afile.getWarningMessage());
624 } catch (Exception e)
626 System.err.println("Failed to write alignment as a '" + format
634 public static String checkProtocol(String file)
636 String protocol = FILE;
637 String ft = file.toLowerCase().trim();
638 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
639 || ft.indexOf("file:") == 0)
646 public static void main(String[] args)
649 while (i < args.length)
651 File f = new File(args[i]);
656 System.out.println("Reading file: " + f);
657 AppletFormatAdapter afa = new AppletFormatAdapter();
658 Runtime r = Runtime.getRuntime();
660 long memf = -r.totalMemory() + r.freeMemory();
661 long t1 = -System.currentTimeMillis();
662 Alignment al = afa.readFile(args[i], FILE,
663 new IdentifyFile().Identify(args[i], FILE));
664 t1 += System.currentTimeMillis();
666 memf += r.totalMemory() - r.freeMemory();
669 System.out.println("Alignment contains " + al.getHeight()
670 + " sequences and " + al.getWidth() + " columns.");
673 System.out.println(new AppletFormatAdapter().formatSequences(
675 } catch (Exception e)
678 .println("Couln't format the alignment for output as a FASTA file.");
679 e.printStackTrace(System.err);
684 System.out.println("Couldn't read alignment");
686 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
688 .println("Difference between free memory now and before is "
689 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
690 } catch (Exception e)
692 System.err.println("Exception when dealing with " + i
693 + "'th argument: " + args[i] + "\n" + e);
698 System.err.println("Ignoring argument '" + args[i] + "' (" + i
699 + "'th)- not a readable file.");
706 * try to discover how to access the given file as a valid datasource that
707 * will be identified as the given type.
711 * @return protocol that yields the data parsable as the given type
713 public static String resolveProtocol(String file, String format)
715 return resolveProtocol(file, format, false);
718 public static String resolveProtocol(String file, String format,
721 // TODO: test thoroughly!
722 String protocol = null;
725 System.out.println("resolving datasource started with:\n>>file\n"
726 + file + ">>endfile");
729 // This might throw a security exception in certain browsers
730 // Netscape Communicator for instance.
734 InputStream is = System.getSecurityManager().getClass()
735 .getResourceAsStream("/" + file);
743 System.err.println("Resource '" + file + "' was "
744 + (rtn ? "" : "not") + " located by classloader.");
749 protocol = AppletFormatAdapter.CLASSLOADER;
752 } catch (Exception ex)
755 .println("Exception checking resources: " + file + " " + ex);
758 if (file.indexOf("://") > -1)
760 protocol = AppletFormatAdapter.URL;
764 // skipping codebase prepend check.
765 protocol = AppletFormatAdapter.FILE;
772 System.out.println("Trying to get contents of resource as "
775 fp = new FileParse(file, protocol);
784 System.out.println("Successful.");
787 } catch (Exception e)
791 System.err.println("Exception when accessing content: " + e);
799 System.out.println("Accessing as paste.");
801 protocol = AppletFormatAdapter.PASTE;
805 fp = new FileParse(file, protocol);
810 } catch (Exception e)
812 System.err.println("Failed to access content as paste!");
821 if (format == null || format.length() == 0)
829 String idformat = new jalview.io.IdentifyFile().Identify(file,
831 if (idformat == null)
835 System.out.println("Format not identified. Inaccessible file.");
841 System.out.println("Format identified as " + idformat
842 + "and expected as " + format);
844 if (idformat.equals(format))
848 System.out.println("Protocol identified as " + protocol);
857 .println("File deemed not accessible via " + protocol);
862 } catch (Exception e)
866 System.err.println("File deemed not accessible via " + protocol);
876 public AlignFile getAlignFile()
881 public void setAlignFile(AlignFile alignFile)
883 this.alignFile = alignFile;