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.IOException;
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[] { "BLC",
87 "CLUSTAL", "FASTA", "MEGA", "MSF", "PileUp", "PIR", "PFAM", "STH",
89 "JnetFile", "RNAML", PhylipFile.FILE_DESC, JSONFile.FILE_DESC,
90 IdentifyFile.GFF3File, "HTML" };
93 * List of readable format file extensions by application in order
94 * corresponding to READABLE_FNAMES
96 public static final String[] READABLE_EXTENSIONS = new String[] {
97 "fa, fasta, mfa, fastq", "aln", "pfam", "meg", "msf", "pir", "blc",
99 "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT, JSONFile.FILE_EXT,
100 ".gff2,gff3", "jar,jvp", HtmlFile.FILE_EXT };
103 * List of readable formats by application in order corresponding to
104 * READABLE_EXTENSIONS
106 public static final String[] READABLE_FNAMES = new String[] { "Fasta",
107 "Clustal", "PFAM", "MEGA", "MSF", "PIR", "BLC", "AMSA", "Stockholm",
109 PhylipFile.FILE_DESC, JSONFile.FILE_DESC, IdentifyFile.GFF3File,
110 "Jalview", HtmlFile.FILE_DESC };
113 * List of valid format strings for use by callers of the formatSequences
116 public static final String[] WRITEABLE_FORMATS = new String[] { "BLC",
117 "CLUSTAL", "FASTA", "MEGA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
119 PhylipFile.FILE_DESC, JSONFile.FILE_DESC };
122 * List of extensions corresponding to file format types in WRITABLE_FNAMES
123 * that are writable by the application.
125 public static final String[] WRITABLE_EXTENSIONS = new String[] {
126 "fa, fasta, mfa, fastq", "aln", "pfam", "meg", "msf", "pir", "blc",
128 "sto,stk", PhylipFile.FILE_EXT, JSONFile.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[] { "Fasta",
135 "Clustal", "PFAM", "MEGA", "MSF", "PIR", "BLC", "AMSA", "STH",
136 PhylipFile.FILE_DESC, JSONFile.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();
177 public void setNewlineString(String nl)
182 public String getNewlineString()
188 * check that this format is valid for reading
191 * a format string to be compared with READABLE_FORMATS
192 * @return true if format is readable
194 public static final boolean isValidFormat(String format)
196 return isValidFormat(format, false);
200 * validate format is valid for IO
203 * a format string to be compared with either READABLE_FORMATS or
206 * when true, format is checked for containment in WRITEABLE_FORMATS
207 * @return true if format is valid
209 public static final boolean isValidFormat(String format,
216 boolean valid = false;
217 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
219 for (String element : format_list)
221 if (element.equalsIgnoreCase(format))
231 * Constructs the correct filetype parser for a characterised datasource
238 * File format of data provided by datasource
240 * @return DOCUMENT ME!
242 public AlignmentI readFile(String inFile, String type, String format)
243 throws java.io.IOException
245 // TODO: generalise mapping between format string and io. class instances
246 // using Constructor.invoke reflection
247 this.inFile = inFile;
250 if (format.equals("FASTA"))
252 alignFile = new FastaFile(inFile, type);
254 else if (format.equals("MSF"))
256 alignFile = new MSFfile(inFile, type);
258 else if (format.equals("PileUp"))
260 alignFile = new PileUpfile(inFile, type);
262 else if (format.equals("CLUSTAL"))
264 alignFile = new ClustalFile(inFile, type);
266 else if (format.equals("BLC"))
268 alignFile = new BLCFile(inFile, type);
270 else if (format.equals("PIR"))
272 alignFile = new PIRFile(inFile, type);
274 else if (format.equals("PFAM"))
276 alignFile = new PfamFile(inFile, type);
278 else if (format.equals("JnetFile"))
280 alignFile = new JPredFile(inFile, type);
281 ((JPredFile) alignFile).removeNonSequences();
283 else if (format.equals("PDB"))
285 alignFile = new MCview.PDBfile(annotFromStructure,
286 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
287 // Uncomment to test Jmol data based PDB processing: JAL-1213
288 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
290 else if (format.equals("STH"))
292 alignFile = new StockholmFile(inFile, type);
294 else if (format.equals("SimpleBLAST"))
296 alignFile = new SimpleBlastFile(inFile, type);
298 else if (format.equals(PhylipFile.FILE_DESC))
300 alignFile = new PhylipFile(inFile, type);
302 else if (format.equals(JSONFile.FILE_DESC))
304 alignFile = new JSONFile(inFile, type);
306 else if (format.equals(HtmlFile.FILE_DESC))
308 alignFile = new HtmlFile(inFile, type);
310 else if (format.equals("RNAML"))
312 alignFile = new RnamlFile(inFile, type);
314 else if (format.equals("MEGA"))
316 alignFile = new MegaFile(inFile, type);
318 else if (format.equals(IdentifyFile.GFF3File))
320 alignFile = new Gff3File(inFile, type);
322 return buildAlignmentFrom(alignFile);
323 } catch (Exception e)
326 System.err.println("Failed to read alignment using the '" + format
327 + "' reader.\n" + e);
329 if (e.getMessage() != null
330 && e.getMessage().startsWith(INVALID_CHARACTERS))
332 throw new java.io.IOException(e.getMessage());
335 // Finally test if the user has pasted just the sequence, no id
336 if (type.equalsIgnoreCase("Paste"))
340 // Possible sequence is just residues with no label
341 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
342 return buildAlignmentFrom(alignFile);
344 } catch (Exception ex)
346 if (ex.toString().startsWith(INVALID_CHARACTERS))
348 throw new java.io.IOException(e.getMessage());
351 ex.printStackTrace();
354 if (format.equalsIgnoreCase("HTML"))
356 throw new IOException(e.getMessage());
358 // If we get to this stage, the format was not supported
359 throw new java.io.IOException(SUPPORTED_FORMATS);
364 * Constructs the correct filetype parser for an already open datasource
367 * an existing datasource
369 * File format of data that will be provided by datasource
371 * @return DOCUMENT ME!
373 public AlignmentI readFromFile(FileParse source, String format)
374 throws java.io.IOException
376 // TODO: generalise mapping between format string and io. class instances
377 // using Constructor.invoke reflection
378 // This is exactly the same as the readFile method except we substitute
379 // 'inFile, type' with 'source'
380 this.inFile = source.getInFile();
381 String type = source.type;
384 if (format.equals("FASTA"))
386 alignFile = new FastaFile(source);
388 else if (format.equals("MSF"))
390 alignFile = new MSFfile(source);
392 else if (format.equals("PileUp"))
394 alignFile = new PileUpfile(source);
396 else if (format.equals("CLUSTAL"))
398 alignFile = new ClustalFile(source);
400 else if (format.equals("BLC"))
402 alignFile = new BLCFile(source);
404 else if (format.equals("PIR"))
406 alignFile = new PIRFile(source);
408 else if (format.equals("PFAM"))
410 alignFile = new PfamFile(source);
412 else if (format.equals("JnetFile"))
414 alignFile = new JPredFile(source);
415 ((JPredFile) alignFile).removeNonSequences();
417 else if (format.equals("PDB"))
419 alignFile = new MCview.PDBfile(annotFromStructure,
420 localSecondaryStruct, serviceSecondaryStruct, source);
422 else if (format.equals("STH"))
424 alignFile = new StockholmFile(source);
426 else if (format.equals("RNAML"))
428 alignFile = new RnamlFile(source);
430 else if (format.equals("MEGA"))
432 alignFile = new MegaFile(source);
434 else if (format.equals("SimpleBLAST"))
436 alignFile = new SimpleBlastFile(source);
438 else if (format.equals(PhylipFile.FILE_DESC))
440 alignFile = new PhylipFile(source);
442 else if (format.equals(IdentifyFile.GFF3File))
444 alignFile = new Gff3File(inFile, type);
446 else if (format.equals(JSONFile.FILE_DESC))
448 alignFile = new JSONFile(source);
450 else if (format.equals(HtmlFile.FILE_DESC))
452 alignFile = new HtmlFile(source);
455 return buildAlignmentFrom(alignFile);
457 } catch (Exception e)
460 System.err.println("Failed to read alignment using the '" + format
461 + "' reader.\n" + e);
463 if (e.getMessage() != null
464 && e.getMessage().startsWith(INVALID_CHARACTERS))
466 throw new java.io.IOException(e.getMessage());
469 // Finally test if the user has pasted just the sequence, no id
470 if (type.equalsIgnoreCase("Paste"))
474 // Possible sequence is just residues with no label
475 alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
476 return buildAlignmentFrom(alignFile);
478 } catch (Exception ex)
480 if (ex.toString().startsWith(INVALID_CHARACTERS))
482 throw new java.io.IOException(e.getMessage());
485 ex.printStackTrace();
489 // If we get to this stage, the format was not supported
490 throw new java.io.IOException(SUPPORTED_FORMATS);
495 * boilerplate method to handle data from an AlignFile and construct a new
496 * alignment or import to an existing alignment
499 * @return AlignmentI instance ready to pass to a UI constructor
501 private AlignmentI buildAlignmentFrom(AlignFile alignFile2)
503 // Standard boilerplate for creating alignment from parser
504 // alignFile.configureForView(viewpanel);
506 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
508 alignFile.addAnnotations(al);
510 alignFile.addGroups(al);
516 * create an alignment flatfile from a Jalview alignment view
521 * @param selectedOnly
522 * @return flatfile in a string
524 public String formatSequences(String format, boolean jvsuffix,
525 AlignmentViewPanel ap, boolean selectedOnly)
528 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
529 selectedOnly, false);
530 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
532 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
533 .getVisibleAlignmentAnnotation(selectedOnly));
536 for (AlignmentAnnotation aa : ala)
538 aselview.addAnnotation(aa);
542 return formatSequences(format, aselview, jvsuffix);
546 * Construct an output class for an alignment in a particular filetype TODO:
547 * allow caller to detect errors and warnings encountered when generating
551 * string name of alignment format
553 * the alignment to be written out
555 * passed to AlnFile class controls whether /START-END is added to
558 * @return alignment flat file contents
560 public String formatSequences(String format, AlignmentI alignment,
565 AlignFile afile = null;
566 if (format.equalsIgnoreCase("FASTA"))
568 afile = new FastaFile();
570 else if (format.equalsIgnoreCase("MSF"))
572 afile = new MSFfile();
574 else if (format.equalsIgnoreCase("PileUp"))
576 afile = new PileUpfile();
578 else if (format.equalsIgnoreCase("CLUSTAL"))
580 afile = new ClustalFile();
582 else if (format.equalsIgnoreCase("BLC"))
584 afile = new BLCFile();
586 else if (format.equalsIgnoreCase("PIR"))
588 afile = new PIRFile();
590 else if (format.equalsIgnoreCase("PFAM"))
592 afile = new PfamFile();
594 else if (format.equalsIgnoreCase("STH"))
596 afile = new StockholmFile(alignment);
598 else if (format.equalsIgnoreCase("AMSA"))
600 afile = new AMSAFile(alignment);
602 else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
604 afile = new PhylipFile();
606 else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
608 afile = new JSONFile();
610 else if (format.equalsIgnoreCase("RNAML"))
612 afile = new RnamlFile();
614 else if (format.equalsIgnoreCase("MEGA"))
616 afile = new MegaFile();
622 .getString("error.implementation_error_unknown_file_format_string"));
625 afile.setNewlineString(newline);
626 afile.addJVSuffix(jvsuffix);
627 afile.setExportSettings(exportSettings);
628 afile.configureForView(viewpanel);
630 // check whether we were given a specific alignment to export, rather than
631 // the one in the viewpanel
632 if (viewpanel == null || viewpanel.getAlignment() == null
633 || viewpanel.getAlignment() != alignment)
635 afile.setSeqs(alignment.getSequencesArray());
639 // MC this is pointless? Only performed if viewpanel.getAlignment() ==
640 // alignment i.e. the same case as the if condition
641 afile.setSeqs(viewpanel.getAlignment().getSequencesArray());
644 String afileresp = afile.print(alignment);
645 if (afile.hasWarningMessage())
647 System.err.println("Warning raised when writing as " + format
648 + " : " + afile.getWarningMessage());
651 } catch (Exception e)
653 System.err.println("Failed to write alignment as a '" + format
661 public static String checkProtocol(String file)
663 String protocol = FILE;
664 String ft = file.toLowerCase().trim();
665 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
666 || ft.indexOf("file:") == 0)
673 public static void main(String[] args)
676 while (i < args.length)
678 File f = new File(args[i]);
683 System.out.println("Reading file: " + f);
684 AppletFormatAdapter afa = new AppletFormatAdapter();
685 Runtime r = Runtime.getRuntime();
687 long memf = -r.totalMemory() + r.freeMemory();
688 long t1 = -System.currentTimeMillis();
689 AlignmentI al = afa.readFile(args[i], FILE,
690 new IdentifyFile().Identify(args[i], FILE));
691 t1 += System.currentTimeMillis();
693 memf += r.totalMemory() - r.freeMemory();
696 System.out.println("Alignment contains " + al.getHeight()
697 + " sequences and " + al.getWidth() + " columns.");
700 System.out.println(new AppletFormatAdapter().formatSequences(
702 } catch (Exception e)
705 .println("Couln't format the alignment for output as a FASTA file.");
706 e.printStackTrace(System.err);
711 System.out.println("Couldn't read alignment");
713 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
715 .println("Difference between free memory now and before is "
716 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
717 } catch (Exception e)
719 System.err.println("Exception when dealing with " + i
720 + "'th argument: " + args[i] + "\n" + e);
725 System.err.println("Ignoring argument '" + args[i] + "' (" + i
726 + "'th)- not a readable file.");
733 * try to discover how to access the given file as a valid datasource that
734 * will be identified as the given type.
738 * @return protocol that yields the data parsable as the given type
740 public static String resolveProtocol(String file, String format)
742 return resolveProtocol(file, format, false);
745 public static String resolveProtocol(String file, String format,
748 // TODO: test thoroughly!
749 String protocol = null;
752 System.out.println("resolving datasource started with:\n>>file\n"
753 + file + ">>endfile");
756 // This might throw a security exception in certain browsers
757 // Netscape Communicator for instance.
761 InputStream is = System.getSecurityManager().getClass()
762 .getResourceAsStream("/" + file);
770 System.err.println("Resource '" + file + "' was "
771 + (rtn ? "" : "not") + " located by classloader.");
776 protocol = AppletFormatAdapter.CLASSLOADER;
779 } catch (Exception ex)
782 .println("Exception checking resources: " + file + " " + ex);
785 if (file.indexOf("://") > -1)
787 protocol = AppletFormatAdapter.URL;
791 // skipping codebase prepend check.
792 protocol = AppletFormatAdapter.FILE;
799 System.out.println("Trying to get contents of resource as "
802 fp = new FileParse(file, protocol);
811 System.out.println("Successful.");
814 } catch (Exception e)
818 System.err.println("Exception when accessing content: " + e);
826 System.out.println("Accessing as paste.");
828 protocol = AppletFormatAdapter.PASTE;
832 fp = new FileParse(file, protocol);
837 } catch (Exception e)
839 System.err.println("Failed to access content as paste!");
848 if (format == null || format.length() == 0)
856 String idformat = new jalview.io.IdentifyFile().Identify(file,
858 if (idformat == null)
862 System.out.println("Format not identified. Inaccessible file.");
868 System.out.println("Format identified as " + idformat
869 + "and expected as " + format);
871 if (idformat.equals(format))
875 System.out.println("Protocol identified as " + protocol);
884 .println("File deemed not accessible via " + protocol);
889 } catch (Exception e)
893 System.err.println("File deemed not accessible via " + protocol);
903 public AlignFile getAlignFile()
908 public void setAlignFile(AlignFile alignFile)
910 this.alignFile = alignFile;