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.
23 import jalview.datamodel.Alignment;
24 import jalview.datamodel.AlignmentI;
27 import java.io.InputStream;
30 * A low level class for alignment and feature IO with alignment formatting
31 * methods used by both applet and application for generating flat alignment
32 * files. It also holds the lists of magic format names that the applet and
33 * application will allow the user to read or write files with.
38 public class AppletFormatAdapter
41 * List of valid format strings used in the isValidFormat method
43 public static final String[] READABLE_FORMATS = new String[]
44 { "BLC", "CLUSTAL", "FASTA", "MEGA", "MSF", "PileUp", "PIR", "PFAM",
45 "PDB", "JnetFile", "RNAML" };
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", "MEGA", "MSF", "PileUp", "PIR", "PFAM",
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", "meg", "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", "MEGA", "MSF", "PIR", "BLC", "AMSA",
73 * List of readable format file extensions by application in order
74 * corresponding to READABLE_FNAMES
76 public static final String[] READABLE_EXTENSIONS = new String[]
77 { "fa, fasta, mfa, fastq", "aln", "pfam", "meg", "msf", "pir", "blc", "amsa",
78 "jar,jvp", "sto,stk", "xml,rnaml" }; // ".blast"
81 * List of readable formats by application in order corresponding to
84 public static final String[] READABLE_FNAMES = new String[]
85 { "Fasta", "Clustal", "PFAM", "MEGA", "MSF", "PIR", "BLC", "AMSA", "Jalview",
86 "Stockholm", "RNAML" };
91 public static String INVALID_CHARACTERS = "Contains invalid characters";
93 // TODO: make these messages dynamic
94 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
95 + prettyPrint(READABLE_FORMATS);
100 * @return grammatically correct(ish) list consisting of els elements.
102 public static String prettyPrint(String[] els)
104 StringBuffer list = new StringBuffer();
105 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
110 list.append(" and " + els[els.length - 1] + ".");
111 return list.toString();
114 public static String FILE = "File";
116 public static String URL = "URL";
118 public static String PASTE = "Paste";
120 public static String CLASSLOADER = "ClassLoader";
122 AlignFile afile = null;
127 * character used to write newlines
129 protected String newline = System.getProperty("line.separator");
131 public void setNewlineString(String nl)
136 public String getNewlineString()
142 * check that this format is valid for reading
145 * a format string to be compared with READABLE_FORMATS
146 * @return true if format is readable
148 public static final boolean isValidFormat(String format)
150 return isValidFormat(format, false);
154 * validate format is valid for IO
157 * a format string to be compared with either READABLE_FORMATS or
160 * when true, format is checked for containment in WRITEABLE_FORMATS
161 * @return true if format is valid
163 public static final boolean isValidFormat(String format,
166 boolean valid = false;
167 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
169 for (int i = 0; i < format_list.length; i++)
171 if (format_list[i].equalsIgnoreCase(format))
181 * Constructs the correct filetype parser for a characterised datasource
188 * File format of data provided by datasource
190 * @return DOCUMENT ME!
192 public Alignment readFile(String inFile, String type, String format)
193 throws java.io.IOException
195 // TODO: generalise mapping between format string and io. class instances
196 // using Constructor.invoke reflection
197 this.inFile = inFile;
200 if (format.equals("FASTA"))
202 afile = new FastaFile(inFile, type);
204 else if (format.equals("MSF"))
206 afile = new MSFfile(inFile, type);
208 else if (format.equals("PileUp"))
210 afile = new PileUpfile(inFile, type);
212 else if (format.equals("CLUSTAL"))
214 afile = new ClustalFile(inFile, type);
216 else if (format.equals("BLC"))
218 afile = new BLCFile(inFile, type);
220 else if (format.equals("PIR"))
222 afile = new PIRFile(inFile, type);
224 else if (format.equals("PFAM"))
226 afile = new PfamFile(inFile, type);
228 else if (format.equals("JnetFile"))
230 afile = new JPredFile(inFile, type);
231 ((JPredFile) afile).removeNonSequences();
233 else if (format.equals("PDB"))
235 afile = new MCview.PDBfile(inFile, type);
236 // Uncomment to test Jmol data based PDB processing: JAL-1213
237 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
239 else if (format.equals("STH"))
241 afile = new StockholmFile(inFile, type);
243 else if (format.equals("SimpleBLAST"))
245 afile = new SimpleBlastFile(inFile, type);
247 else if (format.equals("RNAML"))
249 afile = new RnamlFile(inFile, type);
251 else if (format.equals("MEGA"))
253 afile = new MegaFile(inFile, type);
256 Alignment al = new Alignment(afile.getSeqsAsArray());
258 afile.addAnnotations(al);
261 } catch (Exception e)
264 System.err.println("Failed to read alignment using the '" + format
265 + "' reader.\n" + e);
267 if (e.getMessage() != null
268 && e.getMessage().startsWith(INVALID_CHARACTERS))
270 throw new java.io.IOException(e.getMessage());
273 // Finally test if the user has pasted just the sequence, no id
274 if (type.equalsIgnoreCase("Paste"))
278 // Possible sequence is just residues with no label
279 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
280 Alignment al = new Alignment(afile.getSeqsAsArray());
281 afile.addAnnotations(al);
284 } catch (Exception ex)
286 if (ex.toString().startsWith(INVALID_CHARACTERS))
288 throw new java.io.IOException(e.getMessage());
291 ex.printStackTrace();
295 // If we get to this stage, the format was not supported
296 throw new java.io.IOException(SUPPORTED_FORMATS);
301 * Constructs the correct filetype parser for an already open datasource
304 * an existing datasource
306 * File format of data that will be provided by datasource
308 * @return DOCUMENT ME!
310 public AlignmentI readFromFile(FileParse source, String format)
311 throws java.io.IOException
313 // TODO: generalise mapping between format string and io. class instances
314 // using Constructor.invoke reflection
315 // This is exactly the same as the readFile method except we substitute
316 // 'inFile, type' with 'source'
317 this.inFile = source.getInFile();
318 String type = source.type;
321 if (format.equals("FASTA"))
323 afile = new FastaFile(source);
325 else if (format.equals("MSF"))
327 afile = new MSFfile(source);
329 else if (format.equals("PileUp"))
331 afile = new PileUpfile(source);
333 else if (format.equals("CLUSTAL"))
335 afile = new ClustalFile(source);
337 else if (format.equals("BLC"))
339 afile = new BLCFile(source);
341 else if (format.equals("PIR"))
343 afile = new PIRFile(source);
345 else if (format.equals("PFAM"))
347 afile = new PfamFile(source);
349 else if (format.equals("JnetFile"))
351 afile = new JPredFile(source);
352 ((JPredFile) afile).removeNonSequences();
354 else if (format.equals("PDB"))
356 afile = new MCview.PDBfile(source);
358 else if (format.equals("STH"))
360 afile = new StockholmFile(source);
362 else if (format.equals("RNAML"))
364 afile = new RnamlFile(source);
366 else if (format.equals("SimpleBLAST"))
368 afile = new SimpleBlastFile(source);
370 else if (format.equals("MEGA"))
372 afile = new MegaFile(source);
375 Alignment al = new Alignment(afile.getSeqsAsArray());
377 afile.addAnnotations(al);
380 } catch (Exception e)
383 System.err.println("Failed to read alignment using the '" + format
384 + "' reader.\n" + e);
386 if (e.getMessage() != null
387 && e.getMessage().startsWith(INVALID_CHARACTERS))
389 throw new java.io.IOException(e.getMessage());
392 // Finally test if the user has pasted just the sequence, no id
393 if (type.equalsIgnoreCase("Paste"))
397 // Possible sequence is just residues with no label
398 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
399 Alignment al = new Alignment(afile.getSeqsAsArray());
400 afile.addAnnotations(al);
403 } catch (Exception ex)
405 if (ex.toString().startsWith(INVALID_CHARACTERS))
407 throw new java.io.IOException(e.getMessage());
410 ex.printStackTrace();
414 // If we get to this stage, the format was not supported
415 throw new java.io.IOException(SUPPORTED_FORMATS);
420 * Construct an output class for an alignment in a particular filetype TODO:
421 * allow caller to detect errors and warnings encountered when generating
425 * string name of alignment format
427 * the alignment to be written out
429 * passed to AlnFile class controls whether /START-END is added to
432 * @return alignment flat file contents
434 public String formatSequences(String format, AlignmentI alignment,
439 AlignFile afile = null;
441 if (format.equalsIgnoreCase("FASTA"))
443 afile = new FastaFile();
445 else if (format.equalsIgnoreCase("MSF"))
447 afile = new MSFfile();
449 else if (format.equalsIgnoreCase("PileUp"))
451 afile = new PileUpfile();
453 else if (format.equalsIgnoreCase("CLUSTAL"))
455 afile = new ClustalFile();
457 else if (format.equalsIgnoreCase("BLC"))
459 afile = new BLCFile();
461 else if (format.equalsIgnoreCase("PIR"))
463 afile = new PIRFile();
465 else if (format.equalsIgnoreCase("PFAM"))
467 afile = new PfamFile();
469 else if (format.equalsIgnoreCase("STH"))
471 afile = new StockholmFile(alignment);
473 else if (format.equalsIgnoreCase("AMSA"))
475 afile = new AMSAFile(alignment);
477 else if (format.equalsIgnoreCase("RNAML"))
479 afile = new RnamlFile();
481 else if (format.equalsIgnoreCase("MEGA"))
483 afile = new MegaFile();
488 "Implementation error: Unknown file format string");
490 afile.setNewlineString(newline);
491 afile.addJVSuffix(jvsuffix);
493 afile.setSeqs(alignment.getSequencesArray());
495 String afileresp = afile.print();
496 if (afile.hasWarningMessage())
498 System.err.println("Warning raised when writing as " + format
499 + " : " + afile.getWarningMessage());
502 } catch (Exception e)
504 System.err.println("Failed to write alignment as a '" + format
512 public static String checkProtocol(String file)
514 String protocol = FILE;
515 String ft = file.toLowerCase().trim();
516 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
517 || ft.indexOf("file:") == 0)
524 public static void main(String[] args)
527 while (i < args.length)
529 File f = new File(args[i]);
534 System.out.println("Reading file: " + f);
535 AppletFormatAdapter afa = new AppletFormatAdapter();
536 Runtime r = Runtime.getRuntime();
538 long memf = -r.totalMemory() + r.freeMemory();
539 long t1 = -System.currentTimeMillis();
540 Alignment al = afa.readFile(args[i], FILE,
541 new IdentifyFile().Identify(args[i], FILE));
542 t1 += System.currentTimeMillis();
544 memf += r.totalMemory() - r.freeMemory();
547 System.out.println("Alignment contains " + al.getHeight()
548 + " sequences and " + al.getWidth() + " columns.");
551 System.out.println(new AppletFormatAdapter().formatSequences(
553 } catch (Exception e)
556 .println("Couln't format the alignment for output as a FASTA file.");
557 e.printStackTrace(System.err);
562 System.out.println("Couldn't read alignment");
564 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
566 .println("Difference between free memory now and before is "
567 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
568 } catch (Exception e)
570 System.err.println("Exception when dealing with " + i
571 + "'th argument: " + args[i] + "\n" + e);
576 System.err.println("Ignoring argument '" + args[i] + "' (" + i
577 + "'th)- not a readable file.");
584 * try to discover how to access the given file as a valid datasource that
585 * will be identified as the given type.
589 * @return protocol that yields the data parsable as the given type
591 public static String resolveProtocol(String file, String format)
593 return resolveProtocol(file, format, false);
596 public static String resolveProtocol(String file, String format,
599 // TODO: test thoroughly!
600 String protocol = null;
603 System.out.println("resolving datasource started with:\n>>file\n"
604 + file + ">>endfile");
607 // This might throw a security exception in certain browsers
608 // Netscape Communicator for instance.
612 InputStream is = System.getSecurityManager().getClass()
613 .getResourceAsStream("/" + file);
621 System.err.println("Resource '" + file + "' was "
622 + (rtn ? "" : "not") + " located by classloader.");
627 protocol = AppletFormatAdapter.CLASSLOADER;
630 } catch (Exception ex)
633 .println("Exception checking resources: " + file + " " + ex);
636 if (file.indexOf("://") > -1)
638 protocol = AppletFormatAdapter.URL;
642 // skipping codebase prepend check.
643 protocol = AppletFormatAdapter.FILE;
650 System.out.println("Trying to get contents of resource as "
653 fp = new FileParse(file, protocol);
662 System.out.println("Successful.");
665 } catch (Exception e)
669 System.err.println("Exception when accessing content: " + e);
677 System.out.println("Accessing as paste.");
679 protocol = AppletFormatAdapter.PASTE;
683 fp = new FileParse(file, protocol);
688 } catch (Exception e)
690 System.err.println("Failed to access content as paste!");
699 if (format == null || format.length() == 0)
707 String idformat = new jalview.io.IdentifyFile().Identify(file,
709 if (idformat == null)
713 System.out.println("Format not identified. Inaccessible file.");
719 System.out.println("Format identified as " + idformat
720 + "and expected as " + format);
722 if (idformat.equals(format))
726 System.out.println("Protocol identified as " + protocol);
735 .println("File deemed not accessible via " + protocol);
740 } catch (Exception e)
744 System.err.println("File deemed not accessible via " + protocol);