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" }; // , "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", "STH",
53 * List of extensions corresponding to file format types in WRITABLE_FNAMES
54 * that are writable by the application.
56 public static final String[] WRITABLE_EXTENSIONS = new String[]
57 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jvp",
61 * List of writable formats by the application. Order must correspond with the
62 * WRITABLE_EXTENSIONS list of formats.
64 public static final String[] WRITABLE_FNAMES = new String[]
65 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
69 * List of readable format file extensions by application in order
70 * corresponding to READABLE_FNAMES
72 public static final String[] READABLE_EXTENSIONS = new String[]
73 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar,jvp",
80 * List of readable formats by application in order corresponding to
83 public static final String[] READABLE_FNAMES = new String[]
84 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
90 public static String INVALID_CHARACTERS = "Contains invalid characters";
92 // TODO: make these messages dynamic
93 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
94 + prettyPrint(READABLE_FORMATS);
99 * @return grammatically correct(ish) list consisting of els elements.
101 public static String prettyPrint(String[] els)
103 StringBuffer list = new StringBuffer();
104 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
109 list.append(" and " + els[els.length - 1] + ".");
110 return list.toString();
113 public static String FILE = "File";
115 public static String URL = "URL";
117 public static String PASTE = "Paste";
119 public static String CLASSLOADER = "ClassLoader";
121 AlignFile afile = null;
126 * character used to write newlines
128 protected String newline = System.getProperty("line.separator");
130 public void setNewlineString(String nl)
135 public String getNewlineString()
141 * check that this format is valid for reading
144 * a format string to be compared with READABLE_FORMATS
145 * @return true if format is readable
147 public static final boolean isValidFormat(String format)
149 return isValidFormat(format, false);
153 * validate format is valid for IO
156 * a format string to be compared with either READABLE_FORMATS or
159 * when true, format is checked for containment in WRITEABLE_FORMATS
160 * @return true if format is valid
162 public static final boolean isValidFormat(String format,
165 boolean valid = false;
166 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
168 for (int i = 0; i < format_list.length; i++)
170 if (format_list[i].equalsIgnoreCase(format))
180 * Constructs the correct filetype parser for a characterised datasource
187 * File format of data provided by datasource
189 * @return DOCUMENT ME!
191 public Alignment readFile(String inFile, String type, String format)
192 throws java.io.IOException
194 // TODO: generalise mapping between format string and io. class instances
195 // using Constructor.invoke reflection
196 this.inFile = inFile;
199 if (format.equals("FASTA"))
201 afile = new FastaFile(inFile, type);
203 else if (format.equals("MSF"))
205 afile = new MSFfile(inFile, type);
207 else if (format.equals("PileUp"))
209 afile = new PileUpfile(inFile, type);
211 else if (format.equals("CLUSTAL"))
213 afile = new ClustalFile(inFile, type);
215 else if (format.equals("BLC"))
217 afile = new BLCFile(inFile, type);
219 else if (format.equals("PIR"))
221 afile = new PIRFile(inFile, type);
223 else if (format.equals("PFAM"))
225 afile = new PfamFile(inFile, type);
227 else if (format.equals("JnetFile"))
229 afile = new JPredFile(inFile, type);
230 ((JPredFile) afile).removeNonSequences();
232 else if (format.equals("PDB"))
234 afile = new MCview.PDBfile(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);
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("SimpleBLAST"))
353 afile = new SimpleBlastFile(source);
356 Alignment al = new Alignment(afile.getSeqsAsArray());
358 afile.addAnnotations(al);
361 } catch (Exception e)
364 System.err.println("Failed to read alignment using the '" + format
365 + "' reader.\n" + e);
367 if (e.getMessage() != null
368 && e.getMessage().startsWith(INVALID_CHARACTERS))
370 throw new java.io.IOException(e.getMessage());
373 // Finally test if the user has pasted just the sequence, no id
374 if (type.equalsIgnoreCase("Paste"))
378 // Possible sequence is just residues with no label
379 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
380 Alignment al = new Alignment(afile.getSeqsAsArray());
381 afile.addAnnotations(al);
384 } catch (Exception ex)
386 if (ex.toString().startsWith(INVALID_CHARACTERS))
388 throw new java.io.IOException(e.getMessage());
391 ex.printStackTrace();
395 // If we get to this stage, the format was not supported
396 throw new java.io.IOException(SUPPORTED_FORMATS);
401 * Construct an output class for an alignment in a particular filetype TODO:
402 * allow caller to detect errors and warnings encountered when generating
406 * string name of alignment format
408 * the alignment to be written out
410 * passed to AlnFile class controls whether /START-END is added to
413 * @return alignment flat file contents
415 public String formatSequences(String format, AlignmentI alignment,
420 AlignFile afile = null;
422 if (format.equalsIgnoreCase("FASTA"))
424 afile = new FastaFile();
426 else if (format.equalsIgnoreCase("MSF"))
428 afile = new MSFfile();
430 else if (format.equalsIgnoreCase("PileUp"))
432 afile = new PileUpfile();
434 else if (format.equalsIgnoreCase("CLUSTAL"))
436 afile = new ClustalFile();
438 else if (format.equalsIgnoreCase("BLC"))
440 afile = new BLCFile();
442 else if (format.equalsIgnoreCase("PIR"))
444 afile = new PIRFile();
446 else if (format.equalsIgnoreCase("PFAM"))
448 afile = new PfamFile();
450 else if (format.equalsIgnoreCase("STH"))
452 afile = new StockholmFile(alignment);
454 else if (format.equalsIgnoreCase("AMSA"))
456 afile = new AMSAFile(alignment);
461 "Implementation error: Unknown file format string");
463 afile.setNewlineString(newline);
464 afile.addJVSuffix(jvsuffix);
466 afile.setSeqs(alignment.getSequencesArray());
468 String afileresp = afile.print();
469 if (afile.hasWarningMessage())
471 System.err.println("Warning raised when writing as " + format
472 + " : " + afile.getWarningMessage());
475 } catch (Exception e)
477 System.err.println("Failed to write alignment as a '" + format
485 public static String checkProtocol(String file)
487 String protocol = FILE;
488 String ft = file.toLowerCase().trim();
489 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
490 || ft.indexOf("file:") == 0)
497 public static void main(String[] args)
500 while (i < args.length)
502 File f = new File(args[i]);
507 System.out.println("Reading file: " + f);
508 AppletFormatAdapter afa = new AppletFormatAdapter();
509 String fName = f.getName();
511 Runtime r = Runtime.getRuntime();
513 long memf = -r.totalMemory() + r.freeMemory();
514 long t1 = -System.currentTimeMillis();
515 Alignment al = afa.readFile(args[i], FILE,
516 new IdentifyFile().Identify(args[i], FILE));
517 t1 += System.currentTimeMillis();
519 memf += r.totalMemory() - r.freeMemory();
522 System.out.println("Alignment contains " + al.getHeight()
523 + " sequences and " + al.getWidth() + " columns.");
526 System.out.println(new AppletFormatAdapter()
527 .formatSequences("FASTA", al, true));
528 } catch (Exception e)
531 .println("Couln't format the alignment for output as a FASTA file.");
532 e.printStackTrace(System.err);
537 System.out.println("Couldn't read alignment");
539 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
541 .println("Difference between free memory now and before is "
542 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
544 } catch (Exception e)
546 System.err.println("Exception when dealing with " + i
547 + "'th argument: " + args[i] + "\n" + e);
553 System.err.println("Ignoring argument '" + args[i] + "' (" + i
554 + "'th)- not a readable file.");
561 * try to discover how to access the given file as a valid datasource that
562 * will be identified as the given type.
566 * @return protocol that yields the data parsable as the given type
568 public static String resolveProtocol(String file, String format)
570 return resolveProtocol(file, format, false);
573 public static String resolveProtocol(String file, String format,
576 // TODO: test thoroughly!
577 String protocol = null;
580 System.out.println("resolving datasource started with:\n>>file\n"
581 + file + ">>endfile");
584 // This might throw a security exception in certain browsers
585 // Netscape Communicator for instance.
589 InputStream is = System.getSecurityManager().getClass()
590 .getResourceAsStream("/" + file);
598 System.err.println("Resource '" + file + "' was "
599 + (rtn ? "" : "not") + " located by classloader.");
604 protocol = AppletFormatAdapter.CLASSLOADER;
607 } catch (Exception ex)
610 .println("Exception checking resources: " + file + " " + ex);
613 if (file.indexOf("://") > -1)
615 protocol = AppletFormatAdapter.URL;
619 // skipping codebase prepend check.
620 protocol = AppletFormatAdapter.FILE;
627 System.out.println("Trying to get contents of resource as "
630 fp = new FileParse(file, protocol);
639 System.out.println("Successful.");
642 } catch (Exception e)
646 System.err.println("Exception when accessing content: " + e);
654 System.out.println("Accessing as paste.");
656 protocol = AppletFormatAdapter.PASTE;
660 fp = new FileParse(file, protocol);
665 } catch (Exception e)
667 System.err.println("Failed to access content as paste!");
676 if (format == null || format.length() == 0)
684 String idformat = new jalview.io.IdentifyFile().Identify(file,
686 if (idformat == null)
690 System.out.println("Format not identified. Inaccessible file.");
696 System.out.println("Format identified as " + idformat
697 + "and expected as " + format);
699 if (idformat.equals(format))
703 System.out.println("Protocol identified as " + protocol);
712 .println("File deemed not accessible via " + protocol);
717 } catch (Exception e)
721 System.err.println("File deemed not accessible via " + protocol);