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;
30 import java.io.InputStream;
31 import java.util.List;
34 * A low level class for alignment and feature IO with alignment formatting
35 * methods used by both applet and application for generating flat alignment
36 * files. It also holds the lists of magic format names that the applet and
37 * application will allow the user to read or write files with.
42 public class AppletFormatAdapter
45 * List of valid format strings used in the isValidFormat method
47 public static final String[] READABLE_FORMATS = new String[]
48 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
49 "PDB", "JnetFile", "RNAML", PhylipFile.FILE_DESC }; // , "SimpleBLAST" };
52 * List of valid format strings for use by callers of the formatSequences
55 public static final String[] WRITEABLE_FORMATS = new String[]
56 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
57 "STH", PhylipFile.FILE_DESC };
60 * List of extensions corresponding to file format types in WRITABLE_FNAMES
61 * that are writable by the application.
63 public static final String[] WRITABLE_EXTENSIONS = new String[]
64 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
65 "jvp", "sto,stk", "jar", PhylipFile.FILE_EXT };
68 * List of writable formats by the application. Order must correspond with the
69 * WRITABLE_EXTENSIONS list of formats.
71 public static final String[] WRITABLE_FNAMES = new String[]
72 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
73 "STH", "Jalview", PhylipFile.FILE_DESC };
76 * List of readable format file extensions by application in order
77 * corresponding to READABLE_FNAMES
79 public static final String[] READABLE_EXTENSIONS = new String[]
80 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
81 "jar,jvp", "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT }; // ".blast"
84 * List of readable formats by application in order corresponding to
87 public static final String[] READABLE_FNAMES = new String[]
88 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
89 "Stockholm", "RNAML", PhylipFile.FILE_DESC };// ,
94 public static String INVALID_CHARACTERS = "Contains invalid characters";
96 // TODO: make these messages dynamic
97 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
98 + prettyPrint(READABLE_FORMATS);
103 * @return grammatically correct(ish) list consisting of els elements.
105 public static String prettyPrint(String[] els)
107 StringBuffer list = new StringBuffer();
108 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
113 list.append(" and " + els[els.length - 1] + ".");
114 return list.toString();
117 public static String FILE = "File";
119 public static String URL = "URL";
121 public static String PASTE = "Paste";
123 public static String CLASSLOADER = "ClassLoader";
125 AlignFile afile = null;
130 * character used to write newlines
132 protected String newline = System.getProperty("line.separator");
134 public void setNewlineString(String nl)
139 public String getNewlineString()
145 * check that this format is valid for reading
148 * a format string to be compared with READABLE_FORMATS
149 * @return true if format is readable
151 public static final boolean isValidFormat(String format)
153 return isValidFormat(format, false);
157 * validate format is valid for IO
160 * a format string to be compared with either READABLE_FORMATS or
163 * when true, format is checked for containment in WRITEABLE_FORMATS
164 * @return true if format is valid
166 public static final boolean isValidFormat(String format,
169 boolean valid = false;
170 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
172 for (String element : format_list)
174 if (element.equalsIgnoreCase(format))
184 * Constructs the correct filetype parser for a characterised datasource
191 * File format of data provided by datasource
193 * @return DOCUMENT ME!
195 public Alignment readFile(String inFile, String type, String format)
196 throws java.io.IOException
198 // TODO: generalise mapping between format string and io. class instances
199 // using Constructor.invoke reflection
200 this.inFile = inFile;
203 if (format.equals("FASTA"))
205 afile = new FastaFile(inFile, type);
207 else if (format.equals("MSF"))
209 afile = new MSFfile(inFile, type);
211 else if (format.equals("PileUp"))
213 afile = new PileUpfile(inFile, type);
215 else if (format.equals("CLUSTAL"))
217 afile = new ClustalFile(inFile, type);
219 else if (format.equals("BLC"))
221 afile = new BLCFile(inFile, type);
223 else if (format.equals("PIR"))
225 afile = new PIRFile(inFile, type);
227 else if (format.equals("PFAM"))
229 afile = new PfamFile(inFile, type);
231 else if (format.equals("JnetFile"))
233 afile = new JPredFile(inFile, type);
234 ((JPredFile) afile).removeNonSequences();
236 else if (format.equals("PDB"))
238 afile = new MCview.PDBfile(inFile, type);
239 // Uncomment to test Jmol data based PDB processing: JAL-1213
240 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
242 else if (format.equals("STH"))
244 afile = new StockholmFile(inFile, type);
246 else if (format.equals("SimpleBLAST"))
248 afile = new SimpleBlastFile(inFile, type);
250 else if (format.equals(PhylipFile.FILE_DESC))
252 afile = new PhylipFile(inFile, type);
254 else if (format.equals("RNAML"))
256 afile = new RnamlFile(inFile, type);
259 Alignment al = new Alignment(afile.getSeqsAsArray());
261 afile.addAnnotations(al);
264 } catch (Exception e)
267 System.err.println("Failed to read alignment using the '" + format
268 + "' reader.\n" + e);
270 if (e.getMessage() != null
271 && e.getMessage().startsWith(INVALID_CHARACTERS))
273 throw new java.io.IOException(e.getMessage());
276 // Finally test if the user has pasted just the sequence, no id
277 if (type.equalsIgnoreCase("Paste"))
281 // Possible sequence is just residues with no label
282 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
283 Alignment al = new Alignment(afile.getSeqsAsArray());
284 afile.addAnnotations(al);
287 } catch (Exception ex)
289 if (ex.toString().startsWith(INVALID_CHARACTERS))
291 throw new java.io.IOException(e.getMessage());
294 ex.printStackTrace();
298 // If we get to this stage, the format was not supported
299 throw new java.io.IOException(SUPPORTED_FORMATS);
304 * Constructs the correct filetype parser for an already open datasource
307 * an existing datasource
309 * File format of data that will be provided by datasource
311 * @return DOCUMENT ME!
313 public AlignmentI readFromFile(FileParse source, String format)
314 throws java.io.IOException
316 // TODO: generalise mapping between format string and io. class instances
317 // using Constructor.invoke reflection
318 // This is exactly the same as the readFile method except we substitute
319 // 'inFile, type' with 'source'
320 this.inFile = source.getInFile();
321 String type = source.type;
324 if (format.equals("FASTA"))
326 afile = new FastaFile(source);
328 else if (format.equals("MSF"))
330 afile = new MSFfile(source);
332 else if (format.equals("PileUp"))
334 afile = new PileUpfile(source);
336 else if (format.equals("CLUSTAL"))
338 afile = new ClustalFile(source);
340 else if (format.equals("BLC"))
342 afile = new BLCFile(source);
344 else if (format.equals("PIR"))
346 afile = new PIRFile(source);
348 else if (format.equals("PFAM"))
350 afile = new PfamFile(source);
352 else if (format.equals("JnetFile"))
354 afile = new JPredFile(source);
355 ((JPredFile) afile).removeNonSequences();
357 else if (format.equals("PDB"))
359 afile = new MCview.PDBfile(source);
361 else if (format.equals("STH"))
363 afile = new StockholmFile(source);
365 else if (format.equals("RNAML"))
367 afile = new RnamlFile(source);
369 else if (format.equals("SimpleBLAST"))
371 afile = new SimpleBlastFile(source);
373 else if (format.equals(PhylipFile.FILE_DESC))
375 afile = new PhylipFile(source);
377 Alignment al = new Alignment(afile.getSeqsAsArray());
379 afile.addAnnotations(al);
382 } catch (Exception e)
385 System.err.println("Failed to read alignment using the '" + format
386 + "' reader.\n" + e);
388 if (e.getMessage() != null
389 && e.getMessage().startsWith(INVALID_CHARACTERS))
391 throw new java.io.IOException(e.getMessage());
394 // Finally test if the user has pasted just the sequence, no id
395 if (type.equalsIgnoreCase("Paste"))
399 // Possible sequence is just residues with no label
400 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
401 Alignment al = new Alignment(afile.getSeqsAsArray());
402 afile.addAnnotations(al);
405 } catch (Exception ex)
407 if (ex.toString().startsWith(INVALID_CHARACTERS))
409 throw new java.io.IOException(e.getMessage());
412 ex.printStackTrace();
416 // If we get to this stage, the format was not supported
417 throw new java.io.IOException(SUPPORTED_FORMATS);
423 * create an alignment flatfile from a Jalview alignment view
427 * @param selectedOnly
428 * @return flatfile in a string
430 public String formatSequences(String format, boolean jvsuffix,
431 AlignViewportI av, boolean selectedOnly)
434 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
435 AlignmentI aselview = selvew.getVisibleAlignment(av
437 List<AlignmentAnnotation> ala = (av
438 .getVisibleAlignmentAnnotation(selectedOnly));
441 for (AlignmentAnnotation aa : ala)
443 aselview.addAnnotation(aa);
447 return formatSequences(format, aselview, jvsuffix);
451 * Construct an output class for an alignment in a particular filetype TODO:
452 * allow caller to detect errors and warnings encountered when generating
456 * string name of alignment format
458 * the alignment to be written out
460 * passed to AlnFile class controls whether /START-END is added to
463 * @return alignment flat file contents
465 public String formatSequences(String format, AlignmentI alignment,
470 AlignFile afile = null;
472 if (format.equalsIgnoreCase("FASTA"))
474 afile = new FastaFile();
476 else if (format.equalsIgnoreCase("MSF"))
478 afile = new MSFfile();
480 else if (format.equalsIgnoreCase("PileUp"))
482 afile = new PileUpfile();
484 else if (format.equalsIgnoreCase("CLUSTAL"))
486 afile = new ClustalFile();
488 else if (format.equalsIgnoreCase("BLC"))
490 afile = new BLCFile();
492 else if (format.equalsIgnoreCase("PIR"))
494 afile = new PIRFile();
496 else if (format.equalsIgnoreCase("PFAM"))
498 afile = new PfamFile();
500 else if (format.equalsIgnoreCase("STH"))
502 afile = new StockholmFile(alignment);
504 else if (format.equalsIgnoreCase("AMSA"))
506 afile = new AMSAFile(alignment);
508 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
510 afile = new PhylipFile();
512 else if (format.equalsIgnoreCase("RNAML"))
514 afile = new RnamlFile();
520 "Implementation error: Unknown file format string");
522 afile.setNewlineString(newline);
523 afile.addJVSuffix(jvsuffix);
525 afile.setSeqs(alignment.getSequencesArray());
527 String afileresp = afile.print();
528 if (afile.hasWarningMessage())
530 System.err.println("Warning raised when writing as " + format
531 + " : " + afile.getWarningMessage());
534 } catch (Exception e)
536 System.err.println("Failed to write alignment as a '" + format
544 public static String checkProtocol(String file)
546 String protocol = FILE;
547 String ft = file.toLowerCase().trim();
548 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
549 || ft.indexOf("file:") == 0)
556 public static void main(String[] args)
559 while (i < args.length)
561 File f = new File(args[i]);
566 System.out.println("Reading file: " + f);
567 AppletFormatAdapter afa = new AppletFormatAdapter();
568 Runtime r = Runtime.getRuntime();
570 long memf = -r.totalMemory() + r.freeMemory();
571 long t1 = -System.currentTimeMillis();
572 Alignment al = afa.readFile(args[i], FILE,
573 new IdentifyFile().Identify(args[i], FILE));
574 t1 += System.currentTimeMillis();
576 memf += r.totalMemory() - r.freeMemory();
579 System.out.println("Alignment contains " + al.getHeight()
580 + " sequences and " + al.getWidth() + " columns.");
583 System.out.println(new AppletFormatAdapter().formatSequences(
585 } catch (Exception e)
588 .println("Couln't format the alignment for output as a FASTA file.");
589 e.printStackTrace(System.err);
594 System.out.println("Couldn't read alignment");
596 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
598 .println("Difference between free memory now and before is "
599 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
600 } catch (Exception e)
602 System.err.println("Exception when dealing with " + i
603 + "'th argument: " + args[i] + "\n" + e);
608 System.err.println("Ignoring argument '" + args[i] + "' (" + i
609 + "'th)- not a readable file.");
616 * try to discover how to access the given file as a valid datasource that
617 * will be identified as the given type.
621 * @return protocol that yields the data parsable as the given type
623 public static String resolveProtocol(String file, String format)
625 return resolveProtocol(file, format, false);
628 public static String resolveProtocol(String file, String format,
631 // TODO: test thoroughly!
632 String protocol = null;
635 System.out.println("resolving datasource started with:\n>>file\n"
636 + file + ">>endfile");
639 // This might throw a security exception in certain browsers
640 // Netscape Communicator for instance.
644 InputStream is = System.getSecurityManager().getClass()
645 .getResourceAsStream("/" + file);
653 System.err.println("Resource '" + file + "' was "
654 + (rtn ? "" : "not") + " located by classloader.");
659 protocol = AppletFormatAdapter.CLASSLOADER;
662 } catch (Exception ex)
665 .println("Exception checking resources: " + file + " " + ex);
668 if (file.indexOf("://") > -1)
670 protocol = AppletFormatAdapter.URL;
674 // skipping codebase prepend check.
675 protocol = AppletFormatAdapter.FILE;
682 System.out.println("Trying to get contents of resource as "
685 fp = new FileParse(file, protocol);
694 System.out.println("Successful.");
697 } catch (Exception e)
701 System.err.println("Exception when accessing content: " + e);
709 System.out.println("Accessing as paste.");
711 protocol = AppletFormatAdapter.PASTE;
715 fp = new FileParse(file, protocol);
720 } catch (Exception e)
722 System.err.println("Failed to access content as paste!");
731 if (format == null || format.length() == 0)
739 String idformat = new jalview.io.IdentifyFile().Identify(file,
741 if (idformat == null)
745 System.out.println("Format not identified. Inaccessible file.");
751 System.out.println("Format identified as " + idformat
752 + "and expected as " + format);
754 if (idformat.equals(format))
758 System.out.println("Protocol identified as " + protocol);
767 .println("File deemed not accessible via " + protocol);
772 } catch (Exception e)
776 System.err.println("File deemed not accessible via " + protocol);