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" }; // , "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", "STH",
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, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar",
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, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar",
79 * List of readable formats by application in order corresponding to
82 public static final String[] READABLE_FNAMES = new String[]
83 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
89 public static String INVALID_CHARACTERS = "Contains invalid characters";
91 // TODO: make these messages dynamic
92 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
93 + prettyPrint(READABLE_FORMATS);
98 * @return grammatically correct(ish) list consisting of els elements.
100 public static String prettyPrint(String[] els)
102 StringBuffer list = new StringBuffer();
103 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
108 list.append(" and " + els[els.length - 1] + ".");
109 return list.toString();
112 public static String FILE = "File";
114 public static String URL = "URL";
116 public static String PASTE = "Paste";
118 public static String CLASSLOADER = "ClassLoader";
120 AlignFile afile = null;
125 * character used to write newlines
127 protected String newline = System.getProperty("line.separator");
129 public void setNewlineString(String nl)
134 public String getNewlineString()
140 * check that this format is valid for reading
143 * a format string to be compared with READABLE_FORMATS
144 * @return true if format is readable
146 public static final boolean isValidFormat(String format)
148 return isValidFormat(format, false);
152 * validate format is valid for IO
155 * a format string to be compared with either READABLE_FORMATS or
158 * when true, format is checked for containment in WRITEABLE_FORMATS
159 * @return true if format is valid
161 public static final boolean isValidFormat(String format,
164 boolean valid = false;
165 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
167 for (int i = 0; i < format_list.length; i++)
169 if (format_list[i].equalsIgnoreCase(format))
179 * Constructs the correct filetype parser for a characterised datasource
186 * File format of data provided by datasource
188 * @return DOCUMENT ME!
190 public Alignment readFile(String inFile, String type, String format)
191 throws java.io.IOException
193 // TODO: generalise mapping between format string and io. class instances
194 // using Constructor.invoke reflection
195 this.inFile = inFile;
198 if (format.equals("FASTA"))
200 afile = new FastaFile(inFile, type);
202 else if (format.equals("MSF"))
204 afile = new MSFfile(inFile, type);
206 else if (format.equals("PileUp"))
208 afile = new PileUpfile(inFile, type);
210 else if (format.equals("CLUSTAL"))
212 afile = new ClustalFile(inFile, type);
214 else if (format.equals("BLC"))
216 afile = new BLCFile(inFile, type);
218 else if (format.equals("PIR"))
220 afile = new PIRFile(inFile, type);
222 else if (format.equals("PFAM"))
224 afile = new PfamFile(inFile, type);
226 else if (format.equals("JnetFile"))
228 afile = new JPredFile(inFile, type);
229 ((JPredFile) afile).removeNonSequences();
231 else if (format.equals("PDB"))
233 afile = new MCview.PDBfile(inFile, type);
235 else if (format.equals("STH"))
237 afile = new StockholmFile(inFile, type);
239 else if (format.equals("SimpleBLAST"))
241 afile = new SimpleBlastFile(inFile, type);
244 Alignment al = new Alignment(afile.getSeqsAsArray());
246 afile.addAnnotations(al);
249 } catch (Exception e)
252 System.err.println("Failed to read alignment using the '" + format
253 + "' reader.\n" + e);
255 if (e.getMessage() != null
256 && e.getMessage().startsWith(INVALID_CHARACTERS))
258 throw new java.io.IOException(e.getMessage());
261 // Finally test if the user has pasted just the sequence, no id
262 if (type.equalsIgnoreCase("Paste"))
266 // Possible sequence is just residues with no label
267 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
268 Alignment al = new Alignment(afile.getSeqsAsArray());
269 afile.addAnnotations(al);
272 } catch (Exception ex)
274 if (ex.toString().startsWith(INVALID_CHARACTERS))
276 throw new java.io.IOException(e.getMessage());
279 ex.printStackTrace();
283 // If we get to this stage, the format was not supported
284 throw new java.io.IOException(SUPPORTED_FORMATS);
289 * Constructs the correct filetype parser for an already open datasource
292 * an existing datasource
294 * File format of data that will be provided by datasource
296 * @return DOCUMENT ME!
298 public Alignment readFromFile(FileParse source, String format)
299 throws java.io.IOException
301 // TODO: generalise mapping between format string and io. class instances
302 // using Constructor.invoke reflection
303 // This is exactly the same as the readFile method except we substitute
304 // 'inFile, type' with 'source'
305 this.inFile = source.getInFile();
306 String type = source.type;
309 if (format.equals("FASTA"))
311 afile = new FastaFile(source);
313 else if (format.equals("MSF"))
315 afile = new MSFfile(source);
317 else if (format.equals("PileUp"))
319 afile = new PileUpfile(source);
321 else if (format.equals("CLUSTAL"))
323 afile = new ClustalFile(source);
325 else if (format.equals("BLC"))
327 afile = new BLCFile(source);
329 else if (format.equals("PIR"))
331 afile = new PIRFile(source);
333 else if (format.equals("PFAM"))
335 afile = new PfamFile(source);
337 else if (format.equals("JnetFile"))
339 afile = new JPredFile(source);
340 ((JPredFile) afile).removeNonSequences();
342 else if (format.equals("PDB"))
344 afile = new MCview.PDBfile(source);
346 else if (format.equals("STH"))
348 afile = new StockholmFile(source);
350 else if (format.equals("SimpleBLAST"))
352 afile = new SimpleBlastFile(source);
355 Alignment al = new Alignment(afile.getSeqsAsArray());
357 afile.addAnnotations(al);
360 } catch (Exception e)
363 System.err.println("Failed to read alignment using the '" + format
364 + "' reader.\n" + e);
366 if (e.getMessage() != null
367 && e.getMessage().startsWith(INVALID_CHARACTERS))
369 throw new java.io.IOException(e.getMessage());
372 // Finally test if the user has pasted just the sequence, no id
373 if (type.equalsIgnoreCase("Paste"))
377 // Possible sequence is just residues with no label
378 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
379 Alignment al = new Alignment(afile.getSeqsAsArray());
380 afile.addAnnotations(al);
383 } catch (Exception ex)
385 if (ex.toString().startsWith(INVALID_CHARACTERS))
387 throw new java.io.IOException(e.getMessage());
390 ex.printStackTrace();
394 // If we get to this stage, the format was not supported
395 throw new java.io.IOException(SUPPORTED_FORMATS);
400 * Construct an output class for an alignment in a particular filetype TODO:
401 * allow caller to detect errors and warnings encountered when generating
405 * string name of alignment format
407 * the alignment to be written out
409 * passed to AlnFile class controls whether /START-END is added to
412 * @return alignment flat file contents
414 public String formatSequences(String format, AlignmentI alignment,
419 AlignFile afile = null;
421 if (format.equalsIgnoreCase("FASTA"))
423 afile = new FastaFile();
425 else if (format.equalsIgnoreCase("MSF"))
427 afile = new MSFfile();
429 else if (format.equalsIgnoreCase("PileUp"))
431 afile = new PileUpfile();
433 else if (format.equalsIgnoreCase("CLUSTAL"))
435 afile = new ClustalFile();
437 else if (format.equalsIgnoreCase("BLC"))
439 afile = new BLCFile();
441 else if (format.equalsIgnoreCase("PIR"))
443 afile = new PIRFile();
445 else if (format.equalsIgnoreCase("PFAM"))
447 afile = new PfamFile();
449 else if (format.equalsIgnoreCase("STH"))
451 afile = new StockholmFile(alignment);
453 else if (format.equalsIgnoreCase("AMSA"))
455 afile = new AMSAFile(alignment);
460 "Implementation error: Unknown file format string");
462 afile.setNewlineString(newline);
463 afile.addJVSuffix(jvsuffix);
465 afile.setSeqs(alignment.getSequencesArray());
467 String afileresp = afile.print();
468 if (afile.hasWarningMessage())
470 System.err.println("Warning raised when writing as " + format
471 + " : " + afile.getWarningMessage());
474 } catch (Exception e)
476 System.err.println("Failed to write alignment as a '" + format
484 public static String checkProtocol(String file)
486 String protocol = FILE;
487 String ft = file.toLowerCase().trim();
488 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
489 || ft.indexOf("file:") == 0)
496 public static void main(String[] args)
499 while (i < args.length)
501 File f = new File(args[i]);
506 System.out.println("Reading file: " + f);
507 AppletFormatAdapter afa = new AppletFormatAdapter();
508 String fName = f.getName();
510 Runtime r = Runtime.getRuntime();
512 long memf = -r.totalMemory() + r.freeMemory();
513 long t1 = -System.currentTimeMillis();
514 Alignment al = afa.readFile(args[i], FILE,
515 new IdentifyFile().Identify(args[i], FILE));
516 t1 += System.currentTimeMillis();
518 memf += r.totalMemory() - r.freeMemory();
521 System.out.println("Alignment contains " + al.getHeight()
522 + " sequences and " + al.getWidth() + " columns.");
525 System.out.println(new AppletFormatAdapter()
526 .formatSequences("FASTA", al, true));
527 } catch (Exception e)
530 .println("Couln't format the alignment for output as a FASTA file.");
531 e.printStackTrace(System.err);
536 System.out.println("Couldn't read alignment");
538 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
540 .println("Difference between free memory now and before is "
541 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
543 } catch (Exception e)
545 System.err.println("Exception when dealing with " + i
546 + "'th argument: " + args[i] + "\n" + e);
552 System.err.println("Ignoring argument '" + args[i] + "' (" + i
553 + "'th)- not a readable file.");
560 * try to discover how to access the given file as a valid datasource that
561 * will be identified as the given type.
565 * @return protocol that yields the data parsable as the given type
567 public static String resolveProtocol(String file, String format)
569 return resolveProtocol(file, format, false);
572 public static String resolveProtocol(String file, String format,
575 // TODO: test thoroughly!
576 String protocol = null;
579 System.out.println("resolving datasource started with:\n>>file\n"
580 + file + ">>endfile");
583 // This might throw a security exception in certain browsers
584 // Netscape Communicator for instance.
588 InputStream is = System.getSecurityManager().getClass()
589 .getResourceAsStream("/" + file);
597 System.err.println("Resource '" + file + "' was "
598 + (rtn ? "" : "not") + " located by classloader.");
603 protocol = AppletFormatAdapter.CLASSLOADER;
606 } catch (Exception ex)
609 .println("Exception checking resources: " + file + " " + ex);
612 if (file.indexOf("://") > -1)
614 protocol = AppletFormatAdapter.URL;
618 // skipping codebase prepend check.
619 protocol = AppletFormatAdapter.FILE;
626 System.out.println("Trying to get contents of resource as "
629 fp = new FileParse(file, protocol);
638 System.out.println("Successful.");
641 } catch (Exception e)
645 System.err.println("Exception when accessing content: " + e);
653 System.out.println("Accessing as paste.");
655 protocol = AppletFormatAdapter.PASTE;
659 fp = new FileParse(file, protocol);
664 } catch (Exception e)
666 System.err.println("Failed to access content as paste!");
675 if (format == null || format.length() == 0)
683 String idformat = new jalview.io.IdentifyFile().Identify(file,
685 if (idformat == null)
689 System.out.println("Format not identified. Inaccessible file.");
695 System.out.println("Format identified as " + idformat
696 + "and expected as " + format);
698 if (idformat.equals(format))
702 System.out.println("Protocol identified as " + protocol);
711 .println("File deemed not accessible via " + protocol);
716 } catch (Exception e)
720 System.err.println("File deemed not accessible via " + protocol);