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";
130 * add jalview-derived non-secondary structure annotation from PDB structure
132 boolean annotFromStructure = false;
135 * add secondary structure from PDB data with built-in algorithms
137 boolean localSecondaryStruct = false;
140 * process PDB data with web services
142 boolean serviceSecondaryStruct = false;
144 AlignFile afile = null;
149 * character used to write newlines
151 protected String newline = System.getProperty("line.separator");
153 public void setNewlineString(String nl)
158 public String getNewlineString()
164 * check that this format is valid for reading
167 * a format string to be compared with READABLE_FORMATS
168 * @return true if format is readable
170 public static final boolean isValidFormat(String format)
172 return isValidFormat(format, false);
176 * validate format is valid for IO
179 * a format string to be compared with either READABLE_FORMATS or
182 * when true, format is checked for containment in WRITEABLE_FORMATS
183 * @return true if format is valid
185 public static final boolean isValidFormat(String format,
188 boolean valid = false;
189 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
191 for (String element : format_list)
193 if (element.equalsIgnoreCase(format))
203 * Constructs the correct filetype parser for a characterised datasource
210 * File format of data provided by datasource
212 * @return DOCUMENT ME!
214 public Alignment readFile(String inFile, String type, String format)
215 throws java.io.IOException
217 // TODO: generalise mapping between format string and io. class instances
218 // using Constructor.invoke reflection
219 this.inFile = inFile;
222 if (format.equals("FASTA"))
224 afile = new FastaFile(inFile, type);
226 else if (format.equals("MSF"))
228 afile = new MSFfile(inFile, type);
230 else if (format.equals("PileUp"))
232 afile = new PileUpfile(inFile, type);
234 else if (format.equals("CLUSTAL"))
236 afile = new ClustalFile(inFile, type);
238 else if (format.equals("BLC"))
240 afile = new BLCFile(inFile, type);
242 else if (format.equals("PIR"))
244 afile = new PIRFile(inFile, type);
246 else if (format.equals("PFAM"))
248 afile = new PfamFile(inFile, type);
250 else if (format.equals("JnetFile"))
252 afile = new JPredFile(inFile, type);
253 ((JPredFile) afile).removeNonSequences();
255 else if (format.equals("PDB"))
257 afile = new MCview.PDBfile(annotFromStructure,
258 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
259 // Uncomment to test Jmol data based PDB processing: JAL-1213
260 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
262 else if (format.equals("STH"))
264 afile = new StockholmFile(inFile, type);
266 else if (format.equals("SimpleBLAST"))
268 afile = new SimpleBlastFile(inFile, type);
270 else if (format.equals(PhylipFile.FILE_DESC))
272 afile = new PhylipFile(inFile, type);
274 // else if (format.equals(HtmlFile.FILE_DESC))
276 // afile = new HtmlFile(inFile, type);
278 else if (format.equals("RNAML"))
280 afile = new RnamlFile(inFile, type);
283 Alignment al = new Alignment(afile.getSeqsAsArray());
285 afile.addAnnotations(al);
288 } catch (Exception e)
291 System.err.println("Failed to read alignment using the '" + format
292 + "' reader.\n" + e);
294 if (e.getMessage() != null
295 && e.getMessage().startsWith(INVALID_CHARACTERS))
297 throw new java.io.IOException(e.getMessage());
300 // Finally test if the user has pasted just the sequence, no id
301 if (type.equalsIgnoreCase("Paste"))
305 // Possible sequence is just residues with no label
306 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
307 Alignment al = new Alignment(afile.getSeqsAsArray());
308 afile.addAnnotations(al);
311 } catch (Exception ex)
313 if (ex.toString().startsWith(INVALID_CHARACTERS))
315 throw new java.io.IOException(e.getMessage());
318 ex.printStackTrace();
322 // If we get to this stage, the format was not supported
323 throw new java.io.IOException(SUPPORTED_FORMATS);
328 * Constructs the correct filetype parser for an already open datasource
331 * an existing datasource
333 * File format of data that will be provided by datasource
335 * @return DOCUMENT ME!
337 public AlignmentI readFromFile(FileParse source, String format)
338 throws java.io.IOException
340 // TODO: generalise mapping between format string and io. class instances
341 // using Constructor.invoke reflection
342 // This is exactly the same as the readFile method except we substitute
343 // 'inFile, type' with 'source'
344 this.inFile = source.getInFile();
345 String type = source.type;
348 if (format.equals("FASTA"))
350 afile = new FastaFile(source);
352 else if (format.equals("MSF"))
354 afile = new MSFfile(source);
356 else if (format.equals("PileUp"))
358 afile = new PileUpfile(source);
360 else if (format.equals("CLUSTAL"))
362 afile = new ClustalFile(source);
364 else if (format.equals("BLC"))
366 afile = new BLCFile(source);
368 else if (format.equals("PIR"))
370 afile = new PIRFile(source);
372 else if (format.equals("PFAM"))
374 afile = new PfamFile(source);
376 else if (format.equals("JnetFile"))
378 afile = new JPredFile(source);
379 ((JPredFile) afile).removeNonSequences();
381 else if (format.equals("PDB"))
383 afile = new MCview.PDBfile(annotFromStructure,
384 localSecondaryStruct, serviceSecondaryStruct, source);
386 else if (format.equals("STH"))
388 afile = new StockholmFile(source);
390 else if (format.equals("RNAML"))
392 afile = new RnamlFile(source);
394 else if (format.equals("SimpleBLAST"))
396 afile = new SimpleBlastFile(source);
398 else if (format.equals(PhylipFile.FILE_DESC))
400 afile = new PhylipFile(source);
402 // else if (format.equals(HtmlFile.FILE_DESC))
404 // afile = new HtmlFile(source);
406 Alignment al = new Alignment(afile.getSeqsAsArray());
408 afile.addAnnotations(al);
411 } catch (Exception e)
414 System.err.println("Failed to read alignment using the '" + format
415 + "' reader.\n" + e);
417 if (e.getMessage() != null
418 && e.getMessage().startsWith(INVALID_CHARACTERS))
420 throw new java.io.IOException(e.getMessage());
423 // Finally test if the user has pasted just the sequence, no id
424 if (type.equalsIgnoreCase("Paste"))
428 // Possible sequence is just residues with no label
429 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
430 Alignment al = new Alignment(afile.getSeqsAsArray());
431 afile.addAnnotations(al);
434 } catch (Exception ex)
436 if (ex.toString().startsWith(INVALID_CHARACTERS))
438 throw new java.io.IOException(e.getMessage());
441 ex.printStackTrace();
445 // If we get to this stage, the format was not supported
446 throw new java.io.IOException(SUPPORTED_FORMATS);
452 * create an alignment flatfile from a Jalview alignment view
456 * @param selectedOnly
457 * @return flatfile in a string
459 public String formatSequences(String format, boolean jvsuffix,
460 AlignViewportI av, boolean selectedOnly)
463 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
464 AlignmentI aselview = selvew.getVisibleAlignment(av
466 List<AlignmentAnnotation> ala = (av
467 .getVisibleAlignmentAnnotation(selectedOnly));
470 for (AlignmentAnnotation aa : ala)
472 aselview.addAnnotation(aa);
476 return formatSequences(format, aselview, jvsuffix);
480 * Construct an output class for an alignment in a particular filetype TODO:
481 * allow caller to detect errors and warnings encountered when generating
485 * string name of alignment format
487 * the alignment to be written out
489 * passed to AlnFile class controls whether /START-END is added to
492 * @return alignment flat file contents
494 public String formatSequences(String format, AlignmentI alignment,
499 AlignFile afile = null;
501 if (format.equalsIgnoreCase("FASTA"))
503 afile = new FastaFile();
505 else if (format.equalsIgnoreCase("MSF"))
507 afile = new MSFfile();
509 else if (format.equalsIgnoreCase("PileUp"))
511 afile = new PileUpfile();
513 else if (format.equalsIgnoreCase("CLUSTAL"))
515 afile = new ClustalFile();
517 else if (format.equalsIgnoreCase("BLC"))
519 afile = new BLCFile();
521 else if (format.equalsIgnoreCase("PIR"))
523 afile = new PIRFile();
525 else if (format.equalsIgnoreCase("PFAM"))
527 afile = new PfamFile();
529 else if (format.equalsIgnoreCase("STH"))
531 afile = new StockholmFile(alignment);
533 else if (format.equalsIgnoreCase("AMSA"))
535 afile = new AMSAFile(alignment);
537 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
539 afile = new PhylipFile();
541 // else if (format.equalsIgnoreCase(HtmlFile.FILE_DESC))
543 // afile = new HtmlFile();
545 else if (format.equalsIgnoreCase("RNAML"))
547 afile = new RnamlFile();
552 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
554 afile.setNewlineString(newline);
555 afile.addJVSuffix(jvsuffix);
557 afile.setSeqs(alignment.getSequencesArray());
559 String afileresp = afile.print();
560 if (afile.hasWarningMessage())
562 System.err.println("Warning raised when writing as " + format
563 + " : " + afile.getWarningMessage());
566 } catch (Exception e)
568 System.err.println("Failed to write alignment as a '" + format
576 public static String checkProtocol(String file)
578 String protocol = FILE;
579 String ft = file.toLowerCase().trim();
580 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
581 || ft.indexOf("file:") == 0)
588 public static void main(String[] args)
591 while (i < args.length)
593 File f = new File(args[i]);
598 System.out.println("Reading file: " + f);
599 AppletFormatAdapter afa = new AppletFormatAdapter();
600 Runtime r = Runtime.getRuntime();
602 long memf = -r.totalMemory() + r.freeMemory();
603 long t1 = -System.currentTimeMillis();
604 Alignment al = afa.readFile(args[i], FILE,
605 new IdentifyFile().Identify(args[i], FILE));
606 t1 += System.currentTimeMillis();
608 memf += r.totalMemory() - r.freeMemory();
611 System.out.println("Alignment contains " + al.getHeight()
612 + " sequences and " + al.getWidth() + " columns.");
615 System.out.println(new AppletFormatAdapter().formatSequences(
617 } catch (Exception e)
620 .println("Couln't format the alignment for output as a FASTA file.");
621 e.printStackTrace(System.err);
626 System.out.println("Couldn't read alignment");
628 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
630 .println("Difference between free memory now and before is "
631 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
632 } catch (Exception e)
634 System.err.println("Exception when dealing with " + i
635 + "'th argument: " + args[i] + "\n" + e);
640 System.err.println("Ignoring argument '" + args[i] + "' (" + i
641 + "'th)- not a readable file.");
648 * try to discover how to access the given file as a valid datasource that
649 * will be identified as the given type.
653 * @return protocol that yields the data parsable as the given type
655 public static String resolveProtocol(String file, String format)
657 return resolveProtocol(file, format, false);
660 public static String resolveProtocol(String file, String format,
663 // TODO: test thoroughly!
664 String protocol = null;
667 System.out.println("resolving datasource started with:\n>>file\n"
668 + file + ">>endfile");
671 // This might throw a security exception in certain browsers
672 // Netscape Communicator for instance.
676 InputStream is = System.getSecurityManager().getClass()
677 .getResourceAsStream("/" + file);
685 System.err.println("Resource '" + file + "' was "
686 + (rtn ? "" : "not") + " located by classloader.");
691 protocol = AppletFormatAdapter.CLASSLOADER;
694 } catch (Exception ex)
697 .println("Exception checking resources: " + file + " " + ex);
700 if (file.indexOf("://") > -1)
702 protocol = AppletFormatAdapter.URL;
706 // skipping codebase prepend check.
707 protocol = AppletFormatAdapter.FILE;
714 System.out.println("Trying to get contents of resource as "
717 fp = new FileParse(file, protocol);
726 System.out.println("Successful.");
729 } catch (Exception e)
733 System.err.println("Exception when accessing content: " + e);
741 System.out.println("Accessing as paste.");
743 protocol = AppletFormatAdapter.PASTE;
747 fp = new FileParse(file, protocol);
752 } catch (Exception e)
754 System.err.println("Failed to access content as paste!");
763 if (format == null || format.length() == 0)
771 String idformat = new jalview.io.IdentifyFile().Identify(file,
773 if (idformat == null)
777 System.out.println("Format not identified. Inaccessible file.");
783 System.out.println("Format identified as " + idformat
784 + "and expected as " + format);
786 if (idformat.equals(format))
790 System.out.println("Protocol identified as " + protocol);
799 .println("File deemed not accessible via " + protocol);
804 } catch (Exception e)
808 System.err.println("File deemed not accessible via " + protocol);