2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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
46 * List of valid format strings used in the isValidFormat method
48 public static final String[] READABLE_FORMATS = new String[]
49 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
50 "PDB", "JnetFile", "RNAML", PhylipFile.FILE_DESC }; // , "SimpleBLAST" };
53 * List of readable format file extensions by application in order
54 * corresponding to READABLE_FNAMES
56 public static final String[] READABLE_EXTENSIONS = new String[]
57 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
58 "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT, "jar,jvp" };
61 * List of readable formats by application in order corresponding to
64 public static final String[] READABLE_FNAMES = new String[]
65 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm",
66 "RNAML", PhylipFile.FILE_DESC, "Jalview" };
69 * List of valid format strings for use by callers of the formatSequences
72 public static final String[] WRITEABLE_FORMATS = new String[]
73 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
74 "STH", PhylipFile.FILE_DESC };
77 * List of extensions corresponding to file format types in WRITABLE_FNAMES
78 * that are writable by the application.
80 public static final String[] WRITABLE_EXTENSIONS = new String[]
81 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
82 "jvp", "sto,stk", "jar", PhylipFile.FILE_EXT };
85 * List of writable formats by the application. Order must correspond with the
86 * WRITABLE_EXTENSIONS list of formats.
88 public static final String[] WRITABLE_FNAMES = new String[]
89 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
90 "STH", "Jalview", PhylipFile.FILE_DESC };
95 public static String INVALID_CHARACTERS = "Contains invalid characters";
97 // TODO: make these messages dynamic
98 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
99 + prettyPrint(READABLE_FORMATS);
104 * @return grammatically correct(ish) list consisting of els elements.
106 public static String prettyPrint(String[] els)
108 StringBuffer list = new StringBuffer();
109 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
114 list.append(" and " + els[els.length - 1] + ".");
115 return list.toString();
118 public static String FILE = "File";
120 public static String URL = "URL";
122 public static String PASTE = "Paste";
124 public static String CLASSLOADER = "ClassLoader";
127 * add jalview-derived non-secondary structure annotation from PDB structure
129 boolean annotFromStructure = false;
132 * add secondary structure from PDB data with built-in algorithms
134 boolean localSecondaryStruct = false;
137 * process PDB data with web services
139 boolean serviceSecondaryStruct = false;
141 AlignFile afile = null;
146 * character used to write newlines
148 protected String newline = System.getProperty("line.separator");
150 public void setNewlineString(String nl)
155 public String getNewlineString()
161 * check that this format is valid for reading
164 * a format string to be compared with READABLE_FORMATS
165 * @return true if format is readable
167 public static final boolean isValidFormat(String format)
169 return isValidFormat(format, false);
173 * validate format is valid for IO
176 * a format string to be compared with either READABLE_FORMATS or
179 * when true, format is checked for containment in WRITEABLE_FORMATS
180 * @return true if format is valid
182 public static final boolean isValidFormat(String format,
185 boolean valid = false;
186 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
188 for (String element : format_list)
190 if (element.equalsIgnoreCase(format))
200 * Constructs the correct filetype parser for a characterised datasource
207 * File format of data provided by datasource
209 * @return DOCUMENT ME!
211 public Alignment readFile(String inFile, String type, String format)
212 throws java.io.IOException
214 // TODO: generalise mapping between format string and io. class instances
215 // using Constructor.invoke reflection
216 this.inFile = inFile;
219 if (format.equals("FASTA"))
221 afile = new FastaFile(inFile, type);
223 else if (format.equals("MSF"))
225 afile = new MSFfile(inFile, type);
227 else if (format.equals("PileUp"))
229 afile = new PileUpfile(inFile, type);
231 else if (format.equals("CLUSTAL"))
233 afile = new ClustalFile(inFile, type);
235 else if (format.equals("BLC"))
237 afile = new BLCFile(inFile, type);
239 else if (format.equals("PIR"))
241 afile = new PIRFile(inFile, type);
243 else if (format.equals("PFAM"))
245 afile = new PfamFile(inFile, type);
247 else if (format.equals("JnetFile"))
249 afile = new JPredFile(inFile, type);
250 ((JPredFile) afile).removeNonSequences();
252 else if (format.equals("PDB"))
254 afile = new MCview.PDBfile(annotFromStructure,
255 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
256 // Uncomment to test Jmol data based PDB processing: JAL-1213
257 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
259 else if (format.equals("STH"))
261 afile = new StockholmFile(inFile, type);
263 else if (format.equals("SimpleBLAST"))
265 afile = new SimpleBlastFile(inFile, type);
267 else if (format.equals(PhylipFile.FILE_DESC))
269 afile = new PhylipFile(inFile, type);
271 else if (format.equals("RNAML"))
273 afile = new RnamlFile(inFile, type);
276 Alignment al = new Alignment(afile.getSeqsAsArray());
278 afile.addAnnotations(al);
281 } catch (Exception e)
284 System.err.println("Failed to read alignment using the '" + format
285 + "' reader.\n" + e);
287 if (e.getMessage() != null
288 && e.getMessage().startsWith(INVALID_CHARACTERS))
290 throw new java.io.IOException(e.getMessage());
293 // Finally test if the user has pasted just the sequence, no id
294 if (type.equalsIgnoreCase("Paste"))
298 // Possible sequence is just residues with no label
299 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
300 Alignment al = new Alignment(afile.getSeqsAsArray());
301 afile.addAnnotations(al);
304 } catch (Exception ex)
306 if (ex.toString().startsWith(INVALID_CHARACTERS))
308 throw new java.io.IOException(e.getMessage());
311 ex.printStackTrace();
315 // If we get to this stage, the format was not supported
316 throw new java.io.IOException(SUPPORTED_FORMATS);
321 * Constructs the correct filetype parser for an already open datasource
324 * an existing datasource
326 * File format of data that will be provided by datasource
328 * @return DOCUMENT ME!
330 public AlignmentI readFromFile(FileParse source, String format)
331 throws java.io.IOException
333 // TODO: generalise mapping between format string and io. class instances
334 // using Constructor.invoke reflection
335 // This is exactly the same as the readFile method except we substitute
336 // 'inFile, type' with 'source'
337 this.inFile = source.getInFile();
338 String type = source.type;
341 if (format.equals("FASTA"))
343 afile = new FastaFile(source);
345 else if (format.equals("MSF"))
347 afile = new MSFfile(source);
349 else if (format.equals("PileUp"))
351 afile = new PileUpfile(source);
353 else if (format.equals("CLUSTAL"))
355 afile = new ClustalFile(source);
357 else if (format.equals("BLC"))
359 afile = new BLCFile(source);
361 else if (format.equals("PIR"))
363 afile = new PIRFile(source);
365 else if (format.equals("PFAM"))
367 afile = new PfamFile(source);
369 else if (format.equals("JnetFile"))
371 afile = new JPredFile(source);
372 ((JPredFile) afile).removeNonSequences();
374 else if (format.equals("PDB"))
376 afile = new MCview.PDBfile(annotFromStructure,
377 localSecondaryStruct, serviceSecondaryStruct, source);
379 else if (format.equals("STH"))
381 afile = new StockholmFile(source);
383 else if (format.equals("RNAML"))
385 afile = new RnamlFile(source);
387 else if (format.equals("SimpleBLAST"))
389 afile = new SimpleBlastFile(source);
391 else if (format.equals(PhylipFile.FILE_DESC))
393 afile = new PhylipFile(source);
395 Alignment al = new Alignment(afile.getSeqsAsArray());
397 afile.addAnnotations(al);
400 } catch (Exception e)
403 System.err.println("Failed to read alignment using the '" + format
404 + "' reader.\n" + e);
406 if (e.getMessage() != null
407 && e.getMessage().startsWith(INVALID_CHARACTERS))
409 throw new java.io.IOException(e.getMessage());
412 // Finally test if the user has pasted just the sequence, no id
413 if (type.equalsIgnoreCase("Paste"))
417 // Possible sequence is just residues with no label
418 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
419 Alignment al = new Alignment(afile.getSeqsAsArray());
420 afile.addAnnotations(al);
423 } catch (Exception ex)
425 if (ex.toString().startsWith(INVALID_CHARACTERS))
427 throw new java.io.IOException(e.getMessage());
430 ex.printStackTrace();
434 // If we get to this stage, the format was not supported
435 throw new java.io.IOException(SUPPORTED_FORMATS);
441 * create an alignment flatfile from a Jalview alignment view
445 * @param selectedOnly
446 * @return flatfile in a string
448 public String formatSequences(String format, boolean jvsuffix,
449 AlignViewportI av, boolean selectedOnly)
452 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
453 AlignmentI aselview = selvew.getVisibleAlignment(av
455 List<AlignmentAnnotation> ala = (av
456 .getVisibleAlignmentAnnotation(selectedOnly));
459 for (AlignmentAnnotation aa : ala)
461 aselview.addAnnotation(aa);
465 return formatSequences(format, aselview, jvsuffix);
469 * Construct an output class for an alignment in a particular filetype TODO:
470 * allow caller to detect errors and warnings encountered when generating
474 * string name of alignment format
476 * the alignment to be written out
478 * passed to AlnFile class controls whether /START-END is added to
481 * @return alignment flat file contents
483 public String formatSequences(String format, AlignmentI alignment,
488 AlignFile afile = null;
490 if (format.equalsIgnoreCase("FASTA"))
492 afile = new FastaFile();
494 else if (format.equalsIgnoreCase("MSF"))
496 afile = new MSFfile();
498 else if (format.equalsIgnoreCase("PileUp"))
500 afile = new PileUpfile();
502 else if (format.equalsIgnoreCase("CLUSTAL"))
504 afile = new ClustalFile();
506 else if (format.equalsIgnoreCase("BLC"))
508 afile = new BLCFile();
510 else if (format.equalsIgnoreCase("PIR"))
512 afile = new PIRFile();
514 else if (format.equalsIgnoreCase("PFAM"))
516 afile = new PfamFile();
518 else if (format.equalsIgnoreCase("STH"))
520 afile = new StockholmFile(alignment);
522 else if (format.equalsIgnoreCase("AMSA"))
524 afile = new AMSAFile(alignment);
526 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
528 afile = new PhylipFile();
530 else if (format.equalsIgnoreCase("RNAML"))
532 afile = new RnamlFile();
537 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
539 afile.setNewlineString(newline);
540 afile.addJVSuffix(jvsuffix);
542 afile.setSeqs(alignment.getSequencesArray());
544 String afileresp = afile.print();
545 if (afile.hasWarningMessage())
547 System.err.println("Warning raised when writing as " + format
548 + " : " + afile.getWarningMessage());
551 } catch (Exception e)
553 System.err.println("Failed to write alignment as a '" + format
561 public static String checkProtocol(String file)
563 String protocol = FILE;
564 String ft = file.toLowerCase().trim();
565 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
566 || ft.indexOf("file:") == 0)
573 public static void main(String[] args)
576 while (i < args.length)
578 File f = new File(args[i]);
583 System.out.println("Reading file: " + f);
584 AppletFormatAdapter afa = new AppletFormatAdapter();
585 Runtime r = Runtime.getRuntime();
587 long memf = -r.totalMemory() + r.freeMemory();
588 long t1 = -System.currentTimeMillis();
589 Alignment al = afa.readFile(args[i], FILE,
590 new IdentifyFile().Identify(args[i], FILE));
591 t1 += System.currentTimeMillis();
593 memf += r.totalMemory() - r.freeMemory();
596 System.out.println("Alignment contains " + al.getHeight()
597 + " sequences and " + al.getWidth() + " columns.");
600 System.out.println(new AppletFormatAdapter().formatSequences(
602 } catch (Exception e)
605 .println("Couln't format the alignment for output as a FASTA file.");
606 e.printStackTrace(System.err);
611 System.out.println("Couldn't read alignment");
613 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
615 .println("Difference between free memory now and before is "
616 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
617 } catch (Exception e)
619 System.err.println("Exception when dealing with " + i
620 + "'th argument: " + args[i] + "\n" + e);
625 System.err.println("Ignoring argument '" + args[i] + "' (" + i
626 + "'th)- not a readable file.");
633 * try to discover how to access the given file as a valid datasource that
634 * will be identified as the given type.
638 * @return protocol that yields the data parsable as the given type
640 public static String resolveProtocol(String file, String format)
642 return resolveProtocol(file, format, false);
645 public static String resolveProtocol(String file, String format,
648 // TODO: test thoroughly!
649 String protocol = null;
652 System.out.println("resolving datasource started with:\n>>file\n"
653 + file + ">>endfile");
656 // This might throw a security exception in certain browsers
657 // Netscape Communicator for instance.
661 InputStream is = System.getSecurityManager().getClass()
662 .getResourceAsStream("/" + file);
670 System.err.println("Resource '" + file + "' was "
671 + (rtn ? "" : "not") + " located by classloader.");
676 protocol = AppletFormatAdapter.CLASSLOADER;
679 } catch (Exception ex)
682 .println("Exception checking resources: " + file + " " + ex);
685 if (file.indexOf("://") > -1)
687 protocol = AppletFormatAdapter.URL;
691 // skipping codebase prepend check.
692 protocol = AppletFormatAdapter.FILE;
699 System.out.println("Trying to get contents of resource as "
702 fp = new FileParse(file, protocol);
711 System.out.println("Successful.");
714 } catch (Exception e)
718 System.err.println("Exception when accessing content: " + e);
726 System.out.println("Accessing as paste.");
728 protocol = AppletFormatAdapter.PASTE;
732 fp = new FileParse(file, protocol);
737 } catch (Exception e)
739 System.err.println("Failed to access content as paste!");
748 if (format == null || format.length() == 0)
756 String idformat = new jalview.io.IdentifyFile().Identify(file,
758 if (idformat == null)
762 System.out.println("Format not identified. Inaccessible file.");
768 System.out.println("Format identified as " + idformat
769 + "and expected as " + format);
771 if (idformat.equals(format))
775 System.out.println("Protocol identified as " + protocol);
784 .println("File deemed not accessible via " + protocol);
789 } catch (Exception e)
793 System.err.println("File deemed not accessible via " + protocol);