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.AlignExportSettingI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.AlignmentView;
29 import jalview.util.MessageManager;
32 import java.io.InputStream;
33 import java.util.List;
35 import javajs.J2SIgnoreImport;
37 import jalview.jsdev.Constants;
38 import jalview.jsdev.GenericFileAdapter;
41 * A low level class for alignment and feature IO with alignment formatting
42 * methods used by both applet and application for generating flat alignment
43 * files. It also holds the lists of magic format names that the applet and
44 * application will allow the user to read or write files with.
49 @J2SIgnoreImport({java.io.File.class})
50 public class AppletFormatAdapter
52 private AlignmentViewPanel viewpanel;
54 public static String FILE = "File";
56 public static String URL = "URL";
58 public static String PASTE = "Paste";
60 public static String CLASSLOADER = "ClassLoader";
63 * add jalview-derived non-secondary structure annotation from PDB structure
65 boolean annotFromStructure = false;
68 * add secondary structure from PDB data with built-in algorithms
70 boolean localSecondaryStruct = false;
73 * process PDB data with web services
75 boolean serviceSecondaryStruct = false;
77 private AlignFile alignFile = null;
82 * character used to write newlines
84 protected String newline = System.getProperty("line.separator");
86 private AlignExportSettingI exportSettings;
89 * List of valid format strings used in the isValidFormat method
91 public static final String[] READABLE_FORMATS = new String[]
92 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
93 "PDB", "JnetFile", "RNAML", Constants.Phylip_FILE_DESC, Constants.JSON_FILE_DESC, IdentifyFile.GFF3File,
97 * List of readable format file extensions by application in order
98 * corresponding to READABLE_FNAMES
100 public static final String[] READABLE_EXTENSIONS = new String[]
101 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
102 "sto,stk", "xml,rnaml", Constants.Phylip_FILE_EXT, Constants.JSON_FILE_EXT,
104 "jar,jvp", Constants.Html_FILE_EXT };
107 * List of readable formats by application in order corresponding to
108 * READABLE_EXTENSIONS
110 public static final String[] READABLE_FNAMES = new String[]
111 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm",
112 "RNAML", Constants.Phylip_FILE_DESC, Constants.JSON_FILE_DESC, IdentifyFile.GFF3File, "Jalview",
113 Constants.Html_FILE_DESC };
116 * List of valid format strings for use by callers of the formatSequences
119 public static final String[] WRITEABLE_FORMATS = new String[]
120 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
121 "STH", Constants.Phylip_FILE_DESC, Constants.JSON_FILE_DESC };
124 * List of extensions corresponding to file format types in WRITABLE_FNAMES
125 * that are writable by the application.
127 public static final String[] WRITABLE_EXTENSIONS = new String[]
128 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
129 "sto,stk", Constants.Phylip_FILE_EXT, Constants.JSON_FILE_EXT, "jvp" };
132 * List of writable formats by the application. Order must correspond with the
133 * WRITABLE_EXTENSIONS list of formats.
135 public static final String[] WRITABLE_FNAMES = new String[]
136 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
137 Constants.Phylip_FILE_DESC, Constants.JSON_FILE_DESC, "Jalview" };
139 public static String INVALID_CHARACTERS = "Contains invalid characters";
141 // TODO: make these messages dynamic
142 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
143 + prettyPrint(READABLE_FORMATS);
145 public AppletFormatAdapter()
149 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
151 this.viewpanel = viewpanel;
154 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
155 AlignExportSettingI settings)
157 viewpanel = alignPanel;
158 exportSettings = settings;
164 * @return grammatically correct(ish) list consisting of els elements.
166 public static String prettyPrint(String[] els)
168 StringBuffer list = new StringBuffer();
169 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
174 list.append(" and " + els[els.length - 1] + ".");
175 return list.toString();
179 public void setNewlineString(String nl)
184 public String getNewlineString()
190 * check that this format is valid for reading
193 * a format string to be compared with READABLE_FORMATS
194 * @return true if format is readable
196 public static final boolean isValidFormat(String format)
198 return isValidFormat(format, false);
202 * validate format is valid for IO
205 * a format string to be compared with either READABLE_FORMATS or
208 * when true, format is checked for containment in WRITEABLE_FORMATS
209 * @return true if format is valid
211 public static final boolean isValidFormat(String format,
214 boolean valid = false;
215 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
217 for (String element : format_list)
219 if (element.equalsIgnoreCase(format))
229 * Constructs the correct filetype parser for a characterised datasource
236 * File format of data provided by datasource
238 * @return DOCUMENT ME!
240 public AlignmentI readFile(String inFile, String type, String format)
241 throws java.io.IOException
243 // TODO: generalise mapping between format string and io. class instances
244 // using Constructor.invoke reflection
245 this.inFile = inFile;
248 if (format.equals("FASTA"))
250 alignFile = GenericFileAdapter.getFile("FastaFile", inFile, type);
252 else if (format.equals("MSF"))
254 alignFile = GenericFileAdapter.getFile("MSFfile", inFile, type);
256 else if (format.equals("PileUp"))
258 alignFile = GenericFileAdapter.getFile("PileUpfile", inFile, type);
260 else if (format.equals("CLUSTAL"))
262 alignFile = GenericFileAdapter.getFile("ClustalFile", inFile, type);
264 else if (format.equals("BLC"))
266 alignFile = GenericFileAdapter.getFile("BLCFile", inFile, type);
268 else if (format.equals("PIR"))
270 alignFile = GenericFileAdapter.getFile("PIRFile", inFile, type);
272 else if (format.equals("PFAM"))
274 alignFile = GenericFileAdapter.getFile("PfamFile", inFile, type);
276 else if (format.equals("JnetFile"))
278 alignFile = GenericFileAdapter.getFile("JPredFile", inFile, type);
279 ((JPredFile) alignFile).removeNonSequences();
281 else if (format.equals("PDB"))
283 alignFile = new MCview.PDBfile(annotFromStructure,
284 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
285 // Uncomment to test Jmol data based PDB processing: JAL-1213
286 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
288 else if (format.equals("STH"))
290 alignFile = GenericFileAdapter.getFile("StockholmFile", inFile, type);
292 else if (format.equals("SimpleBLAST"))
294 alignFile = GenericFileAdapter.getFile("SimpleBlastFile", inFile, type);
296 else if (format.equals(PhylipFile.FILE_DESC))
298 alignFile = GenericFileAdapter.getFile("PhylipFile", inFile, type);
300 else if (format.equals(Constants.JSON_FILE_DESC))
302 alignFile = GenericFileAdapter.getFile("JSONFile", inFile, type);
304 else if (format.equals(Constants.Html_FILE_DESC))
306 alignFile = GenericFileAdapter.getFile("HtmlFile", inFile, type);
308 else if (format.equals("RNAML"))
310 alignFile = GenericFileAdapter.getFile("RnamlFile", inFile, type);
312 else if (format.equals(IdentifyFile.GFF3File))
314 alignFile = GenericFileAdapter.getFile("Gff3File", inFile, type);
316 return buildAlignmentFrom(alignFile);
317 } catch (Exception e)
320 System.err.println("Failed to read alignment using the '" + format
321 + "' reader.\n" + e);
323 if (e.getMessage() != null
324 && e.getMessage().startsWith(INVALID_CHARACTERS))
326 throw new java.io.IOException(e.getMessage());
329 // Finally test if the user has pasted just the sequence, no id
330 if (type.equalsIgnoreCase("Paste"))
334 // Possible sequence is just residues with no label
335 alignFile = GenericFileAdapter.getFile("FastaFile", ">UNKNOWN\n" + inFile, "Paste");
336 return buildAlignmentFrom(alignFile);
338 } catch (Exception ex)
340 if (ex.toString().startsWith(INVALID_CHARACTERS))
342 throw new java.io.IOException(e.getMessage());
345 ex.printStackTrace();
349 // If we get to this stage, the format was not supported
350 throw new java.io.IOException(SUPPORTED_FORMATS);
355 * Constructs the correct filetype parser for an already open datasource
358 * an existing datasource
360 * File format of data that will be provided by datasource
362 * @return DOCUMENT ME!
364 public AlignmentI readFromFile(FileParse source, String format)
365 throws java.io.IOException
367 // TODO: generalise mapping between format string and io. class instances
368 // using Constructor.invoke reflection
369 // This is exactly the same as the readFile method except we substitute
370 // 'inFile, type' with 'source'
371 this.inFile = source.getInFile();
372 String type = source.type;
375 if (format.equals("FASTA"))
377 alignFile = GenericFileAdapter.getFile("FastaFile", source);
379 else if (format.equals("MSF"))
381 alignFile = GenericFileAdapter.getFile("MSFfile", source);
383 else if (format.equals("PileUp"))
385 alignFile = GenericFileAdapter.getFile("PileUpfile", source);
387 else if (format.equals("CLUSTAL"))
389 alignFile = GenericFileAdapter.getFile("ClustalFile", source);
391 else if (format.equals("BLC"))
393 alignFile = GenericFileAdapter.getFile("BLCFile", source);
395 else if (format.equals("PIR"))
397 alignFile = GenericFileAdapter.getFile("PIRFile", source);
399 else if (format.equals("PFAM"))
401 alignFile = GenericFileAdapter.getFile("PfamFile", source);
403 else if (format.equals("JnetFile"))
405 alignFile = GenericFileAdapter.getFile("JPredFile", source);
406 ((JPredFile) alignFile).removeNonSequences();
408 else if (format.equals("PDB"))
410 alignFile = new MCview.PDBfile(annotFromStructure,
411 localSecondaryStruct, serviceSecondaryStruct, source);
413 else if (format.equals("STH"))
415 alignFile = GenericFileAdapter.getFile("StockholmFile", source);
417 else if (format.equals("RNAML"))
419 alignFile = GenericFileAdapter.getFile("RnamlFile", source);
421 else if (format.equals("SimpleBLAST"))
423 alignFile = GenericFileAdapter.getFile("SimpleBlastFile", source);
425 else if (format.equals(Constants.Phylip_FILE_DESC))
427 alignFile = GenericFileAdapter.getFile("PhylipFile", source);
429 else if (format.equals(IdentifyFile.GFF3File))
431 alignFile = GenericFileAdapter.getFile("Gff3File", inFile, type);
433 else if (format.equals(Constants.JSON_FILE_DESC))
435 alignFile = GenericFileAdapter.getFile("JSONFile", source);
437 else if (format.equals(Constants.Html_FILE_DESC))
439 alignFile = GenericFileAdapter.getFile("HtmlFile", source);
442 return buildAlignmentFrom(alignFile);
444 } catch (Exception e)
447 System.err.println("Failed to read alignment using the '" + format
448 + "' reader.\n" + e);
450 if (e.getMessage() != null
451 && e.getMessage().startsWith(INVALID_CHARACTERS))
453 throw new java.io.IOException(e.getMessage());
456 // Finally test if the user has pasted just the sequence, no id
457 if (type.equalsIgnoreCase("Paste"))
461 // Possible sequence is just residues with no label
462 alignFile = GenericFileAdapter.getFile("FastaFile", ">UNKNOWN\n" + inFile, "Paste");
463 return buildAlignmentFrom(alignFile);
465 } catch (Exception ex)
467 if (ex.toString().startsWith(INVALID_CHARACTERS))
469 throw new java.io.IOException(e.getMessage());
472 ex.printStackTrace();
476 // If we get to this stage, the format was not supported
477 throw new java.io.IOException(SUPPORTED_FORMATS);
483 * boilerplate method to handle data from an AlignFile and construct a new
484 * alignment or import to an existing alignment
487 * @return AlignmentI instance ready to pass to a UI constructor
489 private AlignmentI buildAlignmentFrom(AlignFile alignFile2)
491 // Standard boilerplate for creating alignment from parser
492 // alignFile.configureForView(viewpanel);
494 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
496 alignFile.addAnnotations(al);
498 alignFile.addGroups(al);
504 * create an alignment flatfile from a Jalview alignment view
508 * @param selectedOnly
509 * @return flatfile in a string
511 public String formatSequences(String format, boolean jvsuffix,
512 AlignmentViewPanel ap, boolean selectedOnly)
515 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
516 selectedOnly, false);
517 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
519 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
520 .getVisibleAlignmentAnnotation(selectedOnly));
523 for (AlignmentAnnotation aa : ala)
525 aselview.addAnnotation(aa);
529 return formatSequences(format, aselview, jvsuffix);
533 * Construct an output class for an alignment in a particular filetype TODO:
534 * allow caller to detect errors and warnings encountered when generating
538 * string name of alignment format
540 * the alignment to be written out
542 * passed to AlnFile class controls whether /START-END is added to
545 * @return alignment flat file contents
547 public String formatSequences(String format, AlignmentI alignment,
552 AlignFile afile = null;
553 if (format.equalsIgnoreCase("FASTA"))
555 afile = GenericFileAdapter.getFile("FastaFile");
557 else if (format.equalsIgnoreCase("MSF"))
559 afile = GenericFileAdapter.getFile("MSFfile");
561 else if (format.equalsIgnoreCase("PileUp"))
563 afile = GenericFileAdapter.getFile("PileUpfile"); // BH NOTE LOWER CASE "file"
565 else if (format.equalsIgnoreCase("CLUSTAL"))
567 afile = GenericFileAdapter.getFile("ClustalFile");
569 else if (format.equalsIgnoreCase("BLC"))
571 afile = GenericFileAdapter.getFile("BLCFile");
573 else if (format.equalsIgnoreCase("PIR"))
575 afile = GenericFileAdapter.getFile("PIRFile");
577 else if (format.equalsIgnoreCase("PFAM"))
579 afile = GenericFileAdapter.getFile("PfamFile");
581 else if (format.equalsIgnoreCase("STH"))
583 afile = GenericFileAdapter.getFile("StockholmFile", alignment);
585 else if (format.equalsIgnoreCase("AMSA"))
587 afile = GenericFileAdapter.getFile("AMSAFile", alignment);
589 else if (format.equalsIgnoreCase(Constants.Phylip_FILE_DESC))
591 afile = GenericFileAdapter.getFile("PhylipFile");
593 else if (format.equalsIgnoreCase(Constants.JSON_FILE_DESC))
595 afile = GenericFileAdapter.getFile("JSONFile");
597 else if (format.equalsIgnoreCase("RNAML"))
599 afile = GenericFileAdapter.getFile("RnamlFile");
604 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
607 afile.setNewlineString(newline);
608 afile.addJVSuffix(jvsuffix);
609 afile.setExportSettings(exportSettings);
610 afile.configureForView(viewpanel);
612 // check whether we were given a specific alignment to export, rather than
613 // the one in the viewpanel
614 if (viewpanel == null || viewpanel.getAlignment() == null
615 || viewpanel.getAlignment() != alignment)
617 afile.setSeqs(alignment.getSequencesArray());
621 afile.setSeqs(viewpanel.getAlignment().getSequencesArray());
624 String afileresp = afile.print();
625 if (afile.hasWarningMessage())
627 System.err.println("Warning raised when writing as " + format
628 + " : " + afile.getWarningMessage());
631 } catch (Exception e)
633 System.err.println("Failed to write alignment as a '" + format
641 public static String checkProtocol(String file)
643 String protocol = FILE;
644 String ft = file.toLowerCase().trim();
645 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
646 || ft.indexOf("file:") == 0)
658 public static void main(String[] args)
661 while (i < args.length)
663 File f = new File(args[i]);
668 System.out.println("Reading file: " + f);
669 AppletFormatAdapter afa = new AppletFormatAdapter();
670 Runtime r = Runtime.getRuntime();
672 long memf = -r.totalMemory() + r.freeMemory();
673 long t1 = -System.currentTimeMillis();
674 AlignmentI al = afa.readFile(args[i], FILE,
675 new IdentifyFile().Identify(args[i], FILE));
676 t1 += System.currentTimeMillis();
678 memf += r.totalMemory() - r.freeMemory();
681 System.out.println("Alignment contains " + al.getHeight()
682 + " sequences and " + al.getWidth() + " columns.");
685 System.out.println(new AppletFormatAdapter().formatSequences(
687 } catch (Exception e)
690 .println("Couln't format the alignment for output as a FASTA file.");
691 e.printStackTrace(System.err);
696 System.out.println("Couldn't read alignment");
698 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
700 .println("Difference between free memory now and before is "
701 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
702 } catch (Exception e)
704 System.err.println("Exception when dealing with " + i
705 + "'th argument: " + args[i] + "\n" + e);
710 System.err.println("Ignoring argument '" + args[i] + "' (" + i
711 + "'th)- not a readable file.");
718 * try to discover how to access the given file as a valid datasource that
719 * will be identified as the given type.
723 * @return protocol that yields the data parsable as the given type
725 public static String resolveProtocol(String file, String format)
727 return resolveProtocol(file, format, false);
730 public static String resolveProtocol(String file, String format,
733 // TODO: test thoroughly!
734 String protocol = null;
737 System.out.println("resolving datasource started with:\n>>file\n"
738 + file + ">>endfile");
741 // This might throw a security exception in certain browsers
742 // Netscape Communicator for instance.
746 InputStream is = System.getSecurityManager().getClass()
747 .getResourceAsStream("/" + file);
755 System.err.println("Resource '" + file + "' was "
756 + (rtn ? "" : "not") + " located by classloader.");
761 protocol = AppletFormatAdapter.CLASSLOADER;
764 } catch (Exception ex)
767 .println("Exception checking resources: " + file + " " + ex);
770 if (file.indexOf("://") > -1)
772 protocol = AppletFormatAdapter.URL;
776 // skipping codebase prepend check.
777 protocol = AppletFormatAdapter.FILE;
784 System.out.println("Trying to get contents of resource as "
787 fp = new FileParse(file, protocol);
796 System.out.println("Successful.");
799 } catch (Exception e)
803 System.err.println("Exception when accessing content: " + e);
811 System.out.println("Accessing as paste.");
813 protocol = AppletFormatAdapter.PASTE;
817 fp = new FileParse(file, protocol);
822 } catch (Exception e)
824 System.err.println("Failed to access content as paste!");
833 if (format == null || format.length() == 0)
841 String idformat = new IdentifyFile().Identify(file,
843 if (idformat == null)
847 System.out.println("Format not identified. Inaccessible file.");
853 System.out.println("Format identified as " + idformat
854 + "and expected as " + format);
856 if (idformat.equals(format))
860 System.out.println("Protocol identified as " + protocol);
869 .println("File deemed not accessible via " + protocol);
874 } catch (Exception e)
878 System.err.println("File deemed not accessible via " + protocol);
888 public AlignFile getAlignFile()
893 public void setAlignFile(AlignFile alignFile)
895 this.alignFile = alignFile;