2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
22 import java.io.InputStream;
24 import jalview.datamodel.*;
27 * A low level class for alignment and feature IO with alignment formatting
28 * methods used by both applet and application for generating flat alignment
29 * files. It also holds the lists of magic format names that the applet and
30 * application will allow the user to read or write files with.
35 public class AppletFormatAdapter
38 * List of valid format strings used in the isValidFormat method
40 public static final String[] READABLE_FORMATS = new String[]
41 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
42 "PDB", "JnetFile" , "RNAML"}; // , "SimpleBLAST" };
45 * List of valid format strings for use by callers of the formatSequences
48 public static final String[] WRITEABLE_FORMATS = new String[]
49 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA" };
52 * List of extensions corresponding to file format types in WRITABLE_FNAMES
53 * that are writable by the application.
55 public static final String[] WRITABLE_EXTENSIONS = new String[]
56 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar",
60 * List of writable formats by the application. Order must correspond with the
61 * WRITABLE_EXTENSIONS list of formats.
63 public static final String[] WRITABLE_FNAMES = new String[]
64 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
68 * List of readable format file extensions by application in order
69 * corresponding to READABLE_FNAMES
71 public static final String[] READABLE_EXTENSIONS = new String[]
72 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar",
73 "sto,stk","xml,rnaml" }; // ".blast"
77 * List of readable formats by application in order corresponding to
80 public static final String[] READABLE_FNAMES = new String[]
81 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
82 "Stockholm","RNAML" };// ,
87 public static String INVALID_CHARACTERS = "Contains invalid characters";
89 // TODO: make these messages dynamic
90 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
91 + prettyPrint(READABLE_FORMATS);
96 * @return grammatically correct(ish) list consisting of els elements.
98 public static String prettyPrint(String[] els)
100 StringBuffer list = new StringBuffer();
101 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
106 list.append(" and " + els[els.length - 1] + ".");
107 return list.toString();
110 public static String FILE = "File";
112 public static String URL = "URL";
114 public static String PASTE = "Paste";
116 public static String CLASSLOADER = "ClassLoader";
118 AlignFile afile = null;
123 * character used to write newlines
125 protected String newline = System.getProperty("line.separator");
127 public void setNewlineString(String nl)
132 public String getNewlineString()
138 * check that this format is valid for reading
141 * a format string to be compared with READABLE_FORMATS
142 * @return true if format is readable
144 public static final boolean isValidFormat(String format)
146 return isValidFormat(format, false);
150 * validate format is valid for IO
153 * a format string to be compared with either READABLE_FORMATS or
156 * when true, format is checked for containment in WRITEABLE_FORMATS
157 * @return true if format is valid
159 public static final boolean isValidFormat(String format,
162 boolean valid = false;
163 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
165 for (int i = 0; i < format_list.length; i++)
167 if (format_list[i].equalsIgnoreCase(format))
177 * Constructs the correct filetype parser for a characterised datasource
184 * File format of data provided by datasource
186 * @return DOCUMENT ME!
188 public Alignment readFile(String inFile, String type, String format)
189 throws java.io.IOException
191 // TODO: generalise mapping between format string and io. class instances
192 // using Constructor.invoke reflection
193 this.inFile = inFile;
196 if (format.equals("FASTA"))
198 afile = new FastaFile(inFile, type);
200 else if (format.equals("MSF"))
202 afile = new MSFfile(inFile, type);
204 else if (format.equals("PileUp"))
206 afile = new PileUpfile(inFile, type);
208 else if (format.equals("CLUSTAL"))
210 afile = new ClustalFile(inFile, type);
212 else if (format.equals("BLC"))
214 afile = new BLCFile(inFile, type);
216 else if (format.equals("PIR"))
218 afile = new PIRFile(inFile, type);
220 else if (format.equals("PFAM"))
222 afile = new PfamFile(inFile, type);
224 else if (format.equals("JnetFile"))
226 afile = new JPredFile(inFile, type);
227 ((JPredFile) afile).removeNonSequences();
229 else if (format.equals("PDB"))
231 afile = new MCview.PDBfile(inFile, type);
232 // Uncomment to test Jmol data based PDB processing: JAL-1213
233 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
235 else if (format.equals("STH"))
237 afile = new StockholmFile(inFile, type);
239 else if (format.equals("SimpleBLAST"))
241 afile = new SimpleBlastFile(inFile, type);
243 else if (format.equals("RNAML"))
245 afile = new RnamlFile(inFile, type);
248 Alignment al = new Alignment(afile.getSeqsAsArray());
250 afile.addAnnotations(al);
253 } catch (Exception e)
256 System.err.println("Failed to read alignment using the '" + format
257 + "' reader.\n" + e);
259 if (e.getMessage() != null
260 && e.getMessage().startsWith(INVALID_CHARACTERS))
262 throw new java.io.IOException(e.getMessage());
265 // Finally test if the user has pasted just the sequence, no id
266 if (type.equalsIgnoreCase("Paste"))
270 // Possible sequence is just residues with no label
271 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
272 Alignment al = new Alignment(afile.getSeqsAsArray());
273 afile.addAnnotations(al);
276 } catch (Exception ex)
278 if (ex.toString().startsWith(INVALID_CHARACTERS))
280 throw new java.io.IOException(e.getMessage());
283 ex.printStackTrace();
287 // If we get to this stage, the format was not supported
288 throw new java.io.IOException(SUPPORTED_FORMATS);
293 * Constructs the correct filetype parser for an already open datasource
296 * an existing datasource
298 * File format of data that will be provided by datasource
300 * @return DOCUMENT ME!
302 public AlignmentI readFromFile(FileParse source, String format)
303 throws java.io.IOException
305 // TODO: generalise mapping between format string and io. class instances
306 // using Constructor.invoke reflection
307 // This is exactly the same as the readFile method except we substitute
308 // 'inFile, type' with 'source'
309 this.inFile = source.getInFile();
310 String type = source.type;
313 if (format.equals("FASTA"))
315 afile = new FastaFile(source);
317 else if (format.equals("MSF"))
319 afile = new MSFfile(source);
321 else if (format.equals("PileUp"))
323 afile = new PileUpfile(source);
325 else if (format.equals("CLUSTAL"))
327 afile = new ClustalFile(source);
329 else if (format.equals("BLC"))
331 afile = new BLCFile(source);
333 else if (format.equals("PIR"))
335 afile = new PIRFile(source);
337 else if (format.equals("PFAM"))
339 afile = new PfamFile(source);
341 else if (format.equals("JnetFile"))
343 afile = new JPredFile(source);
344 ((JPredFile) afile).removeNonSequences();
346 else if (format.equals("PDB"))
348 afile = new MCview.PDBfile(source);
350 else if (format.equals("STH"))
352 afile = new StockholmFile(source);
354 else if (format.equals("RNAML"))
356 afile = new RnamlFile(source);
358 else if (format.equals("SimpleBLAST"))
360 afile = new SimpleBlastFile(source);
363 Alignment al = new Alignment(afile.getSeqsAsArray());
365 afile.addAnnotations(al);
368 } catch (Exception e)
371 System.err.println("Failed to read alignment using the '" + format
372 + "' reader.\n" + e);
374 if (e.getMessage() != null
375 && e.getMessage().startsWith(INVALID_CHARACTERS))
377 throw new java.io.IOException(e.getMessage());
380 // Finally test if the user has pasted just the sequence, no id
381 if (type.equalsIgnoreCase("Paste"))
385 // Possible sequence is just residues with no label
386 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
387 Alignment al = new Alignment(afile.getSeqsAsArray());
388 afile.addAnnotations(al);
391 } catch (Exception ex)
393 if (ex.toString().startsWith(INVALID_CHARACTERS))
395 throw new java.io.IOException(e.getMessage());
398 ex.printStackTrace();
402 // If we get to this stage, the format was not supported
403 throw new java.io.IOException(SUPPORTED_FORMATS);
408 * Construct an output class for an alignment in a particular filetype TODO:
409 * allow caller to detect errors and warnings encountered when generating
413 * string name of alignment format
415 * the alignment to be written out
417 * passed to AlnFile class controls whether /START-END is added to
420 * @return alignment flat file contents
422 public String formatSequences(String format, AlignmentI alignment,
427 AlignFile afile = null;
429 if (format.equalsIgnoreCase("FASTA"))
431 afile = new FastaFile();
433 else if (format.equalsIgnoreCase("MSF"))
435 afile = new MSFfile();
437 else if (format.equalsIgnoreCase("PileUp"))
439 afile = new PileUpfile();
441 else if (format.equalsIgnoreCase("CLUSTAL"))
443 afile = new ClustalFile();
445 else if (format.equalsIgnoreCase("BLC"))
447 afile = new BLCFile();
449 else if (format.equalsIgnoreCase("PIR"))
451 afile = new PIRFile();
453 else if (format.equalsIgnoreCase("PFAM"))
455 afile = new PfamFile();
457 else if (format.equalsIgnoreCase("STH"))
459 afile = new StockholmFile(alignment);
461 else if (format.equalsIgnoreCase("AMSA"))
463 afile = new AMSAFile(alignment);
465 else if (format.equalsIgnoreCase("RNAML"))
467 afile = new RnamlFile();
473 "Implementation error: Unknown file format string");
475 afile.setNewlineString(newline);
476 afile.addJVSuffix(jvsuffix);
478 afile.setSeqs(alignment.getSequencesArray());
480 String afileresp = afile.print();
481 if (afile.hasWarningMessage())
483 System.err.println("Warning raised when writing as " + format
484 + " : " + afile.getWarningMessage());
487 } catch (Exception e)
489 System.err.println("Failed to write alignment as a '" + format
497 public static String checkProtocol(String file)
499 String protocol = FILE;
500 String ft = file.toLowerCase().trim();
501 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
502 || ft.indexOf("file:") == 0)
509 public static void main(String[] args)
512 while (i < args.length)
514 File f = new File(args[i]);
519 System.out.println("Reading file: " + f);
520 AppletFormatAdapter afa = new AppletFormatAdapter();
521 Runtime r = Runtime.getRuntime();
523 long memf = -r.totalMemory() + r.freeMemory();
524 long t1 = -System.currentTimeMillis();
525 Alignment al = afa.readFile(args[i], FILE,
526 new IdentifyFile().Identify(args[i], FILE));
527 t1 += System.currentTimeMillis();
529 memf += r.totalMemory() - r.freeMemory();
532 System.out.println("Alignment contains " + al.getHeight()
533 + " sequences and " + al.getWidth() + " columns.");
536 System.out.println(new AppletFormatAdapter().formatSequences(
538 } catch (Exception e)
541 .println("Couln't format the alignment for output as a FASTA file.");
542 e.printStackTrace(System.err);
547 System.out.println("Couldn't read alignment");
549 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
551 .println("Difference between free memory now and before is "
552 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
553 } catch (Exception e)
555 System.err.println("Exception when dealing with " + i
556 + "'th argument: " + args[i] + "\n" + e);
561 System.err.println("Ignoring argument '" + args[i] + "' (" + i
562 + "'th)- not a readable file.");
569 * try to discover how to access the given file as a valid datasource that
570 * will be identified as the given type.
574 * @return protocol that yields the data parsable as the given type
576 public static String resolveProtocol(String file, String format)
578 return resolveProtocol(file, format, false);
581 public static String resolveProtocol(String file, String format,
584 // TODO: test thoroughly!
585 String protocol = null;
588 System.out.println("resolving datasource started with:\n>>file\n"
589 + file + ">>endfile");
592 // This might throw a security exception in certain browsers
593 // Netscape Communicator for instance.
597 InputStream is = System.getSecurityManager().getClass()
598 .getResourceAsStream("/" + file);
606 System.err.println("Resource '" + file + "' was "
607 + (rtn ? "" : "not") + " located by classloader.");
612 protocol = AppletFormatAdapter.CLASSLOADER;
615 } catch (Exception ex)
618 .println("Exception checking resources: " + file + " " + ex);
621 if (file.indexOf("://") > -1)
623 protocol = AppletFormatAdapter.URL;
627 // skipping codebase prepend check.
628 protocol = AppletFormatAdapter.FILE;
635 System.out.println("Trying to get contents of resource as "
638 fp = new FileParse(file, protocol);
647 System.out.println("Successful.");
650 } catch (Exception e)
654 System.err.println("Exception when accessing content: " + e);
662 System.out.println("Accessing as paste.");
664 protocol = AppletFormatAdapter.PASTE;
668 fp = new FileParse(file, protocol);
673 } catch (Exception e)
675 System.err.println("Failed to access content as paste!");
684 if (format == null || format.length() == 0)
692 String idformat = new jalview.io.IdentifyFile().Identify(file,
694 if (idformat == null)
698 System.out.println("Format not identified. Inaccessible file.");
704 System.out.println("Format identified as " + idformat
705 + "and expected as " + format);
707 if (idformat.equals(format))
711 System.out.println("Protocol identified as " + protocol);
720 .println("File deemed not accessible via " + protocol);
725 } catch (Exception e)
729 System.err.println("File deemed not accessible via " + protocol);