2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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.
24 import java.io.InputStream;
25 import java.util.List;
27 import jalview.api.AlignViewportI;
28 import jalview.datamodel.*;
31 * A low level class for alignment and feature IO with alignment formatting
32 * methods used by both applet and application for generating flat alignment
33 * files. It also holds the lists of magic format names that the applet and
34 * application will allow the user to read or write files with.
39 public class AppletFormatAdapter
42 * List of valid format strings used in the isValidFormat method
44 public static final String[] READABLE_FORMATS = new String[]
45 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
46 "PDB", "JnetFile", "RNAML" }; // , "SimpleBLAST" };
49 * List of valid format strings for use by callers of the formatSequences
52 public static final String[] WRITEABLE_FORMATS = new String[]
53 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA", "STH" };
56 * List of extensions corresponding to file format types in WRITABLE_FNAMES
57 * that are writable by the application.
59 public static final String[] WRITABLE_EXTENSIONS = new String[]
60 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
61 "jvp", "sto,stk", "jar" };
64 * List of writable formats by the application. Order must correspond with the
65 * WRITABLE_EXTENSIONS list of formats.
67 public static final String[] WRITABLE_FNAMES = new String[]
68 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
72 * List of readable format file extensions by application in order
73 * corresponding to READABLE_FNAMES
75 public static final String[] READABLE_EXTENSIONS = new String[]
76 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
77 "jar,jvp", "sto,stk", "xml,rnaml" }; // ".blast"
80 * List of readable formats by application in order corresponding to
83 public static final String[] READABLE_FNAMES = new String[]
84 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
85 "Stockholm", "RNAML" };// ,
90 public static String INVALID_CHARACTERS = "Contains invalid characters";
92 // TODO: make these messages dynamic
93 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
94 + prettyPrint(READABLE_FORMATS);
99 * @return grammatically correct(ish) list consisting of els elements.
101 public static String prettyPrint(String[] els)
103 StringBuffer list = new StringBuffer();
104 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
109 list.append(" and " + els[els.length - 1] + ".");
110 return list.toString();
113 public static String FILE = "File";
115 public static String URL = "URL";
117 public static String PASTE = "Paste";
119 public static String CLASSLOADER = "ClassLoader";
121 AlignFile afile = null;
126 * character used to write newlines
128 protected String newline = System.getProperty("line.separator");
130 public void setNewlineString(String nl)
135 public String getNewlineString()
141 * check that this format is valid for reading
144 * a format string to be compared with READABLE_FORMATS
145 * @return true if format is readable
147 public static final boolean isValidFormat(String format)
149 return isValidFormat(format, false);
153 * validate format is valid for IO
156 * a format string to be compared with either READABLE_FORMATS or
159 * when true, format is checked for containment in WRITEABLE_FORMATS
160 * @return true if format is valid
162 public static final boolean isValidFormat(String format,
165 boolean valid = false;
166 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
168 for (int i = 0; i < format_list.length; i++)
170 if (format_list[i].equalsIgnoreCase(format))
180 * Constructs the correct filetype parser for a characterised datasource
187 * File format of data provided by datasource
189 * @return DOCUMENT ME!
191 public Alignment readFile(String inFile, String type, String format)
192 throws java.io.IOException
194 // TODO: generalise mapping between format string and io. class instances
195 // using Constructor.invoke reflection
196 this.inFile = inFile;
199 if (format.equals("FASTA"))
201 afile = new FastaFile(inFile, type);
203 else if (format.equals("MSF"))
205 afile = new MSFfile(inFile, type);
207 else if (format.equals("PileUp"))
209 afile = new PileUpfile(inFile, type);
211 else if (format.equals("CLUSTAL"))
213 afile = new ClustalFile(inFile, type);
215 else if (format.equals("BLC"))
217 afile = new BLCFile(inFile, type);
219 else if (format.equals("PIR"))
221 afile = new PIRFile(inFile, type);
223 else if (format.equals("PFAM"))
225 afile = new PfamFile(inFile, type);
227 else if (format.equals("JnetFile"))
229 afile = new JPredFile(inFile, type);
230 ((JPredFile) afile).removeNonSequences();
232 else if (format.equals("PDB"))
234 afile = new MCview.PDBfile(inFile, type);
235 // Uncomment to test Jmol data based PDB processing: JAL-1213
236 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
238 else if (format.equals("STH"))
240 afile = new StockholmFile(inFile, type);
242 else if (format.equals("SimpleBLAST"))
244 afile = new SimpleBlastFile(inFile, type);
246 else if (format.equals("RNAML"))
248 afile = new RnamlFile(inFile, type);
251 Alignment al = new Alignment(afile.getSeqsAsArray());
253 afile.addAnnotations(al);
256 } catch (Exception e)
259 System.err.println("Failed to read alignment using the '" + format
260 + "' reader.\n" + e);
262 if (e.getMessage() != null
263 && e.getMessage().startsWith(INVALID_CHARACTERS))
265 throw new java.io.IOException(e.getMessage());
268 // Finally test if the user has pasted just the sequence, no id
269 if (type.equalsIgnoreCase("Paste"))
273 // Possible sequence is just residues with no label
274 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
275 Alignment al = new Alignment(afile.getSeqsAsArray());
276 afile.addAnnotations(al);
279 } catch (Exception ex)
281 if (ex.toString().startsWith(INVALID_CHARACTERS))
283 throw new java.io.IOException(e.getMessage());
286 ex.printStackTrace();
290 // If we get to this stage, the format was not supported
291 throw new java.io.IOException(SUPPORTED_FORMATS);
296 * Constructs the correct filetype parser for an already open datasource
299 * an existing datasource
301 * File format of data that will be provided by datasource
303 * @return DOCUMENT ME!
305 public AlignmentI readFromFile(FileParse source, String format)
306 throws java.io.IOException
308 // TODO: generalise mapping between format string and io. class instances
309 // using Constructor.invoke reflection
310 // This is exactly the same as the readFile method except we substitute
311 // 'inFile, type' with 'source'
312 this.inFile = source.getInFile();
313 String type = source.type;
316 if (format.equals("FASTA"))
318 afile = new FastaFile(source);
320 else if (format.equals("MSF"))
322 afile = new MSFfile(source);
324 else if (format.equals("PileUp"))
326 afile = new PileUpfile(source);
328 else if (format.equals("CLUSTAL"))
330 afile = new ClustalFile(source);
332 else if (format.equals("BLC"))
334 afile = new BLCFile(source);
336 else if (format.equals("PIR"))
338 afile = new PIRFile(source);
340 else if (format.equals("PFAM"))
342 afile = new PfamFile(source);
344 else if (format.equals("JnetFile"))
346 afile = new JPredFile(source);
347 ((JPredFile) afile).removeNonSequences();
349 else if (format.equals("PDB"))
351 afile = new MCview.PDBfile(source);
353 else if (format.equals("STH"))
355 afile = new StockholmFile(source);
357 else if (format.equals("RNAML"))
359 afile = new RnamlFile(source);
361 else if (format.equals("SimpleBLAST"))
363 afile = new SimpleBlastFile(source);
366 Alignment al = new Alignment(afile.getSeqsAsArray());
368 afile.addAnnotations(al);
371 } catch (Exception e)
374 System.err.println("Failed to read alignment using the '" + format
375 + "' reader.\n" + e);
377 if (e.getMessage() != null
378 && e.getMessage().startsWith(INVALID_CHARACTERS))
380 throw new java.io.IOException(e.getMessage());
383 // Finally test if the user has pasted just the sequence, no id
384 if (type.equalsIgnoreCase("Paste"))
388 // Possible sequence is just residues with no label
389 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
390 Alignment al = new Alignment(afile.getSeqsAsArray());
391 afile.addAnnotations(al);
394 } catch (Exception ex)
396 if (ex.toString().startsWith(INVALID_CHARACTERS))
398 throw new java.io.IOException(e.getMessage());
401 ex.printStackTrace();
405 // If we get to this stage, the format was not supported
406 throw new java.io.IOException(SUPPORTED_FORMATS);
412 * create an alignment flatfile from a Jalview alignment view
416 * @param selectedOnly
417 * @return flatfile in a string
419 public String formatSequences(String format, boolean jvsuffix,
420 AlignViewportI av, boolean selectedOnly)
423 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
424 AlignmentI aselview = selvew.getVisibleAlignment(av
426 List<AlignmentAnnotation> ala = (av
427 .getVisibleAlignmentAnnotation(selectedOnly));
430 for (AlignmentAnnotation aa : ala)
432 aselview.addAnnotation(aa);
436 return formatSequences(format, aselview, jvsuffix);
440 * Construct an output class for an alignment in a particular filetype TODO:
441 * allow caller to detect errors and warnings encountered when generating
445 * string name of alignment format
447 * the alignment to be written out
449 * passed to AlnFile class controls whether /START-END is added to
452 * @return alignment flat file contents
454 public String formatSequences(String format, AlignmentI alignment,
459 AlignFile afile = null;
461 if (format.equalsIgnoreCase("FASTA"))
463 afile = new FastaFile();
465 else if (format.equalsIgnoreCase("MSF"))
467 afile = new MSFfile();
469 else if (format.equalsIgnoreCase("PileUp"))
471 afile = new PileUpfile();
473 else if (format.equalsIgnoreCase("CLUSTAL"))
475 afile = new ClustalFile();
477 else if (format.equalsIgnoreCase("BLC"))
479 afile = new BLCFile();
481 else if (format.equalsIgnoreCase("PIR"))
483 afile = new PIRFile();
485 else if (format.equalsIgnoreCase("PFAM"))
487 afile = new PfamFile();
489 else if (format.equalsIgnoreCase("STH"))
491 afile = new StockholmFile(alignment);
493 else if (format.equalsIgnoreCase("AMSA"))
495 afile = new AMSAFile(alignment);
497 else if (format.equalsIgnoreCase("RNAML"))
499 afile = new RnamlFile();
505 "Implementation error: Unknown file format string");
507 afile.setNewlineString(newline);
508 afile.addJVSuffix(jvsuffix);
510 afile.setSeqs(alignment.getSequencesArray());
512 String afileresp = afile.print();
513 if (afile.hasWarningMessage())
515 System.err.println("Warning raised when writing as " + format
516 + " : " + afile.getWarningMessage());
519 } catch (Exception e)
521 System.err.println("Failed to write alignment as a '" + format
529 public static String checkProtocol(String file)
531 String protocol = FILE;
532 String ft = file.toLowerCase().trim();
533 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
534 || ft.indexOf("file:") == 0)
541 public static void main(String[] args)
544 while (i < args.length)
546 File f = new File(args[i]);
551 System.out.println("Reading file: " + f);
552 AppletFormatAdapter afa = new AppletFormatAdapter();
553 Runtime r = Runtime.getRuntime();
555 long memf = -r.totalMemory() + r.freeMemory();
556 long t1 = -System.currentTimeMillis();
557 Alignment al = afa.readFile(args[i], FILE,
558 new IdentifyFile().Identify(args[i], FILE));
559 t1 += System.currentTimeMillis();
561 memf += r.totalMemory() - r.freeMemory();
564 System.out.println("Alignment contains " + al.getHeight()
565 + " sequences and " + al.getWidth() + " columns.");
568 System.out.println(new AppletFormatAdapter().formatSequences(
570 } catch (Exception e)
573 .println("Couln't format the alignment for output as a FASTA file.");
574 e.printStackTrace(System.err);
579 System.out.println("Couldn't read alignment");
581 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
583 .println("Difference between free memory now and before is "
584 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
585 } catch (Exception e)
587 System.err.println("Exception when dealing with " + i
588 + "'th argument: " + args[i] + "\n" + e);
593 System.err.println("Ignoring argument '" + args[i] + "' (" + i
594 + "'th)- not a readable file.");
601 * try to discover how to access the given file as a valid datasource that
602 * will be identified as the given type.
606 * @return protocol that yields the data parsable as the given type
608 public static String resolveProtocol(String file, String format)
610 return resolveProtocol(file, format, false);
613 public static String resolveProtocol(String file, String format,
616 // TODO: test thoroughly!
617 String protocol = null;
620 System.out.println("resolving datasource started with:\n>>file\n"
621 + file + ">>endfile");
624 // This might throw a security exception in certain browsers
625 // Netscape Communicator for instance.
629 InputStream is = System.getSecurityManager().getClass()
630 .getResourceAsStream("/" + file);
638 System.err.println("Resource '" + file + "' was "
639 + (rtn ? "" : "not") + " located by classloader.");
644 protocol = AppletFormatAdapter.CLASSLOADER;
647 } catch (Exception ex)
650 .println("Exception checking resources: " + file + " " + ex);
653 if (file.indexOf("://") > -1)
655 protocol = AppletFormatAdapter.URL;
659 // skipping codebase prepend check.
660 protocol = AppletFormatAdapter.FILE;
667 System.out.println("Trying to get contents of resource as "
670 fp = new FileParse(file, protocol);
679 System.out.println("Successful.");
682 } catch (Exception e)
686 System.err.println("Exception when accessing content: " + e);
694 System.out.println("Accessing as paste.");
696 protocol = AppletFormatAdapter.PASTE;
700 fp = new FileParse(file, protocol);
705 } catch (Exception e)
707 System.err.println("Failed to access content as paste!");
716 if (format == null || format.length() == 0)
724 String idformat = new jalview.io.IdentifyFile().Identify(file,
726 if (idformat == null)
730 System.out.println("Format not identified. Inaccessible file.");
736 System.out.println("Format identified as " + idformat
737 + "and expected as " + format);
739 if (idformat.equals(format))
743 System.out.println("Protocol identified as " + protocol);
752 .println("File deemed not accessible via " + protocol);
757 } catch (Exception e)
761 System.err.println("File deemed not accessible via " + protocol);