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, "HTML" }; // ,
55 * List of valid format strings for use by callers of the formatSequences
58 public static final String[] WRITEABLE_FORMATS = new String[]
59 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
60 "STH", PhylipFile.FILE_DESC };
63 * List of extensions corresponding to file format types in WRITABLE_FNAMES
64 * that are writable by the application.
66 public static final String[] WRITABLE_EXTENSIONS = new String[]
67 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
68 "jvp", "sto,stk", "jar", PhylipFile.FILE_EXT };
71 * List of writable formats by the application. Order must correspond with the
72 * WRITABLE_EXTENSIONS list of formats.
74 public static final String[] WRITABLE_FNAMES = new String[]
75 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
76 "STH", "Jalview", PhylipFile.FILE_DESC };
79 * List of readable format file extensions by application in order
80 * corresponding to READABLE_FNAMES
82 public static final String[] READABLE_EXTENSIONS = new String[]
83 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
84 "jar,jvp", "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT,
88 * List of readable formats by application in order corresponding to
91 public static final String[] READABLE_FNAMES = new String[]
92 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
93 "Stockholm", "RNAML", PhylipFile.FILE_DESC, "HTML" };// ,
98 public static String INVALID_CHARACTERS = "Contains invalid characters";
100 // TODO: make these messages dynamic
101 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
102 + prettyPrint(READABLE_FORMATS);
107 * @return grammatically correct(ish) list consisting of els elements.
109 public static String prettyPrint(String[] els)
111 StringBuffer list = new StringBuffer();
112 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
117 list.append(" and " + els[els.length - 1] + ".");
118 return list.toString();
121 public static String FILE = "File";
123 public static String URL = "URL";
125 public static String PASTE = "Paste";
127 public static String CLASSLOADER = "ClassLoader";
129 AlignFile afile = null;
134 * character used to write newlines
136 protected String newline = System.getProperty("line.separator");
138 public void setNewlineString(String nl)
143 public String getNewlineString()
149 * check that this format is valid for reading
152 * a format string to be compared with READABLE_FORMATS
153 * @return true if format is readable
155 public static final boolean isValidFormat(String format)
157 return isValidFormat(format, false);
161 * validate format is valid for IO
164 * a format string to be compared with either READABLE_FORMATS or
167 * when true, format is checked for containment in WRITEABLE_FORMATS
168 * @return true if format is valid
170 public static final boolean isValidFormat(String format,
173 boolean valid = false;
174 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
176 for (String element : format_list)
178 if (element.equalsIgnoreCase(format))
188 * Constructs the correct filetype parser for a characterised datasource
195 * File format of data provided by datasource
197 * @return DOCUMENT ME!
199 public Alignment readFile(String inFile, String type, String format)
200 throws java.io.IOException
202 // TODO: generalise mapping between format string and io. class instances
203 // using Constructor.invoke reflection
204 this.inFile = inFile;
207 if (format.equals("FASTA"))
209 afile = new FastaFile(inFile, type);
211 else if (format.equals("MSF"))
213 afile = new MSFfile(inFile, type);
215 else if (format.equals("PileUp"))
217 afile = new PileUpfile(inFile, type);
219 else if (format.equals("CLUSTAL"))
221 afile = new ClustalFile(inFile, type);
223 else if (format.equals("BLC"))
225 afile = new BLCFile(inFile, type);
227 else if (format.equals("PIR"))
229 afile = new PIRFile(inFile, type);
231 else if (format.equals("PFAM"))
233 afile = new PfamFile(inFile, type);
235 else if (format.equals("JnetFile"))
237 afile = new JPredFile(inFile, type);
238 ((JPredFile) afile).removeNonSequences();
240 else if (format.equals("PDB"))
242 afile = new MCview.PDBfile(true,true,inFile, type);
243 // Uncomment to test Jmol data based PDB processing: JAL-1213
244 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
246 else if (format.equals("STH"))
248 afile = new StockholmFile(inFile, type);
250 else if (format.equals("SimpleBLAST"))
252 afile = new SimpleBlastFile(inFile, type);
254 else if (format.equals(PhylipFile.FILE_DESC))
256 afile = new PhylipFile(inFile, type);
258 // else if (format.equals(HtmlFile.FILE_DESC))
260 // afile = new HtmlFile(inFile, type);
262 else if (format.equals("RNAML"))
264 afile = new RnamlFile(inFile, type);
267 Alignment al = new Alignment(afile.getSeqsAsArray());
269 afile.addAnnotations(al);
272 } catch (Exception e)
275 System.err.println("Failed to read alignment using the '" + format
276 + "' reader.\n" + e);
278 if (e.getMessage() != null
279 && e.getMessage().startsWith(INVALID_CHARACTERS))
281 throw new java.io.IOException(e.getMessage());
284 // Finally test if the user has pasted just the sequence, no id
285 if (type.equalsIgnoreCase("Paste"))
289 // Possible sequence is just residues with no label
290 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
291 Alignment al = new Alignment(afile.getSeqsAsArray());
292 afile.addAnnotations(al);
295 } catch (Exception ex)
297 if (ex.toString().startsWith(INVALID_CHARACTERS))
299 throw new java.io.IOException(e.getMessage());
302 ex.printStackTrace();
306 // If we get to this stage, the format was not supported
307 throw new java.io.IOException(SUPPORTED_FORMATS);
312 * Constructs the correct filetype parser for an already open datasource
315 * an existing datasource
317 * File format of data that will be provided by datasource
319 * @return DOCUMENT ME!
321 public AlignmentI readFromFile(FileParse source, String format)
322 throws java.io.IOException
324 // TODO: generalise mapping between format string and io. class instances
325 // using Constructor.invoke reflection
326 // This is exactly the same as the readFile method except we substitute
327 // 'inFile, type' with 'source'
328 this.inFile = source.getInFile();
329 String type = source.type;
332 if (format.equals("FASTA"))
334 afile = new FastaFile(source);
336 else if (format.equals("MSF"))
338 afile = new MSFfile(source);
340 else if (format.equals("PileUp"))
342 afile = new PileUpfile(source);
344 else if (format.equals("CLUSTAL"))
346 afile = new ClustalFile(source);
348 else if (format.equals("BLC"))
350 afile = new BLCFile(source);
352 else if (format.equals("PIR"))
354 afile = new PIRFile(source);
356 else if (format.equals("PFAM"))
358 afile = new PfamFile(source);
360 else if (format.equals("JnetFile"))
362 afile = new JPredFile(source);
363 ((JPredFile) afile).removeNonSequences();
365 else if (format.equals("PDB"))
367 afile = new MCview.PDBfile(true,true,source);
369 else if (format.equals("STH"))
371 afile = new StockholmFile(source);
373 else if (format.equals("RNAML"))
375 afile = new RnamlFile(source);
377 else if (format.equals("SimpleBLAST"))
379 afile = new SimpleBlastFile(source);
381 else if (format.equals(PhylipFile.FILE_DESC))
383 afile = new PhylipFile(source);
385 // else if (format.equals(HtmlFile.FILE_DESC))
387 // afile = new HtmlFile(source);
389 Alignment al = new Alignment(afile.getSeqsAsArray());
391 afile.addAnnotations(al);
394 } catch (Exception e)
397 System.err.println("Failed to read alignment using the '" + format
398 + "' reader.\n" + e);
400 if (e.getMessage() != null
401 && e.getMessage().startsWith(INVALID_CHARACTERS))
403 throw new java.io.IOException(e.getMessage());
406 // Finally test if the user has pasted just the sequence, no id
407 if (type.equalsIgnoreCase("Paste"))
411 // Possible sequence is just residues with no label
412 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
413 Alignment al = new Alignment(afile.getSeqsAsArray());
414 afile.addAnnotations(al);
417 } catch (Exception ex)
419 if (ex.toString().startsWith(INVALID_CHARACTERS))
421 throw new java.io.IOException(e.getMessage());
424 ex.printStackTrace();
428 // If we get to this stage, the format was not supported
429 throw new java.io.IOException(SUPPORTED_FORMATS);
435 * create an alignment flatfile from a Jalview alignment view
439 * @param selectedOnly
440 * @return flatfile in a string
442 public String formatSequences(String format, boolean jvsuffix,
443 AlignViewportI av, boolean selectedOnly)
446 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
447 AlignmentI aselview = selvew.getVisibleAlignment(av
449 List<AlignmentAnnotation> ala = (av
450 .getVisibleAlignmentAnnotation(selectedOnly));
453 for (AlignmentAnnotation aa : ala)
455 aselview.addAnnotation(aa);
459 return formatSequences(format, aselview, jvsuffix);
463 * Construct an output class for an alignment in a particular filetype TODO:
464 * allow caller to detect errors and warnings encountered when generating
468 * string name of alignment format
470 * the alignment to be written out
472 * passed to AlnFile class controls whether /START-END is added to
475 * @return alignment flat file contents
477 public String formatSequences(String format, AlignmentI alignment,
482 AlignFile afile = null;
484 if (format.equalsIgnoreCase("FASTA"))
486 afile = new FastaFile();
488 else if (format.equalsIgnoreCase("MSF"))
490 afile = new MSFfile();
492 else if (format.equalsIgnoreCase("PileUp"))
494 afile = new PileUpfile();
496 else if (format.equalsIgnoreCase("CLUSTAL"))
498 afile = new ClustalFile();
500 else if (format.equalsIgnoreCase("BLC"))
502 afile = new BLCFile();
504 else if (format.equalsIgnoreCase("PIR"))
506 afile = new PIRFile();
508 else if (format.equalsIgnoreCase("PFAM"))
510 afile = new PfamFile();
512 else if (format.equalsIgnoreCase("STH"))
514 afile = new StockholmFile(alignment);
516 else if (format.equalsIgnoreCase("AMSA"))
518 afile = new AMSAFile(alignment);
520 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
522 afile = new PhylipFile();
524 // else if (format.equalsIgnoreCase(HtmlFile.FILE_DESC))
526 // afile = new HtmlFile();
528 else if (format.equalsIgnoreCase("RNAML"))
530 afile = new RnamlFile();
535 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
537 afile.setNewlineString(newline);
538 afile.addJVSuffix(jvsuffix);
540 afile.setSeqs(alignment.getSequencesArray());
542 String afileresp = afile.print();
543 if (afile.hasWarningMessage())
545 System.err.println("Warning raised when writing as " + format
546 + " : " + afile.getWarningMessage());
549 } catch (Exception e)
551 System.err.println("Failed to write alignment as a '" + format
559 public static String checkProtocol(String file)
561 String protocol = FILE;
562 String ft = file.toLowerCase().trim();
563 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
564 || ft.indexOf("file:") == 0)
571 public static void main(String[] args)
574 while (i < args.length)
576 File f = new File(args[i]);
581 System.out.println("Reading file: " + f);
582 AppletFormatAdapter afa = new AppletFormatAdapter();
583 Runtime r = Runtime.getRuntime();
585 long memf = -r.totalMemory() + r.freeMemory();
586 long t1 = -System.currentTimeMillis();
587 Alignment al = afa.readFile(args[i], FILE,
588 new IdentifyFile().Identify(args[i], FILE));
589 t1 += System.currentTimeMillis();
591 memf += r.totalMemory() - r.freeMemory();
594 System.out.println("Alignment contains " + al.getHeight()
595 + " sequences and " + al.getWidth() + " columns.");
598 System.out.println(new AppletFormatAdapter().formatSequences(
600 } catch (Exception e)
603 .println("Couln't format the alignment for output as a FASTA file.");
604 e.printStackTrace(System.err);
609 System.out.println("Couldn't read alignment");
611 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
613 .println("Difference between free memory now and before is "
614 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
615 } catch (Exception e)
617 System.err.println("Exception when dealing with " + i
618 + "'th argument: " + args[i] + "\n" + e);
623 System.err.println("Ignoring argument '" + args[i] + "' (" + i
624 + "'th)- not a readable file.");
631 * try to discover how to access the given file as a valid datasource that
632 * will be identified as the given type.
636 * @return protocol that yields the data parsable as the given type
638 public static String resolveProtocol(String file, String format)
640 return resolveProtocol(file, format, false);
643 public static String resolveProtocol(String file, String format,
646 // TODO: test thoroughly!
647 String protocol = null;
650 System.out.println("resolving datasource started with:\n>>file\n"
651 + file + ">>endfile");
654 // This might throw a security exception in certain browsers
655 // Netscape Communicator for instance.
659 InputStream is = System.getSecurityManager().getClass()
660 .getResourceAsStream("/" + file);
668 System.err.println("Resource '" + file + "' was "
669 + (rtn ? "" : "not") + " located by classloader.");
674 protocol = AppletFormatAdapter.CLASSLOADER;
677 } catch (Exception ex)
680 .println("Exception checking resources: " + file + " " + ex);
683 if (file.indexOf("://") > -1)
685 protocol = AppletFormatAdapter.URL;
689 // skipping codebase prepend check.
690 protocol = AppletFormatAdapter.FILE;
697 System.out.println("Trying to get contents of resource as "
700 fp = new FileParse(file, protocol);
709 System.out.println("Successful.");
712 } catch (Exception e)
716 System.err.println("Exception when accessing content: " + e);
724 System.out.println("Accessing as paste.");
726 protocol = AppletFormatAdapter.PASTE;
730 fp = new FileParse(file, protocol);
735 } catch (Exception e)
737 System.err.println("Failed to access content as paste!");
746 if (format == null || format.length() == 0)
754 String idformat = new jalview.io.IdentifyFile().Identify(file,
756 if (idformat == null)
760 System.out.println("Format not identified. Inaccessible file.");
766 System.out.println("Format identified as " + idformat
767 + "and expected as " + format);
769 if (idformat.equals(format))
773 System.out.println("Protocol identified as " + protocol);
782 .println("File deemed not accessible via " + protocol);
787 } catch (Exception e)
791 System.err.println("File deemed not accessible via " + protocol);