2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3 * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, 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" , "RNAML"}; // , "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,faa,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,faa,fasta,fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar",
70 "sto,stk","xml" }; // ,
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);
232 else if (format.equals("STH"))
234 afile = new StockholmFile(inFile, type);
236 else if (format.equals("SimpleBLAST"))
238 afile = new SimpleBlastFile(inFile, type);
240 else if (format.equals("RNAML"))
242 afile = new RnamlFile(inFile, type);
245 Alignment al = new Alignment(afile.getSeqsAsArray());
247 afile.addAnnotations(al);
250 } catch (Exception e)
253 System.err.println("Failed to read alignment using the '" + format
254 + "' reader.\n" + e);
256 if (e.getMessage() != null
257 && e.getMessage().startsWith(INVALID_CHARACTERS))
259 throw new java.io.IOException(e.getMessage());
262 // Finally test if the user has pasted just the sequence, no id
263 if (type.equalsIgnoreCase("Paste"))
267 // Possible sequence is just residues with no label
268 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
269 Alignment al = new Alignment(afile.getSeqsAsArray());
270 afile.addAnnotations(al);
273 } catch (Exception ex)
275 if (ex.toString().startsWith(INVALID_CHARACTERS))
277 throw new java.io.IOException(e.getMessage());
280 ex.printStackTrace();
284 // If we get to this stage, the format was not supported
285 throw new java.io.IOException(SUPPORTED_FORMATS);
290 * Constructs the correct filetype parser for an already open datasource
293 * an existing datasource
295 * File format of data that will be provided by datasource
297 * @return DOCUMENT ME!
299 public Alignment readFromFile(FileParse source, String format)
300 throws java.io.IOException
302 // TODO: generalise mapping between format string and io. class instances
303 // using Constructor.invoke reflection
304 // This is exactly the same as the readFile method except we substitute
305 // 'inFile, type' with 'source'
306 this.inFile = source.getInFile();
307 String type = source.type;
310 if (format.equals("FASTA"))
312 afile = new FastaFile(source);
314 else if (format.equals("MSF"))
316 afile = new MSFfile(source);
318 else if (format.equals("PileUp"))
320 afile = new PileUpfile(source);
322 else if (format.equals("CLUSTAL"))
324 afile = new ClustalFile(source);
326 else if (format.equals("BLC"))
328 afile = new BLCFile(source);
330 else if (format.equals("PIR"))
332 afile = new PIRFile(source);
334 else if (format.equals("PFAM"))
336 afile = new PfamFile(source);
338 else if (format.equals("JnetFile"))
340 afile = new JPredFile(source);
341 ((JPredFile) afile).removeNonSequences();
343 else if (format.equals("PDB"))
345 afile = new MCview.PDBfile(source);
347 else if (format.equals("STH"))
349 afile = new StockholmFile(source);
351 else if (format.equals("RNAML"))
353 afile = new RnamlFile(source);
355 else if (format.equals("SimpleBLAST"))
357 afile = new SimpleBlastFile(source);
360 Alignment al = new Alignment(afile.getSeqsAsArray());
362 afile.addAnnotations(al);
365 } catch (Exception e)
368 System.err.println("Failed to read alignment using the '" + format
369 + "' reader.\n" + e);
371 if (e.getMessage() != null
372 && e.getMessage().startsWith(INVALID_CHARACTERS))
374 throw new java.io.IOException(e.getMessage());
377 // Finally test if the user has pasted just the sequence, no id
378 if (type.equalsIgnoreCase("Paste"))
382 // Possible sequence is just residues with no label
383 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
384 Alignment al = new Alignment(afile.getSeqsAsArray());
385 afile.addAnnotations(al);
388 } catch (Exception ex)
390 if (ex.toString().startsWith(INVALID_CHARACTERS))
392 throw new java.io.IOException(e.getMessage());
395 ex.printStackTrace();
399 // If we get to this stage, the format was not supported
400 throw new java.io.IOException(SUPPORTED_FORMATS);
405 * Construct an output class for an alignment in a particular filetype TODO:
406 * allow caller to detect errors and warnings encountered when generating
410 * string name of alignment format
412 * the alignment to be written out
414 * passed to AlnFile class controls whether /START-END is added to
417 * @return alignment flat file contents
419 public String formatSequences(String format, AlignmentI alignment,
424 AlignFile afile = null;
426 if (format.equalsIgnoreCase("FASTA"))
428 afile = new FastaFile();
430 else if (format.equalsIgnoreCase("MSF"))
432 afile = new MSFfile();
434 else if (format.equalsIgnoreCase("PileUp"))
436 afile = new PileUpfile();
438 else if (format.equalsIgnoreCase("CLUSTAL"))
440 afile = new ClustalFile();
442 else if (format.equalsIgnoreCase("BLC"))
444 afile = new BLCFile();
446 else if (format.equalsIgnoreCase("PIR"))
448 afile = new PIRFile();
450 else if (format.equalsIgnoreCase("PFAM"))
452 afile = new PfamFile();
454 else if (format.equalsIgnoreCase("STH"))
456 afile = new StockholmFile();
458 else if (format.equalsIgnoreCase("AMSA"))
460 afile = new AMSAFile(alignment);
462 else if (format.equalsIgnoreCase("RNAML"))
464 afile = new RnamlFile();
470 "Implementation error: Unknown file format string");
472 afile.setNewlineString(newline);
473 afile.addJVSuffix(jvsuffix);
475 afile.setSeqs(alignment.getSequencesArray());
477 String afileresp = afile.print();
478 if (afile.hasWarningMessage())
480 System.err.println("Warning raised when writing as " + format
481 + " : " + afile.getWarningMessage());
484 } catch (Exception e)
486 System.err.println("Failed to write alignment as a '" + format
494 public static String checkProtocol(String file)
496 String protocol = FILE;
497 String ft = file.toLowerCase().trim();
498 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
499 || ft.indexOf("file:") == 0)
506 public static void main(String[] args)
509 while (i < args.length)
511 File f = new File(args[i]);
516 System.out.println("Reading file: " + f);
517 AppletFormatAdapter afa = new AppletFormatAdapter();
518 Runtime r = Runtime.getRuntime();
520 long memf = -r.totalMemory() + r.freeMemory();
521 long t1 = -System.currentTimeMillis();
522 Alignment al = afa.readFile(args[i], FILE,
523 new IdentifyFile().Identify(args[i], FILE));
524 t1 += System.currentTimeMillis();
526 memf += r.totalMemory() - r.freeMemory();
529 System.out.println("Alignment contains " + al.getHeight()
530 + " sequences and " + al.getWidth() + " columns.");
533 System.out.println(new AppletFormatAdapter().formatSequences(
535 } catch (Exception e)
538 .println("Couln't format the alignment for output as a FASTA file.");
539 e.printStackTrace(System.err);
544 System.out.println("Couldn't read alignment");
546 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
548 .println("Difference between free memory now and before is "
549 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
551 } catch (Exception e)
553 System.err.println("Exception when dealing with " + i
554 + "'th argument: " + args[i] + "\n" + e);
559 System.err.println("Ignoring argument '" + args[i] + "' (" + i
560 + "'th)- not a readable file.");
567 * try to discover how to access the given file as a valid datasource that
568 * will be identified as the given type.
572 * @return protocol that yields the data parsable as the given type
574 public static String resolveProtocol(String file, String format)
576 return resolveProtocol(file, format, false);
579 public static String resolveProtocol(String file, String format,
582 // TODO: test thoroughly!
583 String protocol = null;
586 System.out.println("resolving datasource started with:\n>>file\n"
587 + file + ">>endfile");
590 // This might throw a security exception in certain browsers
591 // Netscape Communicator for instance.
595 InputStream is = System.getSecurityManager().getClass()
596 .getResourceAsStream("/" + file);
604 System.err.println("Resource '" + file + "' was "
605 + (rtn ? "" : "not") + " located by classloader.");
610 protocol = AppletFormatAdapter.CLASSLOADER;
613 } catch (Exception ex)
616 .println("Exception checking resources: " + file + " " + ex);
619 if (file.indexOf("://") > -1)
621 protocol = AppletFormatAdapter.URL;
625 // skipping codebase prepend check.
626 protocol = AppletFormatAdapter.FILE;
633 System.out.println("Trying to get contents of resource as "
636 fp = new FileParse(file, protocol);
645 System.out.println("Successful.");
648 } catch (Exception e)
652 System.err.println("Exception when accessing content: " + e);
660 System.out.println("Accessing as paste.");
662 protocol = AppletFormatAdapter.PASTE;
666 fp = new FileParse(file, protocol);
671 } catch (Exception e)
673 System.err.println("Failed to access content as paste!");
682 if (format == null || format.length() == 0)
690 String idformat = new jalview.io.IdentifyFile().Identify(file,
692 if (idformat == null)
696 System.out.println("Format not identified. Inaccessible file.");
702 System.out.println("Format identified as " + idformat
703 + "and expected as " + format);
705 if (idformat.equals(format))
709 System.out.println("Protocol identified as " + protocol);
718 .println("File deemed not accessible via " + protocol);
723 } catch (Exception e)
727 System.err.println("File deemed not accessible via " + protocol);