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;
26 import jalview.datamodel.*;
29 * A low level class for alignment and feature IO with alignment formatting
30 * methods used by both applet and application for generating flat alignment
31 * files. It also holds the lists of magic format names that the applet and
32 * application will allow the user to read or write files with.
37 public class AppletFormatAdapter
40 * List of valid format strings used in the isValidFormat method
42 public static final String[] READABLE_FORMATS = new String[]
43 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
44 "PDB", "JnetFile", "RNAML", "GENBANK" };
47 * List of valid format strings for use by callers of the formatSequences
50 public static final String[] WRITEABLE_FORMATS = new String[]
51 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA" };
54 * List of extensions corresponding to file format types in WRITABLE_FNAMES
55 * that are writable by the application.
57 public static final String[] WRITABLE_EXTENSIONS = new String[]
58 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
59 "jvp", "sto,stk", "jar" };
62 * List of writable formats by the application. Order must correspond with the
63 * WRITABLE_EXTENSIONS list of formats.
65 public static final String[] WRITABLE_FNAMES = new String[]
66 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
70 * List of readable format file extensions by application in order
71 * corresponding to READABLE_FNAMES
73 public static final String[] READABLE_EXTENSIONS = new String[]
74 { "fa,faa,fasta,mfa,fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
75 "jar,jvp", "sto,stk", "xml,rnaml", "gb" }; // ".blast"
78 * List of readable formats by application in order corresponding to
81 public static final String[] READABLE_FNAMES = new String[]
82 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
83 "Stockholm", "RNAML", "GenBank" };
88 public static String INVALID_CHARACTERS = "Contains invalid characters";
90 // TODO: make these messages dynamic
91 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
92 + prettyPrint(READABLE_FORMATS);
97 * @return grammatically correct(ish) list consisting of els elements.
99 public static String prettyPrint(String[] els)
101 StringBuffer list = new StringBuffer();
102 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
107 list.append(" and " + els[els.length - 1] + ".");
108 return list.toString();
111 public static String FILE = "File";
113 public static String URL = "URL";
115 public static String PASTE = "Paste";
117 public static String CLASSLOADER = "ClassLoader";
119 AlignFile afile = null;
124 * character used to write newlines
126 protected String newline = System.getProperty("line.separator");
128 public void setNewlineString(String nl)
133 public String getNewlineString()
139 * check that this format is valid for reading
142 * a format string to be compared with READABLE_FORMATS
143 * @return true if format is readable
145 public static final boolean isValidFormat(String format)
147 return isValidFormat(format, false);
151 * validate format is valid for IO
154 * a format string to be compared with either READABLE_FORMATS or
157 * when true, format is checked for containment in WRITEABLE_FORMATS
158 * @return true if format is valid
160 public static final boolean isValidFormat(String format,
163 boolean valid = false;
164 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
166 for (int i = 0; i < format_list.length; i++)
168 if (format_list[i].equalsIgnoreCase(format))
178 * Constructs the correct filetype parser for a characterised datasource
185 * File format of data provided by datasource
187 * @return DOCUMENT ME!
189 public Alignment readFile(String inFile, String type, String format)
190 throws java.io.IOException
192 // TODO: generalise mapping between format string and io. class instances
193 // using Constructor.invoke reflection
194 this.inFile = inFile;
197 if (format.equals("FASTA"))
199 afile = new FastaFile(inFile, type);
201 else if (format.equals("MSF"))
203 afile = new MSFfile(inFile, type);
205 else if (format.equals("PileUp"))
207 afile = new PileUpfile(inFile, type);
209 else if (format.equals("CLUSTAL"))
211 afile = new ClustalFile(inFile, type);
213 else if (format.equals("BLC"))
215 afile = new BLCFile(inFile, type);
217 else if (format.equals("PIR"))
219 afile = new PIRFile(inFile, type);
221 else if (format.equals("PFAM"))
223 afile = new PfamFile(inFile, type);
225 else if (format.equals("JnetFile"))
227 afile = new JPredFile(inFile, type);
228 ((JPredFile) afile).removeNonSequences();
230 else if (format.equals("PDB"))
232 afile = new MCview.PDBfile(inFile, type);
233 // Uncomment to test Jmol data based PDB processing: JAL-1213
234 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
236 else if (format.equals("STH"))
238 afile = new StockholmFile(inFile, type);
240 else if (format.equals("SimpleBLAST"))
242 afile = new SimpleBlastFile(inFile, type);
244 else if (format.equals("RNAML"))
246 afile = new RnamlFile(inFile, type);
248 else if (format.equals("GENBANK"))
250 afile = new GenBankFile(inFile, type);
252 Alignment al = new Alignment(afile.getSeqsAsArray());
254 afile.addAnnotations(al);
257 } catch (Exception e)
260 System.err.println("Failed to read alignment using the '" + format
261 + "' reader.\n" + e);
263 if (e.getMessage() != null
264 && e.getMessage().startsWith(INVALID_CHARACTERS))
266 throw new java.io.IOException(e.getMessage());
269 // Finally test if the user has pasted just the sequence, no id
270 if (type.equalsIgnoreCase("Paste"))
274 // Possible sequence is just residues with no label
275 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
276 Alignment al = new Alignment(afile.getSeqsAsArray());
277 afile.addAnnotations(al);
280 } catch (Exception ex)
282 if (ex.toString().startsWith(INVALID_CHARACTERS))
284 throw new java.io.IOException(e.getMessage());
287 ex.printStackTrace();
291 // If we get to this stage, the format was not supported
292 throw new java.io.IOException(SUPPORTED_FORMATS);
297 * Constructs the correct filetype parser for an already open datasource
300 * an existing datasource
302 * File format of data that will be provided by datasource
304 * @return DOCUMENT ME!
306 public AlignmentI readFromFile(FileParse source, String format)
307 throws java.io.IOException
309 // TODO: generalise mapping between format string and io. class instances
310 // using Constructor.invoke reflection
311 // This is exactly the same as the readFile method except we substitute
312 // 'inFile, type' with 'source'
313 this.inFile = source.getInFile();
314 String type = source.type;
317 if (format.equals("FASTA"))
319 afile = new FastaFile(source);
321 else if (format.equals("MSF"))
323 afile = new MSFfile(source);
325 else if (format.equals("PileUp"))
327 afile = new PileUpfile(source);
329 else if (format.equals("CLUSTAL"))
331 afile = new ClustalFile(source);
333 else if (format.equals("BLC"))
335 afile = new BLCFile(source);
337 else if (format.equals("PIR"))
339 afile = new PIRFile(source);
341 else if (format.equals("PFAM"))
343 afile = new PfamFile(source);
345 else if (format.equals("JnetFile"))
347 afile = new JPredFile(source);
348 ((JPredFile) afile).removeNonSequences();
350 else if (format.equals("PDB"))
352 afile = new MCview.PDBfile(source);
354 else if (format.equals("STH"))
356 afile = new StockholmFile(source);
358 else if (format.equals("RNAML"))
360 afile = new RnamlFile(source);
362 else if (format.equals("SimpleBLAST"))
364 afile = new SimpleBlastFile(source);
366 else if (format.equals("GENBANK"))
368 afile = new GenBankFile(source);
371 Alignment al = new Alignment(afile.getSeqsAsArray());
373 afile.addAnnotations(al);
376 } catch (Exception e)
379 System.err.println("Failed to read alignment using the '" + format
380 + "' reader.\n" + e);
382 if (e.getMessage() != null
383 && e.getMessage().startsWith(INVALID_CHARACTERS))
385 throw new java.io.IOException(e.getMessage());
388 // Finally test if the user has pasted just the sequence, no id
389 if (type.equalsIgnoreCase("Paste"))
393 // Possible sequence is just residues with no label
394 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
395 Alignment al = new Alignment(afile.getSeqsAsArray());
396 afile.addAnnotations(al);
399 } catch (Exception ex)
401 if (ex.toString().startsWith(INVALID_CHARACTERS))
403 throw new java.io.IOException(e.getMessage());
406 ex.printStackTrace();
410 // If we get to this stage, the format was not supported
411 throw new java.io.IOException(SUPPORTED_FORMATS);
416 * Construct an output class for an alignment in a particular filetype TODO:
417 * allow caller to detect errors and warnings encountered when generating
421 * string name of alignment format
423 * the alignment to be written out
425 * passed to AlnFile class controls whether /START-END is added to
428 * @return alignment flat file contents
430 public String formatSequences(String format, AlignmentI alignment,
435 AlignFile afile = null;
437 if (format.equalsIgnoreCase("FASTA"))
439 afile = new FastaFile();
441 else if (format.equalsIgnoreCase("MSF"))
443 afile = new MSFfile();
445 else if (format.equalsIgnoreCase("PileUp"))
447 afile = new PileUpfile();
449 else if (format.equalsIgnoreCase("CLUSTAL"))
451 afile = new ClustalFile();
453 else if (format.equalsIgnoreCase("BLC"))
455 afile = new BLCFile();
457 else if (format.equalsIgnoreCase("PIR"))
459 afile = new PIRFile();
461 else if (format.equalsIgnoreCase("PFAM"))
463 afile = new PfamFile();
465 else if (format.equalsIgnoreCase("STH"))
467 afile = new StockholmFile(alignment);
469 else if (format.equalsIgnoreCase("AMSA"))
471 afile = new AMSAFile(alignment);
473 else if (format.equalsIgnoreCase("RNAML"))
475 afile = new RnamlFile();
477 else if (format.equalsIgnoreCase("GENBANK"))
479 afile = new GenBankFile();
484 "Implementation error: Unknown file format string");
486 afile.setNewlineString(newline);
487 afile.addJVSuffix(jvsuffix);
489 afile.setSeqs(alignment.getSequencesArray());
491 String afileresp = afile.print();
492 if (afile.hasWarningMessage())
494 System.err.println("Warning raised when writing as " + format
495 + " : " + afile.getWarningMessage());
498 } catch (Exception e)
500 System.err.println("Failed to write alignment as a '" + format
508 public static String checkProtocol(String file)
510 String protocol = FILE;
511 String ft = file.toLowerCase().trim();
512 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
513 || ft.indexOf("file:") == 0)
520 public static void main(String[] args)
523 while (i < args.length)
525 File f = new File(args[i]);
530 System.out.println("Reading file: " + f);
531 AppletFormatAdapter afa = new AppletFormatAdapter();
532 Runtime r = Runtime.getRuntime();
534 long memf = -r.totalMemory() + r.freeMemory();
535 long t1 = -System.currentTimeMillis();
536 Alignment al = afa.readFile(args[i], FILE,
537 new IdentifyFile().Identify(args[i], FILE));
538 t1 += System.currentTimeMillis();
540 memf += r.totalMemory() - r.freeMemory();
543 System.out.println("Alignment contains " + al.getHeight()
544 + " sequences and " + al.getWidth() + " columns.");
547 System.out.println(new AppletFormatAdapter().formatSequences(
549 } catch (Exception e)
552 .println("Couln't format the alignment for output as a FASTA file.");
553 e.printStackTrace(System.err);
558 System.out.println("Couldn't read alignment");
560 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
562 .println("Difference between free memory now and before is "
563 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
564 } catch (Exception e)
566 System.err.println("Exception when dealing with " + i
567 + "'th argument: " + args[i] + "\n" + e);
572 System.err.println("Ignoring argument '" + args[i] + "' (" + i
573 + "'th)- not a readable file.");
580 * try to discover how to access the given file as a valid datasource that
581 * will be identified as the given type.
585 * @return protocol that yields the data parsable as the given type
587 public static String resolveProtocol(String file, String format)
589 return resolveProtocol(file, format, false);
592 public static String resolveProtocol(String file, String format,
595 // TODO: test thoroughly!
596 String protocol = null;
599 System.out.println("resolving datasource started with:\n>>file\n"
600 + file + ">>endfile");
603 // This might throw a security exception in certain browsers
604 // Netscape Communicator for instance.
608 InputStream is = System.getSecurityManager().getClass()
609 .getResourceAsStream("/" + file);
617 System.err.println("Resource '" + file + "' was "
618 + (rtn ? "" : "not") + " located by classloader.");
623 protocol = AppletFormatAdapter.CLASSLOADER;
626 } catch (Exception ex)
629 .println("Exception checking resources: " + file + " " + ex);
632 if (file.indexOf("://") > -1)
634 protocol = AppletFormatAdapter.URL;
638 // skipping codebase prepend check.
639 protocol = AppletFormatAdapter.FILE;
646 System.out.println("Trying to get contents of resource as "
649 fp = new FileParse(file, protocol);
658 System.out.println("Successful.");
661 } catch (Exception e)
665 System.err.println("Exception when accessing content: " + e);
673 System.out.println("Accessing as paste.");
675 protocol = AppletFormatAdapter.PASTE;
679 fp = new FileParse(file, protocol);
684 } catch (Exception e)
686 System.err.println("Failed to access content as paste!");
695 if (format == null || format.length() == 0)
703 String idformat = new jalview.io.IdentifyFile().Identify(file,
705 if (idformat == null)
709 System.out.println("Format not identified. Inaccessible file.");
715 System.out.println("Format identified as " + idformat
716 + "and expected as " + format);
718 if (idformat.equals(format))
722 System.out.println("Protocol identified as " + protocol);
731 .println("File deemed not accessible via " + protocol);
736 } catch (Exception e)
740 System.err.println("File deemed not accessible via " + protocol);