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
45 private AlignViewportI viewport;
47 public static String FILE = "File";
49 public static String URL = "URL";
51 public static String PASTE = "Paste";
53 public static String CLASSLOADER = "ClassLoader";
56 * add jalview-derived non-secondary structure annotation from PDB structure
58 boolean annotFromStructure = false;
61 * add secondary structure from PDB data with built-in algorithms
63 boolean localSecondaryStruct = false;
66 * process PDB data with web services
68 boolean serviceSecondaryStruct = false;
70 private AlignFile alignFile = null;
75 * character used to write newlines
77 protected String newline = System.getProperty("line.separator");
80 * List of valid format strings used in the isValidFormat method
82 public static final String[] READABLE_FORMATS = new String[]
83 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
84 "PDB", "JnetFile", "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.GFF3File,
88 * List of readable format file extensions by application in order
89 * corresponding to READABLE_FNAMES
91 public static final String[] READABLE_EXTENSIONS = new String[]
92 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
93 "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT, JSONFile.FILE_EXT,
95 "jar,jvp", HtmlFile.FILE_EXT };
98 * List of readable formats by application in order corresponding to
101 public static final String[] READABLE_FNAMES = new String[]
102 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm",
103 "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.GFF3File, "Jalview",
104 HtmlFile.FILE_DESC };
107 * List of valid format strings for use by callers of the formatSequences
110 public static final String[] WRITEABLE_FORMATS = new String[]
111 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
112 "STH", PhylipFile.FILE_DESC, JSONFile.FILE_DESC };
115 * List of extensions corresponding to file format types in WRITABLE_FNAMES
116 * that are writable by the application.
118 public static final String[] WRITABLE_EXTENSIONS = new String[]
119 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
120 "sto,stk", PhylipFile.FILE_EXT, JSONFile.FILE_EXT, "jvp" };
123 * List of writable formats by the application. Order must correspond with the
124 * WRITABLE_EXTENSIONS list of formats.
126 public static final String[] WRITABLE_FNAMES = new String[]
127 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
128 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, "Jalview" };
130 public static String INVALID_CHARACTERS = "Contains invalid characters";
132 // TODO: make these messages dynamic
133 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
134 + prettyPrint(READABLE_FORMATS);
136 public AppletFormatAdapter()
140 public AppletFormatAdapter(AlignViewportI viewport)
142 this.viewport = viewport;
148 * @return grammatically correct(ish) list consisting of els elements.
150 public static String prettyPrint(String[] els)
152 StringBuffer list = new StringBuffer();
153 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
158 list.append(" and " + els[els.length - 1] + ".");
159 return list.toString();
163 public void setNewlineString(String nl)
168 public String getNewlineString()
174 * check that this format is valid for reading
177 * a format string to be compared with READABLE_FORMATS
178 * @return true if format is readable
180 public static final boolean isValidFormat(String format)
182 return isValidFormat(format, false);
186 * validate format is valid for IO
189 * a format string to be compared with either READABLE_FORMATS or
192 * when true, format is checked for containment in WRITEABLE_FORMATS
193 * @return true if format is valid
195 public static final boolean isValidFormat(String format,
198 boolean valid = false;
199 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
201 for (String element : format_list)
203 if (element.equalsIgnoreCase(format))
213 * Constructs the correct filetype parser for a characterised datasource
220 * File format of data provided by datasource
222 * @return DOCUMENT ME!
224 public Alignment readFile(String inFile, String type, String format)
225 throws java.io.IOException
227 // TODO: generalise mapping between format string and io. class instances
228 // using Constructor.invoke reflection
229 this.inFile = inFile;
233 if (format.equals("FASTA"))
235 alignFile = new FastaFile(inFile, type);
237 else if (format.equals("MSF"))
239 alignFile = new MSFfile(inFile, type);
241 else if (format.equals("PileUp"))
243 alignFile = new PileUpfile(inFile, type);
245 else if (format.equals("CLUSTAL"))
247 alignFile = new ClustalFile(inFile, type);
249 else if (format.equals("BLC"))
251 alignFile = new BLCFile(inFile, type);
253 else if (format.equals("PIR"))
255 alignFile = new PIRFile(inFile, type);
257 else if (format.equals("PFAM"))
259 alignFile = new PfamFile(inFile, type);
261 else if (format.equals("JnetFile"))
263 alignFile = new JPredFile(inFile, type);
264 ((JPredFile) alignFile).removeNonSequences();
266 else if (format.equals("PDB"))
268 alignFile = new MCview.PDBfile(annotFromStructure,
269 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
270 // Uncomment to test Jmol data based PDB processing: JAL-1213
271 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
273 else if (format.equals("STH"))
275 alignFile = new StockholmFile(inFile, type);
277 else if (format.equals("SimpleBLAST"))
279 alignFile = new SimpleBlastFile(inFile, type);
281 else if (format.equals(PhylipFile.FILE_DESC))
283 alignFile = new PhylipFile(inFile, type);
285 else if (format.equals(JSONFile.FILE_DESC))
287 alignFile = new JSONFile(inFile, type);
289 else if (format.equals(HtmlFile.FILE_DESC))
291 alignFile = new HtmlFile(inFile, type);
293 else if (format.equals("RNAML"))
295 alignFile = new RnamlFile(inFile, type);
297 else if (format.equals(IdentifyFile.GFF3File))
299 alignFile = new Gff3File(inFile, type);
301 // Standard boilerplate for creating alignment from parser
302 alignFile.setViewport(viewport);
304 al = new Alignment(alignFile.getSeqsAsArray());
306 alignFile.addAnnotations(al);
308 alignFile.addGroups(al);
311 } catch (Exception e)
314 System.err.println("Failed to read alignment using the '" + format
315 + "' reader.\n" + e);
317 if (e.getMessage() != null
318 && e.getMessage().startsWith(INVALID_CHARACTERS))
320 throw new java.io.IOException(e.getMessage());
323 // Finally test if the user has pasted just the sequence, no id
324 if (type.equalsIgnoreCase("Paste"))
328 // Possible sequence is just residues with no label
329 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
330 Alignment al = new Alignment(alignFile.getSeqsAsArray());
332 alignFile.addSeqGroups(al);
333 alignFile.addAnnotations(al);
336 } catch (Exception ex)
338 if (ex.toString().startsWith(INVALID_CHARACTERS))
340 throw new java.io.IOException(e.getMessage());
343 ex.printStackTrace();
347 // If we get to this stage, the format was not supported
348 throw new java.io.IOException(SUPPORTED_FORMATS);
353 * Constructs the correct filetype parser for an already open datasource
356 * an existing datasource
358 * File format of data that will be provided by datasource
360 * @return DOCUMENT ME!
362 public AlignmentI readFromFile(FileParse source, String format)
363 throws java.io.IOException
365 // TODO: generalise mapping between format string and io. class instances
366 // using Constructor.invoke reflection
367 // This is exactly the same as the readFile method except we substitute
368 // 'inFile, type' with 'source'
369 this.inFile = source.getInFile();
370 String type = source.type;
374 if (format.equals("FASTA"))
376 alignFile = new FastaFile(source);
378 else if (format.equals("MSF"))
380 alignFile = new MSFfile(source);
382 else if (format.equals("PileUp"))
384 alignFile = new PileUpfile(source);
386 else if (format.equals("CLUSTAL"))
388 alignFile = new ClustalFile(source);
390 else if (format.equals("BLC"))
392 alignFile = new BLCFile(source);
394 else if (format.equals("PIR"))
396 alignFile = new PIRFile(source);
398 else if (format.equals("PFAM"))
400 alignFile = new PfamFile(source);
402 else if (format.equals("JnetFile"))
404 alignFile = new JPredFile(source);
405 ((JPredFile) alignFile).removeNonSequences();
407 else if (format.equals("PDB"))
409 alignFile = new MCview.PDBfile(annotFromStructure,
410 localSecondaryStruct, serviceSecondaryStruct, source);
412 else if (format.equals("STH"))
414 alignFile = new StockholmFile(source);
416 else if (format.equals("RNAML"))
418 alignFile = new RnamlFile(source);
420 else if (format.equals("SimpleBLAST"))
422 alignFile = new SimpleBlastFile(source);
424 else if (format.equals(PhylipFile.FILE_DESC))
426 alignFile = new PhylipFile(source);
428 else if (format.equals(IdentifyFile.GFF3File))
430 alignFile = new Gff3File(inFile, type);
432 else if (format.equals(JSONFile.FILE_DESC))
434 alignFile = new JSONFile(source);
435 al = new Alignment(alignFile.getSeqsAsArray());
436 alignFile.addAnnotations(al);
437 alignFile.addSeqGroups(al);
440 else if (format.equals(HtmlFile.FILE_DESC))
442 alignFile = new HtmlFile(source);
444 al = new Alignment(alignFile.getSeqsAsArray());
445 alignFile.addAnnotations(al);
448 } catch (Exception e)
451 System.err.println("Failed to read alignment using the '" + format
452 + "' reader.\n" + e);
454 if (e.getMessage() != null
455 && e.getMessage().startsWith(INVALID_CHARACTERS))
457 throw new java.io.IOException(e.getMessage());
460 // Finally test if the user has pasted just the sequence, no id
461 if (type.equalsIgnoreCase("Paste"))
465 // Possible sequence is just residues with no label
466 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
467 Alignment al = new Alignment(alignFile.getSeqsAsArray());
468 alignFile.addAnnotations(al);
469 alignFile.addSeqGroups(al);
472 } catch (Exception ex)
474 if (ex.toString().startsWith(INVALID_CHARACTERS))
476 throw new java.io.IOException(e.getMessage());
479 ex.printStackTrace();
483 // If we get to this stage, the format was not supported
484 throw new java.io.IOException(SUPPORTED_FORMATS);
490 * create an alignment flatfile from a Jalview alignment view
494 * @param selectedOnly
495 * @return flatfile in a string
497 public String formatSequences(String format, boolean jvsuffix,
498 AlignViewportI av, boolean selectedOnly)
501 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
502 AlignmentI aselview = selvew.getVisibleAlignment(av
504 List<AlignmentAnnotation> ala = (av
505 .getVisibleAlignmentAnnotation(selectedOnly));
508 for (AlignmentAnnotation aa : ala)
510 aselview.addAnnotation(aa);
514 return formatSequences(format, aselview, jvsuffix);
518 * Construct an output class for an alignment in a particular filetype TODO:
519 * allow caller to detect errors and warnings encountered when generating
523 * string name of alignment format
525 * the alignment to be written out
527 * passed to AlnFile class controls whether /START-END is added to
530 * @return alignment flat file contents
532 public String formatSequences(String format, AlignmentI alignment,
537 AlignFile afile = null;
538 if (format.equalsIgnoreCase("FASTA"))
540 afile = new FastaFile();
542 else if (format.equalsIgnoreCase("MSF"))
544 afile = new MSFfile();
546 else if (format.equalsIgnoreCase("PileUp"))
548 afile = new PileUpfile();
550 else if (format.equalsIgnoreCase("CLUSTAL"))
552 afile = new ClustalFile();
554 else if (format.equalsIgnoreCase("BLC"))
556 afile = new BLCFile();
558 else if (format.equalsIgnoreCase("PIR"))
560 afile = new PIRFile();
562 else if (format.equalsIgnoreCase("PFAM"))
564 afile = new PfamFile();
566 else if (format.equalsIgnoreCase("STH"))
568 afile = new StockholmFile(alignment);
570 else if (format.equalsIgnoreCase("AMSA"))
572 afile = new AMSAFile(alignment);
574 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
576 afile = new PhylipFile();
578 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
580 afile = new JSONFile();
581 afile.setViewport(viewport);
582 // Add groups to AlignFile
583 afile.seqGroups = alignment.getGroups();
585 // Add non auto calculated annotation to AlignFile
586 for (AlignmentAnnotation annot : alignment.getAlignmentAnnotation())
588 if (annot != null && !annot.autoCalculated)
590 if (annot.label.equals("PDB.CATempFactor"))
594 afile.annotations.add(annot);
598 else if (format.equalsIgnoreCase("RNAML"))
600 afile = new RnamlFile();
605 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
607 afile.setNewlineString(newline);
608 afile.addJVSuffix(jvsuffix);
610 afile.setSeqs(alignment.getSequencesArray());
613 String afileresp = afile.print();
614 if (afile.hasWarningMessage())
616 System.err.println("Warning raised when writing as " + format
617 + " : " + afile.getWarningMessage());
620 } catch (Exception e)
622 System.err.println("Failed to write alignment as a '" + format
630 public static String checkProtocol(String file)
632 String protocol = FILE;
633 String ft = file.toLowerCase().trim();
634 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
635 || ft.indexOf("file:") == 0)
642 public static void main(String[] args)
645 while (i < args.length)
647 File f = new File(args[i]);
652 System.out.println("Reading file: " + f);
653 AppletFormatAdapter afa = new AppletFormatAdapter();
654 Runtime r = Runtime.getRuntime();
656 long memf = -r.totalMemory() + r.freeMemory();
657 long t1 = -System.currentTimeMillis();
658 Alignment al = afa.readFile(args[i], FILE,
659 new IdentifyFile().Identify(args[i], FILE));
660 t1 += System.currentTimeMillis();
662 memf += r.totalMemory() - r.freeMemory();
665 System.out.println("Alignment contains " + al.getHeight()
666 + " sequences and " + al.getWidth() + " columns.");
669 System.out.println(new AppletFormatAdapter().formatSequences(
671 } catch (Exception e)
674 .println("Couln't format the alignment for output as a FASTA file.");
675 e.printStackTrace(System.err);
680 System.out.println("Couldn't read alignment");
682 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
684 .println("Difference between free memory now and before is "
685 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
686 } catch (Exception e)
688 System.err.println("Exception when dealing with " + i
689 + "'th argument: " + args[i] + "\n" + e);
694 System.err.println("Ignoring argument '" + args[i] + "' (" + i
695 + "'th)- not a readable file.");
702 * try to discover how to access the given file as a valid datasource that
703 * will be identified as the given type.
707 * @return protocol that yields the data parsable as the given type
709 public static String resolveProtocol(String file, String format)
711 return resolveProtocol(file, format, false);
714 public static String resolveProtocol(String file, String format,
717 // TODO: test thoroughly!
718 String protocol = null;
721 System.out.println("resolving datasource started with:\n>>file\n"
722 + file + ">>endfile");
725 // This might throw a security exception in certain browsers
726 // Netscape Communicator for instance.
730 InputStream is = System.getSecurityManager().getClass()
731 .getResourceAsStream("/" + file);
739 System.err.println("Resource '" + file + "' was "
740 + (rtn ? "" : "not") + " located by classloader.");
745 protocol = AppletFormatAdapter.CLASSLOADER;
748 } catch (Exception ex)
751 .println("Exception checking resources: " + file + " " + ex);
754 if (file.indexOf("://") > -1)
756 protocol = AppletFormatAdapter.URL;
760 // skipping codebase prepend check.
761 protocol = AppletFormatAdapter.FILE;
768 System.out.println("Trying to get contents of resource as "
771 fp = new FileParse(file, protocol);
780 System.out.println("Successful.");
783 } catch (Exception e)
787 System.err.println("Exception when accessing content: " + e);
795 System.out.println("Accessing as paste.");
797 protocol = AppletFormatAdapter.PASTE;
801 fp = new FileParse(file, protocol);
806 } catch (Exception e)
808 System.err.println("Failed to access content as paste!");
817 if (format == null || format.length() == 0)
825 String idformat = new jalview.io.IdentifyFile().Identify(file,
827 if (idformat == null)
831 System.out.println("Format not identified. Inaccessible file.");
837 System.out.println("Format identified as " + idformat
838 + "and expected as " + format);
840 if (idformat.equals(format))
844 System.out.println("Protocol identified as " + protocol);
853 .println("File deemed not accessible via " + protocol);
858 } catch (Exception e)
862 System.err.println("File deemed not accessible via " + protocol);
872 public AlignFile getAlignFile()
877 public void setAlignFile(AlignFile alignFile)
879 this.alignFile = alignFile;