2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
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/>.
21 import java.io.InputStream;
23 import jalview.datamodel.*;
26 * A low level class for alignment and feature IO with alignment formatting
27 * methods used by both applet and application for generating flat alignment
28 * files. It also holds the lists of magic format names that the applet and
29 * application will allow the user to read or write files with.
34 public class AppletFormatAdapter
37 * List of valid format strings used in the isValidFormat method
39 public static final String[] READABLE_FORMATS = new String[]
40 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
41 "PDB", "JnetFile" }; // , "SimpleBLAST" };
44 * List of valid format strings for use by callers of the formatSequences
47 public static final String[] WRITEABLE_FORMATS = new String[]
48 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA" };
51 * List of extensions corresponding to file format types in WRITABLE_FNAMES
52 * that are writable by the application.
54 public static final String[] WRITABLE_EXTENSIONS = new String[]
55 { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar" };
58 * List of writable formats by the application. Order must correspond with the
59 * WRITABLE_EXTENSIONS list of formats.
61 public static final String[] WRITABLE_FNAMES = new String[]
62 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview" };
65 * List of readable format file extensions by application in order
66 * corresponding to READABLE_FNAMES
68 public static final String[] READABLE_EXTENSIONS = new String[]
69 { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar",
76 * List of readable formats by application in order corresponding to
79 public static final String[] READABLE_FNAMES = new String[]
80 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
86 public static String INVALID_CHARACTERS = "Contains invalid characters";
88 // TODO: make these messages dynamic
89 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
90 + prettyPrint(READABLE_FORMATS);
95 * @return grammatically correct(ish) list consisting of els elements.
97 public static String prettyPrint(String[] els)
99 StringBuffer list = new StringBuffer();
100 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
105 list.append(" and " + els[els.length - 1] + ".");
106 return list.toString();
109 public static String FILE = "File";
111 public static String URL = "URL";
113 public static String PASTE = "Paste";
115 public static String CLASSLOADER = "ClassLoader";
117 AlignFile afile = null;
122 * check that this format is valid for reading
125 * a format string to be compared with READABLE_FORMATS
126 * @return true if format is readable
128 public static final boolean isValidFormat(String format)
130 return isValidFormat(format, false);
134 * validate format is valid for IO
137 * a format string to be compared with either READABLE_FORMATS or
140 * when true, format is checked for containment in WRITEABLE_FORMATS
141 * @return true if format is valid
143 public static final boolean isValidFormat(String format,
146 boolean valid = false;
147 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
149 for (int i = 0; i < format_list.length; i++)
151 if (format_list[i].equalsIgnoreCase(format))
161 * Constructs the correct filetype parser for a characterised datasource
168 * File format of data provided by datasource
170 * @return DOCUMENT ME!
172 public Alignment readFile(String inFile, String type, String format)
173 throws java.io.IOException
175 // TODO: generalise mapping between format string and io. class instances
176 // using Constructor.invoke reflection
177 this.inFile = inFile;
180 if (format.equals("FASTA"))
182 afile = new FastaFile(inFile, type);
184 else if (format.equals("MSF"))
186 afile = new MSFfile(inFile, type);
188 else if (format.equals("PileUp"))
190 afile = new PileUpfile(inFile, type);
192 else if (format.equals("CLUSTAL"))
194 afile = new ClustalFile(inFile, type);
196 else if (format.equals("BLC"))
198 afile = new BLCFile(inFile, type);
200 else if (format.equals("PIR"))
202 afile = new PIRFile(inFile, type);
204 else if (format.equals("PFAM"))
206 afile = new PfamFile(inFile, type);
208 else if (format.equals("JnetFile"))
210 afile = new JPredFile(inFile, type);
211 ((JPredFile) afile).removeNonSequences();
213 else if (format.equals("PDB"))
215 afile = new MCview.PDBfile(inFile, type);
217 else if (format.equals("STH"))
219 afile = new StockholmFile(inFile, type);
221 else if (format.equals("SimpleBLAST"))
223 afile = new SimpleBlastFile(inFile, type);
226 Alignment al = new Alignment(afile.getSeqsAsArray());
228 afile.addAnnotations(al);
231 } catch (Exception e)
234 System.err.println("Failed to read alignment using the '" + format
235 + "' reader.\n" + e);
237 if (e.getMessage() != null
238 && e.getMessage().startsWith(INVALID_CHARACTERS))
240 throw new java.io.IOException(e.getMessage());
243 // Finally test if the user has pasted just the sequence, no id
244 if (type.equalsIgnoreCase("Paste"))
248 // Possible sequence is just residues with no label
249 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
250 Alignment al = new Alignment(afile.getSeqsAsArray());
251 afile.addAnnotations(al);
254 } catch (Exception ex)
256 if (ex.toString().startsWith(INVALID_CHARACTERS))
258 throw new java.io.IOException(e.getMessage());
261 ex.printStackTrace();
265 // If we get to this stage, the format was not supported
266 throw new java.io.IOException(SUPPORTED_FORMATS);
271 * Constructs the correct filetype parser for an already open datasource
274 * an existing datasource
276 * File format of data that will be provided by datasource
278 * @return DOCUMENT ME!
280 public Alignment readFromFile(FileParse source, String format)
281 throws java.io.IOException
283 // TODO: generalise mapping between format string and io. class instances
284 // using Constructor.invoke reflection
285 // This is exactly the same as the readFile method except we substitute
286 // 'inFile, type' with 'source'
287 this.inFile = source.getInFile();
288 String type = source.type;
291 if (format.equals("FASTA"))
293 afile = new FastaFile(source);
295 else if (format.equals("MSF"))
297 afile = new MSFfile(source);
299 else if (format.equals("PileUp"))
301 afile = new PileUpfile(source);
303 else if (format.equals("CLUSTAL"))
305 afile = new ClustalFile(source);
307 else if (format.equals("BLC"))
309 afile = new BLCFile(source);
311 else if (format.equals("PIR"))
313 afile = new PIRFile(source);
315 else if (format.equals("PFAM"))
317 afile = new PfamFile(source);
319 else if (format.equals("JnetFile"))
321 afile = new JPredFile(source);
322 ((JPredFile) afile).removeNonSequences();
324 else if (format.equals("PDB"))
326 afile = new MCview.PDBfile(source);
328 else if (format.equals("STH"))
330 afile = new StockholmFile(source);
332 else if (format.equals("SimpleBLAST"))
334 afile = new SimpleBlastFile(source);
337 Alignment al = new Alignment(afile.getSeqsAsArray());
339 afile.addAnnotations(al);
342 } catch (Exception e)
345 System.err.println("Failed to read alignment using the '" + format
346 + "' reader.\n" + e);
348 if (e.getMessage() != null
349 && e.getMessage().startsWith(INVALID_CHARACTERS))
351 throw new java.io.IOException(e.getMessage());
354 // Finally test if the user has pasted just the sequence, no id
355 if (type.equalsIgnoreCase("Paste"))
359 // Possible sequence is just residues with no label
360 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
361 Alignment al = new Alignment(afile.getSeqsAsArray());
362 afile.addAnnotations(al);
365 } catch (Exception ex)
367 if (ex.toString().startsWith(INVALID_CHARACTERS))
369 throw new java.io.IOException(e.getMessage());
372 ex.printStackTrace();
376 // If we get to this stage, the format was not supported
377 throw new java.io.IOException(SUPPORTED_FORMATS);
382 * Construct an output class for an alignment in a particular filetype TODO:
383 * allow caller to detect errors and warnings encountered when generating
387 * string name of alignment format
389 * the alignment to be written out
391 * passed to AlnFile class controls whether /START-END is added to
394 * @return alignment flat file contents
396 public String formatSequences(String format, AlignmentI alignment,
401 AlignFile afile = null;
403 if (format.equalsIgnoreCase("FASTA"))
405 afile = new FastaFile();
407 else if (format.equalsIgnoreCase("MSF"))
409 afile = new MSFfile();
411 else if (format.equalsIgnoreCase("PileUp"))
413 afile = new PileUpfile();
415 else if (format.equalsIgnoreCase("CLUSTAL"))
417 afile = new ClustalFile();
419 else if (format.equalsIgnoreCase("BLC"))
421 afile = new BLCFile();
423 else if (format.equalsIgnoreCase("PIR"))
425 afile = new PIRFile();
427 else if (format.equalsIgnoreCase("PFAM"))
429 afile = new PfamFile();
431 else if (format.equalsIgnoreCase("STH"))
433 afile = new StockholmFile();
435 else if (format.equalsIgnoreCase("AMSA"))
437 afile = new AMSAFile(alignment);
442 "Implementation error: Unknown file format string");
445 afile.addJVSuffix(jvsuffix);
447 afile.setSeqs(alignment.getSequencesArray());
449 String afileresp = afile.print();
450 if (afile.hasWarningMessage())
452 System.err.println("Warning raised when writing as " + format
453 + " : " + afile.getWarningMessage());
456 } catch (Exception e)
458 System.err.println("Failed to write alignment as a '" + format
466 public static void main(String[] args)
469 while (i < args.length)
471 File f = new File(args[i]);
476 System.out.println("Reading file: " + f);
477 AppletFormatAdapter afa = new AppletFormatAdapter();
478 Runtime r = Runtime.getRuntime();
480 long memf = -r.totalMemory() + r.freeMemory();
481 long t1 = -System.currentTimeMillis();
482 Alignment al = afa.readFile(args[i], FILE,
483 new IdentifyFile().Identify(args[i], FILE));
484 t1 += System.currentTimeMillis();
486 memf += r.totalMemory() - r.freeMemory();
489 System.out.println("Alignment contains " + al.getHeight()
490 + " sequences and " + al.getWidth() + " columns.");
493 System.out.println(new AppletFormatAdapter().formatSequences(
495 } catch (Exception e)
498 .println("Couln't format the alignment for output as a FASTA file.");
499 e.printStackTrace(System.err);
504 System.out.println("Couldn't read alignment");
506 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
508 .println("Difference between free memory now and before is "
509 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
511 } catch (Exception e)
513 System.err.println("Exception when dealing with " + i
514 + "'th argument: " + args[i] + "\n" + e);
519 System.err.println("Ignoring argument '" + args[i] + "' (" + i
520 + "'th)- not a readable file.");
527 * try to discover how to access the given file as a valid datasource that
528 * will be identified as the given type.
532 * @return protocol that yields the data parsable as the given type
534 public static String resolveProtocol(String file, String format)
536 return resolveProtocol(file, format, false);
539 public static String resolveProtocol(String file, String format,
542 // TODO: test thoroughly!
543 String protocol = null;
546 System.out.println("resolving datasource started with:\n>>file\n"
547 + file + ">>endfile");
550 // This might throw a security exception in certain browsers
551 // Netscape Communicator for instance.
555 InputStream is = System.getSecurityManager().getClass()
556 .getResourceAsStream("/" + file);
564 System.err.println("Resource '" + file + "' was "
565 + (rtn ? "" : "not") + " located by classloader.");
570 protocol = AppletFormatAdapter.CLASSLOADER;
573 } catch (Exception ex)
576 .println("Exception checking resources: " + file + " " + ex);
579 if (file.indexOf("://") > -1)
581 protocol = AppletFormatAdapter.URL;
585 // skipping codebase prepend check.
586 protocol = AppletFormatAdapter.FILE;
593 System.out.println("Trying to get contents of resource as "
596 fp = new FileParse(file, protocol);
605 System.out.println("Successful.");
608 } catch (Exception e)
612 System.err.println("Exception when accessing content: " + e);
620 System.out.println("Accessing as paste.");
622 protocol = AppletFormatAdapter.PASTE;
626 fp = new FileParse(file, protocol);
631 } catch (Exception e)
633 System.err.println("Failed to access content as paste!");
642 if (format == null || format.length() == 0)
650 String idformat = new jalview.io.IdentifyFile().Identify(file,
652 if (idformat == null)
656 System.out.println("Format not identified. Inaccessible file.");
662 System.out.println("Format identified as " + idformat
663 + "and expected as " + format);
665 if (idformat.equals(format))
669 System.out.println("Protocol identified as " + protocol);
678 .println("File deemed not accessible via " + protocol);
683 } catch (Exception e)
687 System.err.println("File deemed not accessible via " + protocol);