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" }; // , "SimpleBLAST" };
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, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
75 "jar,jvp", "sto,stk", "xml,rnaml" }; // ".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" };// ,
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);
249 Alignment al = new Alignment(afile.getSeqsAsArray());
251 afile.addAnnotations(al);
254 } catch (Exception e)
257 System.err.println("Failed to read alignment using the '" + format
258 + "' reader.\n" + e);
260 if (e.getMessage() != null
261 && e.getMessage().startsWith(INVALID_CHARACTERS))
263 throw new java.io.IOException(e.getMessage());
266 // Finally test if the user has pasted just the sequence, no id
267 if (type.equalsIgnoreCase("Paste"))
271 // Possible sequence is just residues with no label
272 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
273 Alignment al = new Alignment(afile.getSeqsAsArray());
274 afile.addAnnotations(al);
277 } catch (Exception ex)
279 if (ex.toString().startsWith(INVALID_CHARACTERS))
281 throw new java.io.IOException(e.getMessage());
284 ex.printStackTrace();
288 // If we get to this stage, the format was not supported
289 throw new java.io.IOException(SUPPORTED_FORMATS);
294 * Constructs the correct filetype parser for an already open datasource
297 * an existing datasource
299 * File format of data that will be provided by datasource
301 * @return DOCUMENT ME!
303 public AlignmentI readFromFile(FileParse source, String format)
304 throws java.io.IOException
306 // TODO: generalise mapping between format string and io. class instances
307 // using Constructor.invoke reflection
308 // This is exactly the same as the readFile method except we substitute
309 // 'inFile, type' with 'source'
310 this.inFile = source.getInFile();
311 String type = source.type;
314 if (format.equals("FASTA"))
316 afile = new FastaFile(source);
318 else if (format.equals("MSF"))
320 afile = new MSFfile(source);
322 else if (format.equals("PileUp"))
324 afile = new PileUpfile(source);
326 else if (format.equals("CLUSTAL"))
328 afile = new ClustalFile(source);
330 else if (format.equals("BLC"))
332 afile = new BLCFile(source);
334 else if (format.equals("PIR"))
336 afile = new PIRFile(source);
338 else if (format.equals("PFAM"))
340 afile = new PfamFile(source);
342 else if (format.equals("JnetFile"))
344 afile = new JPredFile(source);
345 ((JPredFile) afile).removeNonSequences();
347 else if (format.equals("PDB"))
349 afile = new MCview.PDBfile(source);
351 else if (format.equals("STH"))
353 afile = new StockholmFile(source);
355 else if (format.equals("RNAML"))
357 afile = new RnamlFile(source);
359 else if (format.equals("SimpleBLAST"))
361 afile = new SimpleBlastFile(source);
364 Alignment al = new Alignment(afile.getSeqsAsArray());
366 afile.addAnnotations(al);
369 } catch (Exception e)
372 System.err.println("Failed to read alignment using the '" + format
373 + "' reader.\n" + e);
375 if (e.getMessage() != null
376 && e.getMessage().startsWith(INVALID_CHARACTERS))
378 throw new java.io.IOException(e.getMessage());
381 // Finally test if the user has pasted just the sequence, no id
382 if (type.equalsIgnoreCase("Paste"))
386 // Possible sequence is just residues with no label
387 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
388 Alignment al = new Alignment(afile.getSeqsAsArray());
389 afile.addAnnotations(al);
392 } catch (Exception ex)
394 if (ex.toString().startsWith(INVALID_CHARACTERS))
396 throw new java.io.IOException(e.getMessage());
399 ex.printStackTrace();
403 // If we get to this stage, the format was not supported
404 throw new java.io.IOException(SUPPORTED_FORMATS);
409 * Construct an output class for an alignment in a particular filetype TODO:
410 * allow caller to detect errors and warnings encountered when generating
414 * string name of alignment format
416 * the alignment to be written out
418 * passed to AlnFile class controls whether /START-END is added to
421 * @return alignment flat file contents
423 public String formatSequences(String format, AlignmentI alignment,
428 AlignFile afile = null;
430 if (format.equalsIgnoreCase("FASTA"))
432 afile = new FastaFile();
434 else if (format.equalsIgnoreCase("MSF"))
436 afile = new MSFfile();
438 else if (format.equalsIgnoreCase("PileUp"))
440 afile = new PileUpfile();
442 else if (format.equalsIgnoreCase("CLUSTAL"))
444 afile = new ClustalFile();
446 else if (format.equalsIgnoreCase("BLC"))
448 afile = new BLCFile();
450 else if (format.equalsIgnoreCase("PIR"))
452 afile = new PIRFile();
454 else if (format.equalsIgnoreCase("PFAM"))
456 afile = new PfamFile();
458 else if (format.equalsIgnoreCase("STH"))
460 afile = new StockholmFile(alignment);
462 else if (format.equalsIgnoreCase("AMSA"))
464 afile = new AMSAFile(alignment);
466 else if (format.equalsIgnoreCase("RNAML"))
468 afile = new RnamlFile();
474 "Implementation error: Unknown file format string");
476 afile.setNewlineString(newline);
477 afile.addJVSuffix(jvsuffix);
479 afile.setSeqs(alignment.getSequencesArray());
481 String afileresp = afile.print();
482 if (afile.hasWarningMessage())
484 System.err.println("Warning raised when writing as " + format
485 + " : " + afile.getWarningMessage());
488 } catch (Exception e)
490 System.err.println("Failed to write alignment as a '" + format
498 public static String checkProtocol(String file)
500 String protocol = FILE;
501 String ft = file.toLowerCase().trim();
502 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
503 || ft.indexOf("file:") == 0)
510 public static void main(String[] args)
513 while (i < args.length)
515 File f = new File(args[i]);
520 System.out.println("Reading file: " + f);
521 AppletFormatAdapter afa = new AppletFormatAdapter();
522 Runtime r = Runtime.getRuntime();
524 long memf = -r.totalMemory() + r.freeMemory();
525 long t1 = -System.currentTimeMillis();
526 Alignment al = afa.readFile(args[i], FILE,
527 new IdentifyFile().Identify(args[i], FILE));
528 t1 += System.currentTimeMillis();
530 memf += r.totalMemory() - r.freeMemory();
533 System.out.println("Alignment contains " + al.getHeight()
534 + " sequences and " + al.getWidth() + " columns.");
537 System.out.println(new AppletFormatAdapter().formatSequences(
539 } catch (Exception e)
542 .println("Couln't format the alignment for output as a FASTA file.");
543 e.printStackTrace(System.err);
548 System.out.println("Couldn't read alignment");
550 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
552 .println("Difference between free memory now and before is "
553 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
554 } catch (Exception e)
556 System.err.println("Exception when dealing with " + i
557 + "'th argument: " + args[i] + "\n" + e);
562 System.err.println("Ignoring argument '" + args[i] + "' (" + i
563 + "'th)- not a readable file.");
570 * try to discover how to access the given file as a valid datasource that
571 * will be identified as the given type.
575 * @return protocol that yields the data parsable as the given type
577 public static String resolveProtocol(String file, String format)
579 return resolveProtocol(file, format, false);
582 public static String resolveProtocol(String file, String format,
585 // TODO: test thoroughly!
586 String protocol = null;
589 System.out.println("resolving datasource started with:\n>>file\n"
590 + file + ">>endfile");
593 // This might throw a security exception in certain browsers
594 // Netscape Communicator for instance.
598 InputStream is = System.getSecurityManager().getClass()
599 .getResourceAsStream("/" + file);
607 System.err.println("Resource '" + file + "' was "
608 + (rtn ? "" : "not") + " located by classloader.");
613 protocol = AppletFormatAdapter.CLASSLOADER;
616 } catch (Exception ex)
619 .println("Exception checking resources: " + file + " " + ex);
622 if (file.indexOf("://") > -1)
624 protocol = AppletFormatAdapter.URL;
628 // skipping codebase prepend check.
629 protocol = AppletFormatAdapter.FILE;
636 System.out.println("Trying to get contents of resource as "
639 fp = new FileParse(file, protocol);
648 System.out.println("Successful.");
651 } catch (Exception e)
655 System.err.println("Exception when accessing content: " + e);
663 System.out.println("Accessing as paste.");
665 protocol = AppletFormatAdapter.PASTE;
669 fp = new FileParse(file, protocol);
674 } catch (Exception e)
676 System.err.println("Failed to access content as paste!");
685 if (format == null || format.length() == 0)
693 String idformat = new jalview.io.IdentifyFile().Identify(file,
695 if (idformat == null)
699 System.out.println("Format not identified. Inaccessible file.");
705 System.out.println("Format identified as " + idformat
706 + "and expected as " + format);
708 if (idformat.equals(format))
712 System.out.println("Protocol identified as " + protocol);
721 .println("File deemed not accessible via " + protocol);
726 } catch (Exception e)
730 System.err.println("File deemed not accessible via " + protocol);