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.gui.AlignmentPanel;
30 import jalview.util.MessageManager;
33 import java.io.InputStream;
34 import java.util.List;
37 * A low level class for alignment and feature IO with alignment formatting
38 * methods used by both applet and application for generating flat alignment
39 * files. It also holds the lists of magic format names that the applet and
40 * application will allow the user to read or write files with.
45 public class AppletFormatAdapter
47 private AlignmentViewPanel viewpanel;
49 public static String FILE = "File";
51 public static String URL = "URL";
53 public static String PASTE = "Paste";
55 public static String CLASSLOADER = "ClassLoader";
58 * add jalview-derived non-secondary structure annotation from PDB structure
60 boolean annotFromStructure = false;
63 * add secondary structure from PDB data with built-in algorithms
65 boolean localSecondaryStruct = false;
68 * process PDB data with web services
70 boolean serviceSecondaryStruct = false;
72 private AlignFile alignFile = null;
77 * character used to write newlines
79 protected String newline = System.getProperty("line.separator");
81 private AlignExportSettingI exportSettings;
84 * List of valid format strings used in the isValidFormat method
86 public static final String[] READABLE_FORMATS = new String[]
87 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
88 "PDB", "JnetFile", "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.GFF3File,
92 * List of readable format file extensions by application in order
93 * corresponding to READABLE_FNAMES
95 public static final String[] READABLE_EXTENSIONS = new String[]
96 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
97 "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT, JSONFile.FILE_EXT,
99 "jar,jvp", HtmlFile.FILE_EXT };
102 * List of readable formats by application in order corresponding to
103 * READABLE_EXTENSIONS
105 public static final String[] READABLE_FNAMES = new String[]
106 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm",
107 "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.GFF3File, "Jalview",
108 HtmlFile.FILE_DESC };
111 * List of valid format strings for use by callers of the formatSequences
114 public static final String[] WRITEABLE_FORMATS = new String[]
115 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
116 "STH", PhylipFile.FILE_DESC, JSONFile.FILE_DESC };
119 * List of extensions corresponding to file format types in WRITABLE_FNAMES
120 * that are writable by the application.
122 public static final String[] WRITABLE_EXTENSIONS = new String[]
123 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
124 "sto,stk", PhylipFile.FILE_EXT, JSONFile.FILE_EXT, "jvp" };
127 * List of writable formats by the application. Order must correspond with the
128 * WRITABLE_EXTENSIONS list of formats.
130 public static final String[] WRITABLE_FNAMES = new String[]
131 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
132 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, "Jalview" };
134 public static String INVALID_CHARACTERS = "Contains invalid characters";
136 // TODO: make these messages dynamic
137 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
138 + prettyPrint(READABLE_FORMATS);
140 public AppletFormatAdapter()
144 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
146 this.viewpanel = viewpanel;
149 public AppletFormatAdapter(AlignmentPanel alignPanel,
150 AlignExportSettingI settings)
152 viewpanel = alignPanel;
153 exportSettings = settings;
159 * @return grammatically correct(ish) list consisting of els elements.
161 public static String prettyPrint(String[] els)
163 StringBuffer list = new StringBuffer();
164 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
169 list.append(" and " + els[els.length - 1] + ".");
170 return list.toString();
174 public void setNewlineString(String nl)
179 public String getNewlineString()
185 * check that this format is valid for reading
188 * a format string to be compared with READABLE_FORMATS
189 * @return true if format is readable
191 public static final boolean isValidFormat(String format)
193 return isValidFormat(format, false);
197 * validate format is valid for IO
200 * a format string to be compared with either READABLE_FORMATS or
203 * when true, format is checked for containment in WRITEABLE_FORMATS
204 * @return true if format is valid
206 public static final boolean isValidFormat(String format,
209 boolean valid = false;
210 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
212 for (String element : format_list)
214 if (element.equalsIgnoreCase(format))
224 * Constructs the correct filetype parser for a characterised datasource
231 * File format of data provided by datasource
233 * @return DOCUMENT ME!
235 public AlignmentI readFile(String inFile, String type, String format)
236 throws java.io.IOException
238 // TODO: generalise mapping between format string and io. class instances
239 // using Constructor.invoke reflection
240 this.inFile = inFile;
243 if (format.equals("FASTA"))
245 alignFile = new FastaFile(inFile, type);
247 else if (format.equals("MSF"))
249 alignFile = new MSFfile(inFile, type);
251 else if (format.equals("PileUp"))
253 alignFile = new PileUpfile(inFile, type);
255 else if (format.equals("CLUSTAL"))
257 alignFile = new ClustalFile(inFile, type);
259 else if (format.equals("BLC"))
261 alignFile = new BLCFile(inFile, type);
263 else if (format.equals("PIR"))
265 alignFile = new PIRFile(inFile, type);
267 else if (format.equals("PFAM"))
269 alignFile = new PfamFile(inFile, type);
271 else if (format.equals("JnetFile"))
273 alignFile = new JPredFile(inFile, type);
274 ((JPredFile) alignFile).removeNonSequences();
276 else if (format.equals("PDB"))
278 alignFile = new MCview.PDBfile(annotFromStructure,
279 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
280 // Uncomment to test Jmol data based PDB processing: JAL-1213
281 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
283 else if (format.equals("STH"))
285 alignFile = new StockholmFile(inFile, type);
287 else if (format.equals("SimpleBLAST"))
289 alignFile = new SimpleBlastFile(inFile, type);
291 else if (format.equals(PhylipFile.FILE_DESC))
293 alignFile = new PhylipFile(inFile, type);
295 else if (format.equals(JSONFile.FILE_DESC))
297 alignFile = new JSONFile(inFile, type);
299 else if (format.equals(HtmlFile.FILE_DESC))
301 alignFile = new HtmlFile(inFile, type);
303 else if (format.equals("RNAML"))
305 alignFile = new RnamlFile(inFile, type);
307 else if (format.equals(IdentifyFile.GFF3File))
309 alignFile = new Gff3File(inFile, type);
311 return buildAlignmentFrom(alignFile);
312 } catch (Exception e)
315 System.err.println("Failed to read alignment using the '" + format
316 + "' reader.\n" + e);
318 if (e.getMessage() != null
319 && e.getMessage().startsWith(INVALID_CHARACTERS))
321 throw new java.io.IOException(e.getMessage());
324 // Finally test if the user has pasted just the sequence, no id
325 if (type.equalsIgnoreCase("Paste"))
329 // Possible sequence is just residues with no label
330 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
331 return buildAlignmentFrom(alignFile);
333 } catch (Exception ex)
335 if (ex.toString().startsWith(INVALID_CHARACTERS))
337 throw new java.io.IOException(e.getMessage());
340 ex.printStackTrace();
344 // If we get to this stage, the format was not supported
345 throw new java.io.IOException(SUPPORTED_FORMATS);
350 * Constructs the correct filetype parser for an already open datasource
353 * an existing datasource
355 * File format of data that will be provided by datasource
357 * @return DOCUMENT ME!
359 public AlignmentI readFromFile(FileParse source, String format)
360 throws java.io.IOException
362 // TODO: generalise mapping between format string and io. class instances
363 // using Constructor.invoke reflection
364 // This is exactly the same as the readFile method except we substitute
365 // 'inFile, type' with 'source'
366 this.inFile = source.getInFile();
367 String type = source.type;
370 if (format.equals("FASTA"))
372 alignFile = new FastaFile(source);
374 else if (format.equals("MSF"))
376 alignFile = new MSFfile(source);
378 else if (format.equals("PileUp"))
380 alignFile = new PileUpfile(source);
382 else if (format.equals("CLUSTAL"))
384 alignFile = new ClustalFile(source);
386 else if (format.equals("BLC"))
388 alignFile = new BLCFile(source);
390 else if (format.equals("PIR"))
392 alignFile = new PIRFile(source);
394 else if (format.equals("PFAM"))
396 alignFile = new PfamFile(source);
398 else if (format.equals("JnetFile"))
400 alignFile = new JPredFile(source);
401 ((JPredFile) alignFile).removeNonSequences();
403 else if (format.equals("PDB"))
405 alignFile = new MCview.PDBfile(annotFromStructure,
406 localSecondaryStruct, serviceSecondaryStruct, source);
408 else if (format.equals("STH"))
410 alignFile = new StockholmFile(source);
412 else if (format.equals("RNAML"))
414 alignFile = new RnamlFile(source);
416 else if (format.equals("SimpleBLAST"))
418 alignFile = new SimpleBlastFile(source);
420 else if (format.equals(PhylipFile.FILE_DESC))
422 alignFile = new PhylipFile(source);
424 else if (format.equals(IdentifyFile.GFF3File))
426 alignFile = new Gff3File(inFile, type);
428 else if (format.equals(JSONFile.FILE_DESC))
430 alignFile = new JSONFile(source);
432 else if (format.equals(HtmlFile.FILE_DESC))
434 alignFile = new HtmlFile(source);
437 return buildAlignmentFrom(alignFile);
439 } catch (Exception e)
442 System.err.println("Failed to read alignment using the '" + format
443 + "' reader.\n" + e);
445 if (e.getMessage() != null
446 && e.getMessage().startsWith(INVALID_CHARACTERS))
448 throw new java.io.IOException(e.getMessage());
451 // Finally test if the user has pasted just the sequence, no id
452 if (type.equalsIgnoreCase("Paste"))
456 // Possible sequence is just residues with no label
457 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
458 return buildAlignmentFrom(alignFile);
460 } catch (Exception ex)
462 if (ex.toString().startsWith(INVALID_CHARACTERS))
464 throw new java.io.IOException(e.getMessage());
467 ex.printStackTrace();
471 // If we get to this stage, the format was not supported
472 throw new java.io.IOException(SUPPORTED_FORMATS);
478 * boilerplate method to handle data from an AlignFile and construct a new
479 * alignment or import to an existing alignment
482 * @return AlignmentI instance ready to pass to a UI constructor
484 private AlignmentI buildAlignmentFrom(AlignFile alignFile2)
486 // Standard boilerplate for creating alignment from parser
487 alignFile.configureForView(viewpanel);
489 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
491 alignFile.addAnnotations(al);
493 alignFile.addGroups(al);
499 * create an alignment flatfile from a Jalview alignment view
503 * @param selectedOnly
504 * @return flatfile in a string
506 public String formatSequences(String format, boolean jvsuffix,
507 AlignmentViewPanel ap, boolean selectedOnly)
510 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
511 selectedOnly, false);
512 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
514 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
515 .getVisibleAlignmentAnnotation(selectedOnly));
518 for (AlignmentAnnotation aa : ala)
520 aselview.addAnnotation(aa);
524 return formatSequences(format, aselview, jvsuffix);
528 * Construct an output class for an alignment in a particular filetype TODO:
529 * allow caller to detect errors and warnings encountered when generating
533 * string name of alignment format
535 * the alignment to be written out
537 * passed to AlnFile class controls whether /START-END is added to
540 * @return alignment flat file contents
542 public String formatSequences(String format, AlignmentI alignment,
547 AlignFile afile = null;
548 if (format.equalsIgnoreCase("FASTA"))
550 afile = new FastaFile();
552 else if (format.equalsIgnoreCase("MSF"))
554 afile = new MSFfile();
556 else if (format.equalsIgnoreCase("PileUp"))
558 afile = new PileUpfile();
560 else if (format.equalsIgnoreCase("CLUSTAL"))
562 afile = new ClustalFile();
564 else if (format.equalsIgnoreCase("BLC"))
566 afile = new BLCFile();
568 else if (format.equalsIgnoreCase("PIR"))
570 afile = new PIRFile();
572 else if (format.equalsIgnoreCase("PFAM"))
574 afile = new PfamFile();
576 else if (format.equalsIgnoreCase("STH"))
578 afile = new StockholmFile(alignment);
580 else if (format.equalsIgnoreCase("AMSA"))
582 afile = new AMSAFile(alignment);
584 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
586 afile = new PhylipFile();
588 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
590 afile = new JSONFile();
592 else if (format.equalsIgnoreCase("RNAML"))
594 afile = new RnamlFile();
599 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
601 afile.setNewlineString(newline);
602 afile.addJVSuffix(jvsuffix);
604 afile.setExportSettings(exportSettings);
606 afile.configureForView(viewpanel);
608 // check whether we were given a specific alignment to export, rather than
609 // the one in the viewpanel
610 if (viewpanel == null || viewpanel.getAlignment() == null
611 || viewpanel.getAlignment() != alignment)
613 afile.setSeqs(alignment.getSequencesArray());
617 afile.setSeqs(viewpanel.getAlignment().getSequencesArray());
620 String afileresp = afile.print();
621 if (afile.hasWarningMessage())
623 System.err.println("Warning raised when writing as " + format
624 + " : " + afile.getWarningMessage());
627 } catch (Exception e)
629 System.err.println("Failed to write alignment as a '" + format
637 public static String checkProtocol(String file)
639 String protocol = FILE;
640 String ft = file.toLowerCase().trim();
641 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
642 || ft.indexOf("file:") == 0)
649 public static void main(String[] args)
652 while (i < args.length)
654 File f = new File(args[i]);
659 System.out.println("Reading file: " + f);
660 AppletFormatAdapter afa = new AppletFormatAdapter();
661 Runtime r = Runtime.getRuntime();
663 long memf = -r.totalMemory() + r.freeMemory();
664 long t1 = -System.currentTimeMillis();
665 AlignmentI al = afa.readFile(args[i], FILE,
666 new IdentifyFile().Identify(args[i], FILE));
667 t1 += System.currentTimeMillis();
669 memf += r.totalMemory() - r.freeMemory();
672 System.out.println("Alignment contains " + al.getHeight()
673 + " sequences and " + al.getWidth() + " columns.");
676 System.out.println(new AppletFormatAdapter().formatSequences(
678 } catch (Exception e)
681 .println("Couln't format the alignment for output as a FASTA file.");
682 e.printStackTrace(System.err);
687 System.out.println("Couldn't read alignment");
689 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
691 .println("Difference between free memory now and before is "
692 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
693 } catch (Exception e)
695 System.err.println("Exception when dealing with " + i
696 + "'th argument: " + args[i] + "\n" + e);
701 System.err.println("Ignoring argument '" + args[i] + "' (" + i
702 + "'th)- not a readable file.");
709 * try to discover how to access the given file as a valid datasource that
710 * will be identified as the given type.
714 * @return protocol that yields the data parsable as the given type
716 public static String resolveProtocol(String file, String format)
718 return resolveProtocol(file, format, false);
721 public static String resolveProtocol(String file, String format,
724 // TODO: test thoroughly!
725 String protocol = null;
728 System.out.println("resolving datasource started with:\n>>file\n"
729 + file + ">>endfile");
732 // This might throw a security exception in certain browsers
733 // Netscape Communicator for instance.
737 InputStream is = System.getSecurityManager().getClass()
738 .getResourceAsStream("/" + file);
746 System.err.println("Resource '" + file + "' was "
747 + (rtn ? "" : "not") + " located by classloader.");
752 protocol = AppletFormatAdapter.CLASSLOADER;
755 } catch (Exception ex)
758 .println("Exception checking resources: " + file + " " + ex);
761 if (file.indexOf("://") > -1)
763 protocol = AppletFormatAdapter.URL;
767 // skipping codebase prepend check.
768 protocol = AppletFormatAdapter.FILE;
775 System.out.println("Trying to get contents of resource as "
778 fp = new FileParse(file, protocol);
787 System.out.println("Successful.");
790 } catch (Exception e)
794 System.err.println("Exception when accessing content: " + e);
802 System.out.println("Accessing as paste.");
804 protocol = AppletFormatAdapter.PASTE;
808 fp = new FileParse(file, protocol);
813 } catch (Exception e)
815 System.err.println("Failed to access content as paste!");
824 if (format == null || format.length() == 0)
832 String idformat = new jalview.io.IdentifyFile().Identify(file,
834 if (idformat == null)
838 System.out.println("Format not identified. Inaccessible file.");
844 System.out.println("Format identified as " + idformat
845 + "and expected as " + format);
847 if (idformat.equals(format))
851 System.out.println("Protocol identified as " + protocol);
860 .println("File deemed not accessible via " + protocol);
865 } catch (Exception e)
869 System.err.println("File deemed not accessible via " + protocol);
879 public AlignFile getAlignFile()
884 public void setAlignFile(AlignFile alignFile)
886 this.alignFile = alignFile;