2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.1)
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", "jvp",
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,jvp",
73 "sto,stk", "xml,rnaml" }; // ".blast"
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",
81 "Stockholm","RNAML" };// ,
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 * character used to write newlines
124 protected String newline = System.getProperty("line.separator");
126 public void setNewlineString(String nl)
131 public String getNewlineString()
137 * check that this format is valid for reading
140 * a format string to be compared with READABLE_FORMATS
141 * @return true if format is readable
143 public static final boolean isValidFormat(String format)
145 return isValidFormat(format, false);
149 * validate format is valid for IO
152 * a format string to be compared with either READABLE_FORMATS or
155 * when true, format is checked for containment in WRITEABLE_FORMATS
156 * @return true if format is valid
158 public static final boolean isValidFormat(String format,
161 boolean valid = false;
162 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
164 for (int i = 0; i < format_list.length; i++)
166 if (format_list[i].equalsIgnoreCase(format))
176 * Constructs the correct filetype parser for a characterised datasource
183 * File format of data provided by datasource
185 * @return DOCUMENT ME!
187 public Alignment readFile(String inFile, String type, String format)
188 throws java.io.IOException
190 // TODO: generalise mapping between format string and io. class instances
191 // using Constructor.invoke reflection
192 this.inFile = inFile;
195 if (format.equals("FASTA"))
197 afile = new FastaFile(inFile, type);
199 else if (format.equals("MSF"))
201 afile = new MSFfile(inFile, type);
203 else if (format.equals("PileUp"))
205 afile = new PileUpfile(inFile, type);
207 else if (format.equals("CLUSTAL"))
209 afile = new ClustalFile(inFile, type);
211 else if (format.equals("BLC"))
213 afile = new BLCFile(inFile, type);
215 else if (format.equals("PIR"))
217 afile = new PIRFile(inFile, type);
219 else if (format.equals("PFAM"))
221 afile = new PfamFile(inFile, type);
223 else if (format.equals("JnetFile"))
225 afile = new JPredFile(inFile, type);
226 ((JPredFile) afile).removeNonSequences();
228 else if (format.equals("PDB"))
230 afile = new MCview.PDBfile(inFile, type);
231 // Uncomment to test Jmol data based PDB processing: JAL-1213
232 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
234 else if (format.equals("STH"))
236 afile = new StockholmFile(inFile, type);
238 else if (format.equals("SimpleBLAST"))
240 afile = new SimpleBlastFile(inFile, type);
242 else if (format.equals("RNAML"))
244 afile = new RnamlFile(inFile, type);
247 Alignment al = new Alignment(afile.getSeqsAsArray());
249 afile.addAnnotations(al);
252 } catch (Exception e)
255 System.err.println("Failed to read alignment using the '" + format
256 + "' reader.\n" + e);
258 if (e.getMessage() != null
259 && e.getMessage().startsWith(INVALID_CHARACTERS))
261 throw new java.io.IOException(e.getMessage());
264 // Finally test if the user has pasted just the sequence, no id
265 if (type.equalsIgnoreCase("Paste"))
269 // Possible sequence is just residues with no label
270 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
271 Alignment al = new Alignment(afile.getSeqsAsArray());
272 afile.addAnnotations(al);
275 } catch (Exception ex)
277 if (ex.toString().startsWith(INVALID_CHARACTERS))
279 throw new java.io.IOException(e.getMessage());
282 ex.printStackTrace();
286 // If we get to this stage, the format was not supported
287 throw new java.io.IOException(SUPPORTED_FORMATS);
292 * Constructs the correct filetype parser for an already open datasource
295 * an existing datasource
297 * File format of data that will be provided by datasource
299 * @return DOCUMENT ME!
301 public AlignmentI readFromFile(FileParse source, String format)
302 throws java.io.IOException
304 // TODO: generalise mapping between format string and io. class instances
305 // using Constructor.invoke reflection
306 // This is exactly the same as the readFile method except we substitute
307 // 'inFile, type' with 'source'
308 this.inFile = source.getInFile();
309 String type = source.type;
312 if (format.equals("FASTA"))
314 afile = new FastaFile(source);
316 else if (format.equals("MSF"))
318 afile = new MSFfile(source);
320 else if (format.equals("PileUp"))
322 afile = new PileUpfile(source);
324 else if (format.equals("CLUSTAL"))
326 afile = new ClustalFile(source);
328 else if (format.equals("BLC"))
330 afile = new BLCFile(source);
332 else if (format.equals("PIR"))
334 afile = new PIRFile(source);
336 else if (format.equals("PFAM"))
338 afile = new PfamFile(source);
340 else if (format.equals("JnetFile"))
342 afile = new JPredFile(source);
343 ((JPredFile) afile).removeNonSequences();
345 else if (format.equals("PDB"))
347 afile = new MCview.PDBfile(source);
349 else if (format.equals("STH"))
351 afile = new StockholmFile(source);
353 else if (format.equals("RNAML"))
355 afile = new RnamlFile(source);
357 else if (format.equals("SimpleBLAST"))
359 afile = new SimpleBlastFile(source);
362 Alignment al = new Alignment(afile.getSeqsAsArray());
364 afile.addAnnotations(al);
367 } catch (Exception e)
370 System.err.println("Failed to read alignment using the '" + format
371 + "' reader.\n" + e);
373 if (e.getMessage() != null
374 && e.getMessage().startsWith(INVALID_CHARACTERS))
376 throw new java.io.IOException(e.getMessage());
379 // Finally test if the user has pasted just the sequence, no id
380 if (type.equalsIgnoreCase("Paste"))
384 // Possible sequence is just residues with no label
385 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
386 Alignment al = new Alignment(afile.getSeqsAsArray());
387 afile.addAnnotations(al);
390 } catch (Exception ex)
392 if (ex.toString().startsWith(INVALID_CHARACTERS))
394 throw new java.io.IOException(e.getMessage());
397 ex.printStackTrace();
401 // If we get to this stage, the format was not supported
402 throw new java.io.IOException(SUPPORTED_FORMATS);
407 * Construct an output class for an alignment in a particular filetype TODO:
408 * allow caller to detect errors and warnings encountered when generating
412 * string name of alignment format
414 * the alignment to be written out
416 * passed to AlnFile class controls whether /START-END is added to
419 * @return alignment flat file contents
421 public String formatSequences(String format, AlignmentI alignment,
426 AlignFile afile = null;
428 if (format.equalsIgnoreCase("FASTA"))
430 afile = new FastaFile();
432 else if (format.equalsIgnoreCase("MSF"))
434 afile = new MSFfile();
436 else if (format.equalsIgnoreCase("PileUp"))
438 afile = new PileUpfile();
440 else if (format.equalsIgnoreCase("CLUSTAL"))
442 afile = new ClustalFile();
444 else if (format.equalsIgnoreCase("BLC"))
446 afile = new BLCFile();
448 else if (format.equalsIgnoreCase("PIR"))
450 afile = new PIRFile();
452 else if (format.equalsIgnoreCase("PFAM"))
454 afile = new PfamFile();
456 else if (format.equalsIgnoreCase("STH"))
458 afile = new StockholmFile(alignment);
460 else if (format.equalsIgnoreCase("AMSA"))
462 afile = new AMSAFile(alignment);
464 else if (format.equalsIgnoreCase("RNAML"))
466 afile = new RnamlFile();
472 "Implementation error: Unknown file format string");
474 afile.setNewlineString(newline);
475 afile.addJVSuffix(jvsuffix);
477 afile.setSeqs(alignment.getSequencesArray());
479 String afileresp = afile.print();
480 if (afile.hasWarningMessage())
482 System.err.println("Warning raised when writing as " + format
483 + " : " + afile.getWarningMessage());
486 } catch (Exception e)
488 System.err.println("Failed to write alignment as a '" + format
496 public static String checkProtocol(String file)
498 String protocol = FILE;
499 String ft = file.toLowerCase().trim();
500 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
501 || ft.indexOf("file:") == 0)
508 public static void main(String[] args)
511 while (i < args.length)
513 File f = new File(args[i]);
518 System.out.println("Reading file: " + f);
519 AppletFormatAdapter afa = new AppletFormatAdapter();
520 Runtime r = Runtime.getRuntime();
522 long memf = -r.totalMemory() + r.freeMemory();
523 long t1 = -System.currentTimeMillis();
524 Alignment al = afa.readFile(args[i], FILE,
525 new IdentifyFile().Identify(args[i], FILE));
526 t1 += System.currentTimeMillis();
528 memf += r.totalMemory() - r.freeMemory();
531 System.out.println("Alignment contains " + al.getHeight()
532 + " sequences and " + al.getWidth() + " columns.");
535 System.out.println(new AppletFormatAdapter().formatSequences(
537 } catch (Exception e)
540 .println("Couln't format the alignment for output as a FASTA file.");
541 e.printStackTrace(System.err);
546 System.out.println("Couldn't read alignment");
548 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
550 .println("Difference between free memory now and before is "
551 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
552 } catch (Exception e)
554 System.err.println("Exception when dealing with " + i
555 + "'th argument: " + args[i] + "\n" + e);
560 System.err.println("Ignoring argument '" + args[i] + "' (" + i
561 + "'th)- not a readable file.");
568 * try to discover how to access the given file as a valid datasource that
569 * will be identified as the given type.
573 * @return protocol that yields the data parsable as the given type
575 public static String resolveProtocol(String file, String format)
577 return resolveProtocol(file, format, false);
580 public static String resolveProtocol(String file, String format,
583 // TODO: test thoroughly!
584 String protocol = null;
587 System.out.println("resolving datasource started with:\n>>file\n"
588 + file + ">>endfile");
591 // This might throw a security exception in certain browsers
592 // Netscape Communicator for instance.
596 InputStream is = System.getSecurityManager().getClass()
597 .getResourceAsStream("/" + file);
605 System.err.println("Resource '" + file + "' was "
606 + (rtn ? "" : "not") + " located by classloader.");
611 protocol = AppletFormatAdapter.CLASSLOADER;
614 } catch (Exception ex)
617 .println("Exception checking resources: " + file + " " + ex);
620 if (file.indexOf("://") > -1)
622 protocol = AppletFormatAdapter.URL;
626 // skipping codebase prepend check.
627 protocol = AppletFormatAdapter.FILE;
634 System.out.println("Trying to get contents of resource as "
637 fp = new FileParse(file, protocol);
646 System.out.println("Successful.");
649 } catch (Exception e)
653 System.err.println("Exception when accessing content: " + e);
661 System.out.println("Accessing as paste.");
663 protocol = AppletFormatAdapter.PASTE;
667 fp = new FileParse(file, protocol);
672 } catch (Exception e)
674 System.err.println("Failed to access content as paste!");
683 if (format == null || format.length() == 0)
691 String idformat = new jalview.io.IdentifyFile().Identify(file,
693 if (idformat == null)
697 System.out.println("Format not identified. Inaccessible file.");
703 System.out.println("Format identified as " + idformat
704 + "and expected as " + format);
706 if (idformat.equals(format))
710 System.out.println("Protocol identified as " + protocol);
719 .println("File deemed not accessible via " + protocol);
724 } catch (Exception e)
728 System.err.println("File deemed not accessible via " + protocol);