2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, 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" }; // , "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, 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, fasta, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar",
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",
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;
121 * character used to write newlines
123 protected String newline = System.getProperty("line.separator");
124 public void setNewlineString(String nl)
128 public String getNewlineString()
133 * check that this format is valid for reading
136 * a format string to be compared with READABLE_FORMATS
137 * @return true if format is readable
139 public static final boolean isValidFormat(String format)
141 return isValidFormat(format, false);
145 * validate format is valid for IO
148 * a format string to be compared with either READABLE_FORMATS or
151 * when true, format is checked for containment in WRITEABLE_FORMATS
152 * @return true if format is valid
154 public static final boolean isValidFormat(String format,
157 boolean valid = false;
158 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
160 for (int i = 0; i < format_list.length; i++)
162 if (format_list[i].equalsIgnoreCase(format))
172 * Constructs the correct filetype parser for a characterised datasource
179 * File format of data provided by datasource
181 * @return DOCUMENT ME!
183 public Alignment readFile(String inFile, String type, String format)
184 throws java.io.IOException
186 // TODO: generalise mapping between format string and io. class instances
187 // using Constructor.invoke reflection
188 this.inFile = inFile;
191 if (format.equals("FASTA"))
193 afile = new FastaFile(inFile, type);
195 else if (format.equals("MSF"))
197 afile = new MSFfile(inFile, type);
199 else if (format.equals("PileUp"))
201 afile = new PileUpfile(inFile, type);
203 else if (format.equals("CLUSTAL"))
205 afile = new ClustalFile(inFile, type);
207 else if (format.equals("BLC"))
209 afile = new BLCFile(inFile, type);
211 else if (format.equals("PIR"))
213 afile = new PIRFile(inFile, type);
215 else if (format.equals("PFAM"))
217 afile = new PfamFile(inFile, type);
219 else if (format.equals("JnetFile"))
221 afile = new JPredFile(inFile, type);
222 ((JPredFile) afile).removeNonSequences();
224 else if (format.equals("PDB"))
226 afile = new MCview.PDBfile(inFile, type);
228 else if (format.equals("STH"))
230 afile = new StockholmFile(inFile, type);
232 else if (format.equals("SimpleBLAST"))
234 afile = new SimpleBlastFile(inFile, type);
237 Alignment al = new Alignment(afile.getSeqsAsArray());
239 afile.addAnnotations(al);
242 } catch (Exception e)
245 System.err.println("Failed to read alignment using the '" + format
246 + "' reader.\n" + e);
248 if (e.getMessage() != null
249 && e.getMessage().startsWith(INVALID_CHARACTERS))
251 throw new java.io.IOException(e.getMessage());
254 // Finally test if the user has pasted just the sequence, no id
255 if (type.equalsIgnoreCase("Paste"))
259 // Possible sequence is just residues with no label
260 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
261 Alignment al = new Alignment(afile.getSeqsAsArray());
262 afile.addAnnotations(al);
265 } catch (Exception ex)
267 if (ex.toString().startsWith(INVALID_CHARACTERS))
269 throw new java.io.IOException(e.getMessage());
272 ex.printStackTrace();
276 // If we get to this stage, the format was not supported
277 throw new java.io.IOException(SUPPORTED_FORMATS);
282 * Constructs the correct filetype parser for an already open datasource
285 * an existing datasource
287 * File format of data that will be provided by datasource
289 * @return DOCUMENT ME!
291 public Alignment readFromFile(FileParse source, String format)
292 throws java.io.IOException
294 // TODO: generalise mapping between format string and io. class instances
295 // using Constructor.invoke reflection
296 // This is exactly the same as the readFile method except we substitute
297 // 'inFile, type' with 'source'
298 this.inFile = source.getInFile();
299 String type = source.type;
302 if (format.equals("FASTA"))
304 afile = new FastaFile(source);
306 else if (format.equals("MSF"))
308 afile = new MSFfile(source);
310 else if (format.equals("PileUp"))
312 afile = new PileUpfile(source);
314 else if (format.equals("CLUSTAL"))
316 afile = new ClustalFile(source);
318 else if (format.equals("BLC"))
320 afile = new BLCFile(source);
322 else if (format.equals("PIR"))
324 afile = new PIRFile(source);
326 else if (format.equals("PFAM"))
328 afile = new PfamFile(source);
330 else if (format.equals("JnetFile"))
332 afile = new JPredFile(source);
333 ((JPredFile) afile).removeNonSequences();
335 else if (format.equals("PDB"))
337 afile = new MCview.PDBfile(source);
339 else if (format.equals("STH"))
341 afile = new StockholmFile(source);
343 else if (format.equals("SimpleBLAST"))
345 afile = new SimpleBlastFile(source);
348 Alignment al = new Alignment(afile.getSeqsAsArray());
350 afile.addAnnotations(al);
353 } catch (Exception e)
356 System.err.println("Failed to read alignment using the '" + format
357 + "' reader.\n" + e);
359 if (e.getMessage() != null
360 && e.getMessage().startsWith(INVALID_CHARACTERS))
362 throw new java.io.IOException(e.getMessage());
365 // Finally test if the user has pasted just the sequence, no id
366 if (type.equalsIgnoreCase("Paste"))
370 // Possible sequence is just residues with no label
371 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
372 Alignment al = new Alignment(afile.getSeqsAsArray());
373 afile.addAnnotations(al);
376 } catch (Exception ex)
378 if (ex.toString().startsWith(INVALID_CHARACTERS))
380 throw new java.io.IOException(e.getMessage());
383 ex.printStackTrace();
387 // If we get to this stage, the format was not supported
388 throw new java.io.IOException(SUPPORTED_FORMATS);
393 * Construct an output class for an alignment in a particular filetype TODO:
394 * allow caller to detect errors and warnings encountered when generating
398 * string name of alignment format
400 * the alignment to be written out
402 * passed to AlnFile class controls whether /START-END is added to
405 * @return alignment flat file contents
407 public String formatSequences(String format, AlignmentI alignment,
412 AlignFile afile = null;
414 if (format.equalsIgnoreCase("FASTA"))
416 afile = new FastaFile();
418 else if (format.equalsIgnoreCase("MSF"))
420 afile = new MSFfile();
422 else if (format.equalsIgnoreCase("PileUp"))
424 afile = new PileUpfile();
426 else if (format.equalsIgnoreCase("CLUSTAL"))
428 afile = new ClustalFile();
430 else if (format.equalsIgnoreCase("BLC"))
432 afile = new BLCFile();
434 else if (format.equalsIgnoreCase("PIR"))
436 afile = new PIRFile();
438 else if (format.equalsIgnoreCase("PFAM"))
440 afile = new PfamFile();
442 else if (format.equalsIgnoreCase("STH"))
444 afile = new StockholmFile();
446 else if (format.equalsIgnoreCase("AMSA"))
448 afile = new AMSAFile(alignment);
453 "Implementation error: Unknown file format string");
455 afile.setNewlineString(newline);
456 afile.addJVSuffix(jvsuffix);
458 afile.setSeqs(alignment.getSequencesArray());
460 String afileresp = afile.print();
461 if (afile.hasWarningMessage())
463 System.err.println("Warning raised when writing as " + format
464 + " : " + afile.getWarningMessage());
467 } catch (Exception e)
469 System.err.println("Failed to write alignment as a '" + format
477 public static String checkProtocol(String file)
479 String protocol = FILE;
480 String ft = file.toLowerCase().trim();
481 if (ft.indexOf("http:") ==0 || ft.indexOf("https:") ==0 || ft.indexOf("file:") == 0)
488 public static void main(String[] args)
491 while (i < args.length)
493 File f = new File(args[i]);
498 System.out.println("Reading file: " + f);
499 AppletFormatAdapter afa = new AppletFormatAdapter();
500 Runtime r = Runtime.getRuntime();
502 long memf = -r.totalMemory() + r.freeMemory();
503 long t1 = -System.currentTimeMillis();
504 Alignment al = afa.readFile(args[i], FILE,
505 new IdentifyFile().Identify(args[i], FILE));
506 t1 += System.currentTimeMillis();
508 memf += r.totalMemory() - r.freeMemory();
511 System.out.println("Alignment contains " + al.getHeight()
512 + " sequences and " + al.getWidth() + " columns.");
515 System.out.println(new AppletFormatAdapter().formatSequences(
517 } catch (Exception e)
520 .println("Couln't format the alignment for output as a FASTA file.");
521 e.printStackTrace(System.err);
526 System.out.println("Couldn't read alignment");
528 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
530 .println("Difference between free memory now and before is "
531 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
533 } catch (Exception e)
535 System.err.println("Exception when dealing with " + i
536 + "'th argument: " + args[i] + "\n" + e);
541 System.err.println("Ignoring argument '" + args[i] + "' (" + i
542 + "'th)- not a readable file.");
549 * try to discover how to access the given file as a valid datasource that
550 * will be identified as the given type.
554 * @return protocol that yields the data parsable as the given type
556 public static String resolveProtocol(String file, String format)
558 return resolveProtocol(file, format, false);
561 public static String resolveProtocol(String file, String format,
564 // TODO: test thoroughly!
565 String protocol = null;
568 System.out.println("resolving datasource started with:\n>>file\n"
569 + file + ">>endfile");
572 // This might throw a security exception in certain browsers
573 // Netscape Communicator for instance.
577 InputStream is = System.getSecurityManager().getClass()
578 .getResourceAsStream("/" + file);
586 System.err.println("Resource '" + file + "' was "
587 + (rtn ? "" : "not") + " located by classloader.");
592 protocol = AppletFormatAdapter.CLASSLOADER;
595 } catch (Exception ex)
598 .println("Exception checking resources: " + file + " " + ex);
601 if (file.indexOf("://") > -1)
603 protocol = AppletFormatAdapter.URL;
607 // skipping codebase prepend check.
608 protocol = AppletFormatAdapter.FILE;
615 System.out.println("Trying to get contents of resource as "
618 fp = new FileParse(file, protocol);
627 System.out.println("Successful.");
630 } catch (Exception e)
634 System.err.println("Exception when accessing content: " + e);
642 System.out.println("Accessing as paste.");
644 protocol = AppletFormatAdapter.PASTE;
648 fp = new FileParse(file, protocol);
653 } catch (Exception e)
655 System.err.println("Failed to access content as paste!");
664 if (format == null || format.length() == 0)
672 String idformat = new jalview.io.IdentifyFile().Identify(file,
674 if (idformat == null)
678 System.out.println("Format not identified. Inaccessible file.");
684 System.out.println("Format identified as " + idformat
685 + "and expected as " + format);
687 if (idformat.equals(format))
691 System.out.println("Protocol identified as " + protocol);
700 .println("File deemed not accessible via " + protocol);
705 } catch (Exception e)
709 System.err.println("File deemed not accessible via " + protocol);