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.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" };
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", "html" };
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", "HTML" };
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 "sto,stk", PhylipFile.FILE_EXT, "jvp" };
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", "STH",
90 PhylipFile.FILE_DESC, "Jalview" };
92 public static String INVALID_CHARACTERS = "Contains invalid characters";
94 // TODO: make these messages dynamic
95 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
96 + prettyPrint(READABLE_FORMATS);
101 * @return grammatically correct(ish) list consisting of els elements.
103 public static String prettyPrint(String[] els)
105 StringBuffer list = new StringBuffer();
106 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
111 list.append(" and " + els[els.length - 1] + ".");
112 return list.toString();
115 public static String FILE = "File";
117 public static String URL = "URL";
119 public static String PASTE = "Paste";
121 public static String CLASSLOADER = "ClassLoader";
124 * add jalview-derived non-secondary structure annotation from PDB structure
126 boolean annotFromStructure = false;
129 * add secondary structure from PDB data with built-in algorithms
131 boolean localSecondaryStruct = false;
134 * process PDB data with web services
136 boolean serviceSecondaryStruct = false;
138 AlignFile afile = null;
143 * character used to write newlines
145 protected String newline = System.getProperty("line.separator");
147 public void setNewlineString(String nl)
152 public String getNewlineString()
158 * check that this format is valid for reading
161 * a format string to be compared with READABLE_FORMATS
162 * @return true if format is readable
164 public static final boolean isValidFormat(String format)
166 return isValidFormat(format, false);
170 * validate format is valid for IO
173 * a format string to be compared with either READABLE_FORMATS or
176 * when true, format is checked for containment in WRITEABLE_FORMATS
177 * @return true if format is valid
179 public static final boolean isValidFormat(String format,
182 boolean valid = false;
183 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
185 for (String element : format_list)
187 if (element.equalsIgnoreCase(format))
197 * Constructs the correct filetype parser for a characterised datasource
204 * File format of data provided by datasource
206 * @return DOCUMENT ME!
208 public Alignment readFile(String inFile, String type, String format)
209 throws java.io.IOException
211 // TODO: generalise mapping between format string and io. class instances
212 // using Constructor.invoke reflection
213 this.inFile = inFile;
216 if (format.equals("FASTA"))
218 afile = new FastaFile(inFile, type);
220 else if (format.equals("MSF"))
222 afile = new MSFfile(inFile, type);
224 else if (format.equals("PileUp"))
226 afile = new PileUpfile(inFile, type);
228 else if (format.equals("CLUSTAL"))
230 afile = new ClustalFile(inFile, type);
232 else if (format.equals("BLC"))
234 afile = new BLCFile(inFile, type);
236 else if (format.equals("PIR"))
238 afile = new PIRFile(inFile, type);
240 else if (format.equals("PFAM"))
242 afile = new PfamFile(inFile, type);
244 else if (format.equals("JnetFile"))
246 afile = new JPredFile(inFile, type);
247 ((JPredFile) afile).removeNonSequences();
249 else if (format.equals("PDB"))
251 afile = new MCview.PDBfile(annotFromStructure,
252 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
253 // Uncomment to test Jmol data based PDB processing: JAL-1213
254 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
256 else if (format.equals("STH"))
258 afile = new StockholmFile(inFile, type);
260 else if (format.equals("SimpleBLAST"))
262 afile = new SimpleBlastFile(inFile, type);
264 else if (format.equals(PhylipFile.FILE_DESC))
266 afile = new PhylipFile(inFile, type);
268 // else if (format.equals(HtmlFile.FILE_DESC))
270 // afile = new HtmlFile(inFile, type);
272 else if (format.equals("RNAML"))
274 afile = new RnamlFile(inFile, type);
277 Alignment al = new Alignment(afile.getSeqsAsArray());
279 afile.addAnnotations(al);
282 } catch (Exception e)
285 System.err.println("Failed to read alignment using the '" + format
286 + "' reader.\n" + e);
288 if (e.getMessage() != null
289 && e.getMessage().startsWith(INVALID_CHARACTERS))
291 throw new java.io.IOException(e.getMessage());
294 // Finally test if the user has pasted just the sequence, no id
295 if (type.equalsIgnoreCase("Paste"))
299 // Possible sequence is just residues with no label
300 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
301 Alignment al = new Alignment(afile.getSeqsAsArray());
302 afile.addAnnotations(al);
305 } catch (Exception ex)
307 if (ex.toString().startsWith(INVALID_CHARACTERS))
309 throw new java.io.IOException(e.getMessage());
312 ex.printStackTrace();
316 // If we get to this stage, the format was not supported
317 throw new java.io.IOException(SUPPORTED_FORMATS);
322 * Constructs the correct filetype parser for an already open datasource
325 * an existing datasource
327 * File format of data that will be provided by datasource
329 * @return DOCUMENT ME!
331 public AlignmentI readFromFile(FileParse source, String format)
332 throws java.io.IOException
334 // TODO: generalise mapping between format string and io. class instances
335 // using Constructor.invoke reflection
336 // This is exactly the same as the readFile method except we substitute
337 // 'inFile, type' with 'source'
338 this.inFile = source.getInFile();
339 String type = source.type;
342 if (format.equals("FASTA"))
344 afile = new FastaFile(source);
346 else if (format.equals("MSF"))
348 afile = new MSFfile(source);
350 else if (format.equals("PileUp"))
352 afile = new PileUpfile(source);
354 else if (format.equals("CLUSTAL"))
356 afile = new ClustalFile(source);
358 else if (format.equals("BLC"))
360 afile = new BLCFile(source);
362 else if (format.equals("PIR"))
364 afile = new PIRFile(source);
366 else if (format.equals("PFAM"))
368 afile = new PfamFile(source);
370 else if (format.equals("JnetFile"))
372 afile = new JPredFile(source);
373 ((JPredFile) afile).removeNonSequences();
375 else if (format.equals("PDB"))
377 afile = new MCview.PDBfile(annotFromStructure,
378 localSecondaryStruct, serviceSecondaryStruct, source);
380 else if (format.equals("STH"))
382 afile = new StockholmFile(source);
384 else if (format.equals("RNAML"))
386 afile = new RnamlFile(source);
388 else if (format.equals("SimpleBLAST"))
390 afile = new SimpleBlastFile(source);
392 else if (format.equals(PhylipFile.FILE_DESC))
394 afile = new PhylipFile(source);
396 // else if (format.equals(HtmlFile.FILE_DESC))
398 // afile = new HtmlFile(source);
400 Alignment al = new Alignment(afile.getSeqsAsArray());
402 afile.addAnnotations(al);
405 } catch (Exception e)
408 System.err.println("Failed to read alignment using the '" + format
409 + "' reader.\n" + e);
411 if (e.getMessage() != null
412 && e.getMessage().startsWith(INVALID_CHARACTERS))
414 throw new java.io.IOException(e.getMessage());
417 // Finally test if the user has pasted just the sequence, no id
418 if (type.equalsIgnoreCase("Paste"))
422 // Possible sequence is just residues with no label
423 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
424 Alignment al = new Alignment(afile.getSeqsAsArray());
425 afile.addAnnotations(al);
428 } catch (Exception ex)
430 if (ex.toString().startsWith(INVALID_CHARACTERS))
432 throw new java.io.IOException(e.getMessage());
435 ex.printStackTrace();
439 // If we get to this stage, the format was not supported
440 throw new java.io.IOException(SUPPORTED_FORMATS);
446 * create an alignment flatfile from a Jalview alignment view
450 * @param selectedOnly
451 * @return flatfile in a string
453 public String formatSequences(String format, boolean jvsuffix,
454 AlignViewportI av, boolean selectedOnly)
457 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
458 AlignmentI aselview = selvew.getVisibleAlignment(av
460 List<AlignmentAnnotation> ala = (av
461 .getVisibleAlignmentAnnotation(selectedOnly));
464 for (AlignmentAnnotation aa : ala)
466 aselview.addAnnotation(aa);
470 return formatSequences(format, aselview, jvsuffix);
474 * Construct an output class for an alignment in a particular filetype TODO:
475 * allow caller to detect errors and warnings encountered when generating
479 * string name of alignment format
481 * the alignment to be written out
483 * passed to AlnFile class controls whether /START-END is added to
486 * @return alignment flat file contents
488 public String formatSequences(String format, AlignmentI alignment,
493 AlignFile afile = null;
495 if (format.equalsIgnoreCase("FASTA"))
497 afile = new FastaFile();
499 else if (format.equalsIgnoreCase("MSF"))
501 afile = new MSFfile();
503 else if (format.equalsIgnoreCase("PileUp"))
505 afile = new PileUpfile();
507 else if (format.equalsIgnoreCase("CLUSTAL"))
509 afile = new ClustalFile();
511 else if (format.equalsIgnoreCase("BLC"))
513 afile = new BLCFile();
515 else if (format.equalsIgnoreCase("PIR"))
517 afile = new PIRFile();
519 else if (format.equalsIgnoreCase("PFAM"))
521 afile = new PfamFile();
523 else if (format.equalsIgnoreCase("STH"))
525 afile = new StockholmFile(alignment);
527 else if (format.equalsIgnoreCase("AMSA"))
529 afile = new AMSAFile(alignment);
531 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
533 afile = new PhylipFile();
535 // else if (format.equalsIgnoreCase(HtmlFile.FILE_DESC))
537 // afile = new HtmlFile();
539 else if (format.equalsIgnoreCase("RNAML"))
541 afile = new RnamlFile();
546 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
548 afile.setNewlineString(newline);
549 afile.addJVSuffix(jvsuffix);
551 afile.setSeqs(alignment.getSequencesArray());
553 String afileresp = afile.print();
554 if (afile.hasWarningMessage())
556 System.err.println("Warning raised when writing as " + format
557 + " : " + afile.getWarningMessage());
560 } catch (Exception e)
562 System.err.println("Failed to write alignment as a '" + format
570 public static String checkProtocol(String file)
572 String protocol = FILE;
573 String ft = file.toLowerCase().trim();
574 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
575 || ft.indexOf("file:") == 0)
582 public static void main(String[] args)
585 while (i < args.length)
587 File f = new File(args[i]);
592 System.out.println("Reading file: " + f);
593 AppletFormatAdapter afa = new AppletFormatAdapter();
594 Runtime r = Runtime.getRuntime();
596 long memf = -r.totalMemory() + r.freeMemory();
597 long t1 = -System.currentTimeMillis();
598 Alignment al = afa.readFile(args[i], FILE,
599 new IdentifyFile().Identify(args[i], FILE));
600 t1 += System.currentTimeMillis();
602 memf += r.totalMemory() - r.freeMemory();
605 System.out.println("Alignment contains " + al.getHeight()
606 + " sequences and " + al.getWidth() + " columns.");
609 System.out.println(new AppletFormatAdapter().formatSequences(
611 } catch (Exception e)
614 .println("Couln't format the alignment for output as a FASTA file.");
615 e.printStackTrace(System.err);
620 System.out.println("Couldn't read alignment");
622 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
624 .println("Difference between free memory now and before is "
625 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
626 } catch (Exception e)
628 System.err.println("Exception when dealing with " + i
629 + "'th argument: " + args[i] + "\n" + e);
634 System.err.println("Ignoring argument '" + args[i] + "' (" + i
635 + "'th)- not a readable file.");
642 * try to discover how to access the given file as a valid datasource that
643 * will be identified as the given type.
647 * @return protocol that yields the data parsable as the given type
649 public static String resolveProtocol(String file, String format)
651 return resolveProtocol(file, format, false);
654 public static String resolveProtocol(String file, String format,
657 // TODO: test thoroughly!
658 String protocol = null;
661 System.out.println("resolving datasource started with:\n>>file\n"
662 + file + ">>endfile");
665 // This might throw a security exception in certain browsers
666 // Netscape Communicator for instance.
670 InputStream is = System.getSecurityManager().getClass()
671 .getResourceAsStream("/" + file);
679 System.err.println("Resource '" + file + "' was "
680 + (rtn ? "" : "not") + " located by classloader.");
685 protocol = AppletFormatAdapter.CLASSLOADER;
688 } catch (Exception ex)
691 .println("Exception checking resources: " + file + " " + ex);
694 if (file.indexOf("://") > -1)
696 protocol = AppletFormatAdapter.URL;
700 // skipping codebase prepend check.
701 protocol = AppletFormatAdapter.FILE;
708 System.out.println("Trying to get contents of resource as "
711 fp = new FileParse(file, protocol);
720 System.out.println("Successful.");
723 } catch (Exception e)
727 System.err.println("Exception when accessing content: " + e);
735 System.out.println("Accessing as paste.");
737 protocol = AppletFormatAdapter.PASTE;
741 fp = new FileParse(file, protocol);
746 } catch (Exception e)
748 System.err.println("Failed to access content as paste!");
757 if (format == null || format.length() == 0)
765 String idformat = new jalview.io.IdentifyFile().Identify(file,
767 if (idformat == null)
771 System.out.println("Format not identified. Inaccessible file.");
777 System.out.println("Format identified as " + idformat
778 + "and expected as " + format);
780 if (idformat.equals(format))
784 System.out.println("Protocol identified as " + protocol);
793 .println("File deemed not accessible via " + protocol);
798 } catch (Exception e)
802 System.err.println("File deemed not accessible via " + protocol);