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
47 * List of valid format strings used in the isValidFormat method
49 public static final String[] READABLE_FORMATS = new String[]
50 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
51 "PDB", "JnetFile", "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC,
55 * List of readable format file extensions by application in order
56 * corresponding to READABLE_FNAMES
58 public static final String[] READABLE_EXTENSIONS = new String[]
59 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
60 "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT, JSONFile.FILE_EXT,
61 "jar,jvp", HtmlFile.FILE_EXT };
64 * List of readable formats by application in order corresponding to
67 public static final String[] READABLE_FNAMES = new String[]
68 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm",
69 "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC, "Jalview",
73 * List of valid format strings for use by callers of the formatSequences
76 public static final String[] WRITEABLE_FORMATS = new String[]
77 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
78 "STH", PhylipFile.FILE_DESC, JSONFile.FILE_DESC };
81 * List of extensions corresponding to file format types in WRITABLE_FNAMES
82 * that are writable by the application.
84 public static final String[] WRITABLE_EXTENSIONS = new String[]
85 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
86 "sto,stk", PhylipFile.FILE_EXT, JSONFile.FILE_EXT, "jvp" };
89 * List of writable formats by the application. Order must correspond with the
90 * WRITABLE_EXTENSIONS list of formats.
92 public static final String[] WRITABLE_FNAMES = new String[]
93 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
94 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, "Jalview" };
96 public static String INVALID_CHARACTERS = "Contains invalid characters";
98 // TODO: make these messages dynamic
99 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
100 + prettyPrint(READABLE_FORMATS);
105 * @return grammatically correct(ish) list consisting of els elements.
107 public static String prettyPrint(String[] els)
109 StringBuffer list = new StringBuffer();
110 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
115 list.append(" and " + els[els.length - 1] + ".");
116 return list.toString();
119 public static String FILE = "File";
121 public static String URL = "URL";
123 public static String PASTE = "Paste";
125 public static String CLASSLOADER = "ClassLoader";
128 * add jalview-derived non-secondary structure annotation from PDB structure
130 boolean annotFromStructure = false;
133 * add secondary structure from PDB data with built-in algorithms
135 boolean localSecondaryStruct = false;
138 * process PDB data with web services
140 boolean serviceSecondaryStruct = false;
142 AlignFile afile = null;
147 * character used to write newlines
149 protected String newline = System.getProperty("line.separator");
151 public void setNewlineString(String nl)
156 public String getNewlineString()
162 * check that this format is valid for reading
165 * a format string to be compared with READABLE_FORMATS
166 * @return true if format is readable
168 public static final boolean isValidFormat(String format)
170 return isValidFormat(format, false);
174 * validate format is valid for IO
177 * a format string to be compared with either READABLE_FORMATS or
180 * when true, format is checked for containment in WRITEABLE_FORMATS
181 * @return true if format is valid
183 public static final boolean isValidFormat(String format,
186 boolean valid = false;
187 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
189 for (String element : format_list)
191 if (element.equalsIgnoreCase(format))
201 * Constructs the correct filetype parser for a characterised datasource
208 * File format of data provided by datasource
210 * @return DOCUMENT ME!
212 public Alignment readFile(String inFile, String type, String format)
213 throws java.io.IOException
215 // TODO: generalise mapping between format string and io. class instances
216 // using Constructor.invoke reflection
217 this.inFile = inFile;
221 if (format.equals("FASTA"))
223 afile = new FastaFile(inFile, type);
225 else if (format.equals("MSF"))
227 afile = new MSFfile(inFile, type);
229 else if (format.equals("PileUp"))
231 afile = new PileUpfile(inFile, type);
233 else if (format.equals("CLUSTAL"))
235 afile = new ClustalFile(inFile, type);
237 else if (format.equals("BLC"))
239 afile = new BLCFile(inFile, type);
241 else if (format.equals("PIR"))
243 afile = new PIRFile(inFile, type);
245 else if (format.equals("PFAM"))
247 afile = new PfamFile(inFile, type);
249 else if (format.equals("JnetFile"))
251 afile = new JPredFile(inFile, type);
252 ((JPredFile) afile).removeNonSequences();
254 else if (format.equals("PDB"))
256 afile = new MCview.PDBfile(annotFromStructure,
257 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
258 // Uncomment to test Jmol data based PDB processing: JAL-1213
259 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
261 else if (format.equals("STH"))
263 afile = new StockholmFile(inFile, type);
265 else if (format.equals("SimpleBLAST"))
267 afile = new SimpleBlastFile(inFile, type);
269 else if (format.equals(PhylipFile.FILE_DESC))
271 afile = new PhylipFile(inFile, type);
273 else if (format.equals(JSONFile.FILE_DESC))
275 afile = new JSONFile(inFile, type);
276 al = new Alignment(afile.getSeqsAsArray());
277 afile.addAnnotations(al);
278 for (SequenceGroup sg : afile.getSeqGroups())
284 else if (format.equals(HtmlFile.FILE_DESC))
286 afile = new HtmlFile(inFile, type);
287 al = new Alignment(afile.getSeqsAsArray());
288 afile.addAnnotations(al);
289 for (SequenceGroup sg : afile.getSeqGroups())
295 else if (format.equals("RNAML"))
297 afile = new RnamlFile(inFile, type);
300 al = new Alignment(afile.getSeqsAsArray());
302 afile.addAnnotations(al);
305 } catch (Exception e)
308 System.err.println("Failed to read alignment using the '" + format
309 + "' reader.\n" + e);
311 if (e.getMessage() != null
312 && e.getMessage().startsWith(INVALID_CHARACTERS))
314 throw new java.io.IOException(e.getMessage());
317 // Finally test if the user has pasted just the sequence, no id
318 if (type.equalsIgnoreCase("Paste"))
322 // Possible sequence is just residues with no label
323 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
324 Alignment al = new Alignment(afile.getSeqsAsArray());
326 afile.addSeqGroups(al);
327 afile.addAnnotations(al);
330 } catch (Exception ex)
332 if (ex.toString().startsWith(INVALID_CHARACTERS))
334 throw new java.io.IOException(e.getMessage());
337 ex.printStackTrace();
341 // If we get to this stage, the format was not supported
342 throw new java.io.IOException(SUPPORTED_FORMATS);
347 * Constructs the correct filetype parser for an already open datasource
350 * an existing datasource
352 * File format of data that will be provided by datasource
354 * @return DOCUMENT ME!
356 public AlignmentI readFromFile(FileParse source, String format)
357 throws java.io.IOException
359 // TODO: generalise mapping between format string and io. class instances
360 // using Constructor.invoke reflection
361 // This is exactly the same as the readFile method except we substitute
362 // 'inFile, type' with 'source'
363 this.inFile = source.getInFile();
364 String type = source.type;
368 if (format.equals("FASTA"))
370 afile = new FastaFile(source);
372 else if (format.equals("MSF"))
374 afile = new MSFfile(source);
376 else if (format.equals("PileUp"))
378 afile = new PileUpfile(source);
380 else if (format.equals("CLUSTAL"))
382 afile = new ClustalFile(source);
384 else if (format.equals("BLC"))
386 afile = new BLCFile(source);
388 else if (format.equals("PIR"))
390 afile = new PIRFile(source);
392 else if (format.equals("PFAM"))
394 afile = new PfamFile(source);
396 else if (format.equals("JnetFile"))
398 afile = new JPredFile(source);
399 ((JPredFile) afile).removeNonSequences();
401 else if (format.equals("PDB"))
403 afile = new MCview.PDBfile(annotFromStructure,
404 localSecondaryStruct, serviceSecondaryStruct, source);
406 else if (format.equals("STH"))
408 afile = new StockholmFile(source);
410 else if (format.equals("RNAML"))
412 afile = new RnamlFile(source);
414 else if (format.equals("SimpleBLAST"))
416 afile = new SimpleBlastFile(source);
418 else if (format.equals(PhylipFile.FILE_DESC))
420 afile = new PhylipFile(source);
422 else if (format.equals(JSONFile.FILE_DESC))
424 afile = new JSONFile(source);
425 al = new Alignment(afile.getSeqsAsArray());
426 afile.addAnnotations(al);
427 afile.addSeqGroups(al);
430 else if (format.equals(HtmlFile.FILE_DESC))
432 afile = new HtmlFile(source);
434 al = new Alignment(afile.getSeqsAsArray());
435 afile.addAnnotations(al);
438 } catch (Exception e)
441 System.err.println("Failed to read alignment using the '" + format
442 + "' reader.\n" + e);
444 if (e.getMessage() != null
445 && e.getMessage().startsWith(INVALID_CHARACTERS))
447 throw new java.io.IOException(e.getMessage());
450 // Finally test if the user has pasted just the sequence, no id
451 if (type.equalsIgnoreCase("Paste"))
455 // Possible sequence is just residues with no label
456 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
457 Alignment al = new Alignment(afile.getSeqsAsArray());
458 afile.addAnnotations(al);
459 afile.addSeqGroups(al);
462 } catch (Exception ex)
464 if (ex.toString().startsWith(INVALID_CHARACTERS))
466 throw new java.io.IOException(e.getMessage());
469 ex.printStackTrace();
473 // If we get to this stage, the format was not supported
474 throw new java.io.IOException(SUPPORTED_FORMATS);
480 * create an alignment flatfile from a Jalview alignment view
484 * @param selectedOnly
485 * @return flatfile in a string
487 public String formatSequences(String format, boolean jvsuffix,
488 AlignViewportI av, boolean selectedOnly)
491 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
492 AlignmentI aselview = selvew.getVisibleAlignment(av
494 List<AlignmentAnnotation> ala = (av
495 .getVisibleAlignmentAnnotation(selectedOnly));
498 for (AlignmentAnnotation aa : ala)
500 aselview.addAnnotation(aa);
504 return formatSequences(format, aselview, jvsuffix);
508 * Construct an output class for an alignment in a particular filetype TODO:
509 * allow caller to detect errors and warnings encountered when generating
513 * string name of alignment format
515 * the alignment to be written out
517 * passed to AlnFile class controls whether /START-END is added to
520 * @return alignment flat file contents
522 public String formatSequences(String format, AlignmentI alignment,
527 AlignFile afile = null;
528 if (format.equalsIgnoreCase("FASTA"))
530 afile = new FastaFile();
532 else if (format.equalsIgnoreCase("MSF"))
534 afile = new MSFfile();
536 else if (format.equalsIgnoreCase("PileUp"))
538 afile = new PileUpfile();
540 else if (format.equalsIgnoreCase("CLUSTAL"))
542 afile = new ClustalFile();
544 else if (format.equalsIgnoreCase("BLC"))
546 afile = new BLCFile();
548 else if (format.equalsIgnoreCase("PIR"))
550 afile = new PIRFile();
552 else if (format.equalsIgnoreCase("PFAM"))
554 afile = new PfamFile();
556 else if (format.equalsIgnoreCase("STH"))
558 afile = new StockholmFile(alignment);
560 else if (format.equalsIgnoreCase("AMSA"))
562 afile = new AMSAFile(alignment);
564 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
566 afile = new PhylipFile();
568 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
570 afile = new JSONFile();
571 // Add groups to AlignFile
572 afile.seqGroups = alignment.getGroups();
574 // Add non auto calculated annotation to AlignFile
575 for (AlignmentAnnotation annot : alignment.getAlignmentAnnotation())
577 if (annot != null && !annot.autoCalculated)
579 if (annot.label.equals("PDB.CATempFactor"))
583 afile.annotations.add(annot);
587 else if (format.equalsIgnoreCase("RNAML"))
589 afile = new RnamlFile();
594 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
596 afile.setNewlineString(newline);
597 afile.addJVSuffix(jvsuffix);
599 afile.setSeqs(alignment.getSequencesArray());
602 String afileresp = afile.print();
603 if (afile.hasWarningMessage())
605 System.err.println("Warning raised when writing as " + format
606 + " : " + afile.getWarningMessage());
609 } catch (Exception e)
611 System.err.println("Failed to write alignment as a '" + format
619 public static String checkProtocol(String file)
621 String protocol = FILE;
622 String ft = file.toLowerCase().trim();
623 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
624 || ft.indexOf("file:") == 0)
631 public static void main(String[] args)
634 while (i < args.length)
636 File f = new File(args[i]);
641 System.out.println("Reading file: " + f);
642 AppletFormatAdapter afa = new AppletFormatAdapter();
643 Runtime r = Runtime.getRuntime();
645 long memf = -r.totalMemory() + r.freeMemory();
646 long t1 = -System.currentTimeMillis();
647 Alignment al = afa.readFile(args[i], FILE,
648 new IdentifyFile().Identify(args[i], FILE));
649 t1 += System.currentTimeMillis();
651 memf += r.totalMemory() - r.freeMemory();
654 System.out.println("Alignment contains " + al.getHeight()
655 + " sequences and " + al.getWidth() + " columns.");
658 System.out.println(new AppletFormatAdapter().formatSequences(
660 } catch (Exception e)
663 .println("Couln't format the alignment for output as a FASTA file.");
664 e.printStackTrace(System.err);
669 System.out.println("Couldn't read alignment");
671 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
673 .println("Difference between free memory now and before is "
674 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
675 } catch (Exception e)
677 System.err.println("Exception when dealing with " + i
678 + "'th argument: " + args[i] + "\n" + e);
683 System.err.println("Ignoring argument '" + args[i] + "' (" + i
684 + "'th)- not a readable file.");
691 * try to discover how to access the given file as a valid datasource that
692 * will be identified as the given type.
696 * @return protocol that yields the data parsable as the given type
698 public static String resolveProtocol(String file, String format)
700 return resolveProtocol(file, format, false);
703 public static String resolveProtocol(String file, String format,
706 // TODO: test thoroughly!
707 String protocol = null;
710 System.out.println("resolving datasource started with:\n>>file\n"
711 + file + ">>endfile");
714 // This might throw a security exception in certain browsers
715 // Netscape Communicator for instance.
719 InputStream is = System.getSecurityManager().getClass()
720 .getResourceAsStream("/" + file);
728 System.err.println("Resource '" + file + "' was "
729 + (rtn ? "" : "not") + " located by classloader.");
734 protocol = AppletFormatAdapter.CLASSLOADER;
737 } catch (Exception ex)
740 .println("Exception checking resources: " + file + " " + ex);
743 if (file.indexOf("://") > -1)
745 protocol = AppletFormatAdapter.URL;
749 // skipping codebase prepend check.
750 protocol = AppletFormatAdapter.FILE;
757 System.out.println("Trying to get contents of resource as "
760 fp = new FileParse(file, protocol);
769 System.out.println("Successful.");
772 } catch (Exception e)
776 System.err.println("Exception when accessing content: " + e);
784 System.out.println("Accessing as paste.");
786 protocol = AppletFormatAdapter.PASTE;
790 fp = new FileParse(file, protocol);
795 } catch (Exception e)
797 System.err.println("Failed to access content as paste!");
806 if (format == null || format.length() == 0)
814 String idformat = new jalview.io.IdentifyFile().Identify(file,
816 if (idformat == null)
820 System.out.println("Format not identified. Inaccessible file.");
826 System.out.println("Format identified as " + idformat
827 + "and expected as " + format);
829 if (idformat.equals(format))
833 System.out.println("Protocol identified as " + protocol);
842 .println("File deemed not accessible via " + protocol);
847 } catch (Exception e)
851 System.err.println("File deemed not accessible via " + protocol);