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.GenericFileAdapter;
40 * A low level class for alignment and feature IO with alignment formatting
41 * methods used by both applet and application for generating flat alignment
42 * files. It also holds the lists of magic format names that the applet and
43 * application will allow the user to read or write files with.
48 @J2SIgnoreImport({java.io.File.class})
49 public class AppletFormatAdapter
51 private AlignmentViewPanel viewpanel;
53 public static String FILE = "File";
55 public static String URL = "URL";
57 public static String PASTE = "Paste";
59 public static String CLASSLOADER = "ClassLoader";
62 * add jalview-derived non-secondary structure annotation from PDB structure
64 boolean annotFromStructure = false;
67 * add secondary structure from PDB data with built-in algorithms
69 boolean localSecondaryStruct = false;
72 * process PDB data with web services
74 boolean serviceSecondaryStruct = false;
76 private AlignFile alignFile = null;
81 * character used to write newlines
83 protected String newline = System.getProperty("line.separator");
85 private AlignExportSettingI exportSettings;
88 * List of valid format strings used in the isValidFormat method
90 public static final String[] READABLE_FORMATS = new String[]
91 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
92 "PDB", "JnetFile", "RNAML", GenericFileAdapter.Phylip_FILE_DESC, GenericFileAdapter.JSON_FILE_DESC, IdentifyFile.GFF3File,
96 * List of readable format file extensions by application in order
97 * corresponding to READABLE_FNAMES
99 public static final String[] READABLE_EXTENSIONS = new String[]
100 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
101 "sto,stk", "xml,rnaml", GenericFileAdapter.Phylip_FILE_EXT, GenericFileAdapter.JSON_FILE_EXT,
103 "jar,jvp", GenericFileAdapter.Html_FILE_EXT };
106 * List of readable formats by application in order corresponding to
107 * READABLE_EXTENSIONS
109 public static final String[] READABLE_FNAMES = new String[]
110 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm",
111 "RNAML", GenericFileAdapter.Phylip_FILE_DESC, GenericFileAdapter.JSON_FILE_DESC, IdentifyFile.GFF3File, "Jalview",
112 GenericFileAdapter.Html_FILE_DESC };
115 * List of valid format strings for use by callers of the formatSequences
118 public static final String[] WRITEABLE_FORMATS = new String[]
119 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
120 "STH", GenericFileAdapter.Phylip_FILE_DESC, GenericFileAdapter.JSON_FILE_DESC };
123 * List of extensions corresponding to file format types in WRITABLE_FNAMES
124 * that are writable by the application.
126 public static final String[] WRITABLE_EXTENSIONS = new String[]
127 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
128 "sto,stk", GenericFileAdapter.Phylip_FILE_EXT, GenericFileAdapter.JSON_FILE_EXT, "jvp" };
131 * List of writable formats by the application. Order must correspond with the
132 * WRITABLE_EXTENSIONS list of formats.
134 public static final String[] WRITABLE_FNAMES = new String[]
135 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
136 GenericFileAdapter.Phylip_FILE_DESC, GenericFileAdapter.JSON_FILE_DESC, "Jalview" };
138 public static String INVALID_CHARACTERS = "Contains invalid characters";
140 // TODO: make these messages dynamic
141 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
142 + prettyPrint(READABLE_FORMATS);
144 public AppletFormatAdapter()
148 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
150 this.viewpanel = viewpanel;
153 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
154 AlignExportSettingI settings)
156 viewpanel = alignPanel;
157 exportSettings = settings;
163 * @return grammatically correct(ish) list consisting of els elements.
165 public static String prettyPrint(String[] els)
167 StringBuffer list = new StringBuffer();
168 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
173 list.append(" and " + els[els.length - 1] + ".");
174 return list.toString();
178 public void setNewlineString(String nl)
183 public String getNewlineString()
189 * check that this format is valid for reading
192 * a format string to be compared with READABLE_FORMATS
193 * @return true if format is readable
195 public static final boolean isValidFormat(String format)
197 return isValidFormat(format, false);
201 * validate format is valid for IO
204 * a format string to be compared with either READABLE_FORMATS or
207 * when true, format is checked for containment in WRITEABLE_FORMATS
208 * @return true if format is valid
210 public static final boolean isValidFormat(String format,
213 boolean valid = false;
214 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
216 for (String element : format_list)
218 if (element.equalsIgnoreCase(format))
228 * Constructs the correct filetype parser for a characterised datasource
235 * File format of data provided by datasource
237 * @return DOCUMENT ME!
239 public AlignmentI readFile(String inFile, String type, String format)
240 throws java.io.IOException
242 // TODO: generalise mapping between format string and io. class instances
243 // using Constructor.invoke reflection
244 this.inFile = inFile;
247 if (format.equals("FASTA"))
249 alignFile = GenericFileAdapter.getFile("FastaFile", inFile, type);
251 else if (format.equals("MSF"))
253 alignFile = GenericFileAdapter.getFile("MSFfile", inFile, type);
255 else if (format.equals("PileUp"))
257 alignFile = GenericFileAdapter.getFile("PileUpfile", inFile, type);
259 else if (format.equals("CLUSTAL"))
261 alignFile = GenericFileAdapter.getFile("ClustalFile", inFile, type);
263 else if (format.equals("BLC"))
265 alignFile = GenericFileAdapter.getFile("BLCFile", inFile, type);
267 else if (format.equals("PIR"))
269 alignFile = GenericFileAdapter.getFile("PIRFile", inFile, type);
271 else if (format.equals("PFAM"))
273 alignFile = GenericFileAdapter.getFile("PfamFile", inFile, type);
275 else if (format.equals("JnetFile"))
277 alignFile = GenericFileAdapter.getFile("JPredFile", inFile, type);
278 ((JPredFile) alignFile).removeNonSequences();
280 else if (format.equals("PDB"))
282 alignFile = new MCview.PDBfile(annotFromStructure,
283 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
284 // Uncomment to test Jmol data based PDB processing: JAL-1213
285 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
287 else if (format.equals("STH"))
289 alignFile = GenericFileAdapter.getFile("StockholmFile", inFile, type);
291 else if (format.equals("SimpleBLAST"))
293 alignFile = GenericFileAdapter.getFile("SimpleBlastFile", inFile, type);
295 else if (format.equals(PhylipFile.FILE_DESC))
297 alignFile = GenericFileAdapter.getFile("PhylipFile", inFile, type);
299 else if (format.equals(GenericFileAdapter.JSON_FILE_DESC))
301 alignFile = GenericFileAdapter.getFile("JSONFile", inFile, type);
303 else if (format.equals(GenericFileAdapter.Html_FILE_DESC))
305 alignFile = GenericFileAdapter.getFile("HtmlFile", inFile, type);
307 else if (format.equals("RNAML"))
309 alignFile = GenericFileAdapter.getFile("RnamlFile", inFile, type);
311 else if (format.equals(IdentifyFile.GFF3File))
313 alignFile = GenericFileAdapter.getFile("Gff3File", inFile, type);
315 return buildAlignmentFrom(alignFile);
316 } catch (Exception e)
319 System.err.println("Failed to read alignment using the '" + format
320 + "' reader.\n" + e);
322 if (e.getMessage() != null
323 && e.getMessage().startsWith(INVALID_CHARACTERS))
325 throw new java.io.IOException(e.getMessage());
328 // Finally test if the user has pasted just the sequence, no id
329 if (type.equalsIgnoreCase("Paste"))
333 // Possible sequence is just residues with no label
334 alignFile = GenericFileAdapter.getFile("FastaFile", ">UNKNOWN\n" + inFile, "Paste");
335 return buildAlignmentFrom(alignFile);
337 } catch (Exception ex)
339 if (ex.toString().startsWith(INVALID_CHARACTERS))
341 throw new java.io.IOException(e.getMessage());
344 ex.printStackTrace();
348 // If we get to this stage, the format was not supported
349 throw new java.io.IOException(SUPPORTED_FORMATS);
354 * Constructs the correct filetype parser for an already open datasource
357 * an existing datasource
359 * File format of data that will be provided by datasource
361 * @return DOCUMENT ME!
363 public AlignmentI readFromFile(FileParse source, String format)
364 throws java.io.IOException
366 // TODO: generalise mapping between format string and io. class instances
367 // using Constructor.invoke reflection
368 // This is exactly the same as the readFile method except we substitute
369 // 'inFile, type' with 'source'
370 this.inFile = source.getInFile();
371 String type = source.type;
374 if (format.equals("FASTA"))
376 alignFile = GenericFileAdapter.getFile("FastaFile", source);
378 else if (format.equals("MSF"))
380 alignFile = GenericFileAdapter.getFile("MSFfile", source);
382 else if (format.equals("PileUp"))
384 alignFile = GenericFileAdapter.getFile("PileUpfile", source);
386 else if (format.equals("CLUSTAL"))
388 alignFile = GenericFileAdapter.getFile("ClustalFile", source);
390 else if (format.equals("BLC"))
392 alignFile = GenericFileAdapter.getFile("BLCFile", source);
394 else if (format.equals("PIR"))
396 alignFile = GenericFileAdapter.getFile("PIRFile", source);
398 else if (format.equals("PFAM"))
400 alignFile = GenericFileAdapter.getFile("PfamFile", source);
402 else if (format.equals("JnetFile"))
404 alignFile = GenericFileAdapter.getFile("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 = GenericFileAdapter.getFile("StockholmFile", source);
416 else if (format.equals("RNAML"))
418 alignFile = GenericFileAdapter.getFile("RnamlFile", source);
420 else if (format.equals("SimpleBLAST"))
422 alignFile = GenericFileAdapter.getFile("SimpleBlastFile", source);
424 else if (format.equals(GenericFileAdapter.Phylip_FILE_DESC))
426 alignFile = GenericFileAdapter.getFile("PhylipFile", source);
428 else if (format.equals(IdentifyFile.GFF3File))
430 alignFile = GenericFileAdapter.getFile("Gff3File", inFile, type);
432 else if (format.equals(GenericFileAdapter.JSON_FILE_DESC))
434 alignFile = GenericFileAdapter.getFile("JSONFile", source);
436 else if (format.equals(GenericFileAdapter.Html_FILE_DESC))
438 alignFile = GenericFileAdapter.getFile("HtmlFile", source);
441 return buildAlignmentFrom(alignFile);
443 } catch (Exception e)
446 System.err.println("Failed to read alignment using the '" + format
447 + "' reader.\n" + e);
449 if (e.getMessage() != null
450 && e.getMessage().startsWith(INVALID_CHARACTERS))
452 throw new java.io.IOException(e.getMessage());
455 // Finally test if the user has pasted just the sequence, no id
456 if (type.equalsIgnoreCase("Paste"))
460 // Possible sequence is just residues with no label
461 alignFile = GenericFileAdapter.getFile("FastaFile", ">UNKNOWN\n" + inFile, "Paste");
462 return buildAlignmentFrom(alignFile);
464 } catch (Exception ex)
466 if (ex.toString().startsWith(INVALID_CHARACTERS))
468 throw new java.io.IOException(e.getMessage());
471 ex.printStackTrace();
475 // If we get to this stage, the format was not supported
476 throw new java.io.IOException(SUPPORTED_FORMATS);
482 * boilerplate method to handle data from an AlignFile and construct a new
483 * alignment or import to an existing alignment
486 * @return AlignmentI instance ready to pass to a UI constructor
488 private AlignmentI buildAlignmentFrom(AlignFile alignFile2)
490 // Standard boilerplate for creating alignment from parser
491 // alignFile.configureForView(viewpanel);
493 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
495 alignFile.addAnnotations(al);
497 alignFile.addGroups(al);
503 * create an alignment flatfile from a Jalview alignment view
507 * @param selectedOnly
508 * @return flatfile in a string
510 public String formatSequences(String format, boolean jvsuffix,
511 AlignmentViewPanel ap, boolean selectedOnly)
514 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
515 selectedOnly, false);
516 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
518 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
519 .getVisibleAlignmentAnnotation(selectedOnly));
522 for (AlignmentAnnotation aa : ala)
524 aselview.addAnnotation(aa);
528 return formatSequences(format, aselview, jvsuffix);
532 * Construct an output class for an alignment in a particular filetype TODO:
533 * allow caller to detect errors and warnings encountered when generating
537 * string name of alignment format
539 * the alignment to be written out
541 * passed to AlnFile class controls whether /START-END is added to
544 * @return alignment flat file contents
546 public String formatSequences(String format, AlignmentI alignment,
551 AlignFile afile = null;
552 if (format.equalsIgnoreCase("FASTA"))
554 afile = GenericFileAdapter.getFile("FastaFile");
556 else if (format.equalsIgnoreCase("MSF"))
558 afile = GenericFileAdapter.getFile("MSFfile");
560 else if (format.equalsIgnoreCase("PileUp"))
562 afile = GenericFileAdapter.getFile("PileUpfile"); // BH NOTE LOWER CASE "file"
564 else if (format.equalsIgnoreCase("CLUSTAL"))
566 afile = GenericFileAdapter.getFile("ClustalFile");
568 else if (format.equalsIgnoreCase("BLC"))
570 afile = GenericFileAdapter.getFile("BLCFile");
572 else if (format.equalsIgnoreCase("PIR"))
574 afile = GenericFileAdapter.getFile("PIRFile");
576 else if (format.equalsIgnoreCase("PFAM"))
578 afile = GenericFileAdapter.getFile("PfamFile");
580 else if (format.equalsIgnoreCase("STH"))
582 afile = GenericFileAdapter.getFile("StockholmFile", alignment);
584 else if (format.equalsIgnoreCase("AMSA"))
586 afile = GenericFileAdapter.getFile("AMSAFile", alignment);
588 else if (format.equalsIgnoreCase(GenericFileAdapter.Phylip_FILE_DESC))
590 afile = GenericFileAdapter.getFile("PhylipFile");
592 else if (format.equalsIgnoreCase(GenericFileAdapter.JSON_FILE_DESC))
594 afile = GenericFileAdapter.getFile("JSONFile");
596 else if (format.equalsIgnoreCase("RNAML"))
598 afile = GenericFileAdapter.getFile("RnamlFile");
603 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
606 afile.setNewlineString(newline);
607 afile.addJVSuffix(jvsuffix);
608 afile.setExportSettings(exportSettings);
609 afile.configureForView(viewpanel);
611 // check whether we were given a specific alignment to export, rather than
612 // the one in the viewpanel
613 if (viewpanel == null || viewpanel.getAlignment() == null
614 || viewpanel.getAlignment() != alignment)
616 afile.setSeqs(alignment.getSequencesArray());
620 afile.setSeqs(viewpanel.getAlignment().getSequencesArray());
623 String afileresp = afile.print();
624 if (afile.hasWarningMessage())
626 System.err.println("Warning raised when writing as " + format
627 + " : " + afile.getWarningMessage());
630 } catch (Exception e)
632 System.err.println("Failed to write alignment as a '" + format
640 public static String checkProtocol(String file)
642 String protocol = FILE;
643 String ft = file.toLowerCase().trim();
644 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
645 || ft.indexOf("file:") == 0)
657 public static void main(String[] args)
660 while (i < args.length)
662 File f = new File(args[i]);
667 System.out.println("Reading file: " + f);
668 AppletFormatAdapter afa = new AppletFormatAdapter();
669 Runtime r = Runtime.getRuntime();
671 long memf = -r.totalMemory() + r.freeMemory();
672 long t1 = -System.currentTimeMillis();
673 AlignmentI al = afa.readFile(args[i], FILE,
674 new IdentifyFile().Identify(args[i], FILE));
675 t1 += System.currentTimeMillis();
677 memf += r.totalMemory() - r.freeMemory();
680 System.out.println("Alignment contains " + al.getHeight()
681 + " sequences and " + al.getWidth() + " columns.");
684 System.out.println(new AppletFormatAdapter().formatSequences(
686 } catch (Exception e)
689 .println("Couln't format the alignment for output as a FASTA file.");
690 e.printStackTrace(System.err);
695 System.out.println("Couldn't read alignment");
697 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
699 .println("Difference between free memory now and before is "
700 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
701 } catch (Exception e)
703 System.err.println("Exception when dealing with " + i
704 + "'th argument: " + args[i] + "\n" + e);
709 System.err.println("Ignoring argument '" + args[i] + "' (" + i
710 + "'th)- not a readable file.");
717 * try to discover how to access the given file as a valid datasource that
718 * will be identified as the given type.
722 * @return protocol that yields the data parsable as the given type
724 public static String resolveProtocol(String file, String format)
726 return resolveProtocol(file, format, false);
729 public static String resolveProtocol(String file, String format,
732 // TODO: test thoroughly!
733 String protocol = null;
736 System.out.println("resolving datasource started with:\n>>file\n"
737 + file + ">>endfile");
740 // This might throw a security exception in certain browsers
741 // Netscape Communicator for instance.
745 InputStream is = System.getSecurityManager().getClass()
746 .getResourceAsStream("/" + file);
754 System.err.println("Resource '" + file + "' was "
755 + (rtn ? "" : "not") + " located by classloader.");
760 protocol = AppletFormatAdapter.CLASSLOADER;
763 } catch (Exception ex)
766 .println("Exception checking resources: " + file + " " + ex);
769 if (file.indexOf("://") > -1)
771 protocol = AppletFormatAdapter.URL;
775 // skipping codebase prepend check.
776 protocol = AppletFormatAdapter.FILE;
783 System.out.println("Trying to get contents of resource as "
786 fp = new FileParse(file, protocol);
795 System.out.println("Successful.");
798 } catch (Exception e)
802 System.err.println("Exception when accessing content: " + e);
810 System.out.println("Accessing as paste.");
812 protocol = AppletFormatAdapter.PASTE;
816 fp = new FileParse(file, protocol);
821 } catch (Exception e)
823 System.err.println("Failed to access content as paste!");
832 if (format == null || format.length() == 0)
840 String idformat = new IdentifyFile().Identify(file,
842 if (idformat == null)
846 System.out.println("Format not identified. Inaccessible file.");
852 System.out.println("Format identified as " + idformat
853 + "and expected as " + format);
855 if (idformat.equals(format))
859 System.out.println("Protocol identified as " + protocol);
868 .println("File deemed not accessible via " + protocol);
873 } catch (Exception e)
877 System.err.println("File deemed not accessible via " + protocol);
887 public AlignFile getAlignFile()
892 public void setAlignFile(AlignFile alignFile)
894 this.alignFile = alignFile;