2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3 * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, 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, 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",
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;
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 //if (contient de l'ARN)
228 System.out.println(inFile); //donne le path
230 //new URL = http://paradise-ibmc.u-strasbg.fr/webservices/annotate3d?data=inFile;
231 //afile = new RnamlFile(inFile, type);
234 afile = new MCview.PDBfile(inFile, type);
237 else if (format.equals("STH"))
239 afile = new StockholmFile(inFile, type);
241 else if (format.equals("SimpleBLAST"))
243 afile = new SimpleBlastFile(inFile, type);
245 else if (format.equals("RNAML"))
247 afile = new RnamlFile(inFile, type);
250 Alignment al = new Alignment(afile.getSeqsAsArray());
252 afile.addAnnotations(al);
255 } catch (Exception e)
258 System.err.println("Failed to read alignment using the '" + format
259 + "' reader.\n" + e);
261 if (e.getMessage() != null
262 && e.getMessage().startsWith(INVALID_CHARACTERS))
264 throw new java.io.IOException(e.getMessage());
267 // Finally test if the user has pasted just the sequence, no id
268 if (type.equalsIgnoreCase("Paste"))
272 // Possible sequence is just residues with no label
273 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
274 Alignment al = new Alignment(afile.getSeqsAsArray());
275 afile.addAnnotations(al);
278 } catch (Exception ex)
280 if (ex.toString().startsWith(INVALID_CHARACTERS))
282 throw new java.io.IOException(e.getMessage());
285 ex.printStackTrace();
289 // If we get to this stage, the format was not supported
290 throw new java.io.IOException(SUPPORTED_FORMATS);
295 * Constructs the correct filetype parser for an already open datasource
298 * an existing datasource
300 * File format of data that will be provided by datasource
302 * @return DOCUMENT ME!
304 public Alignment readFromFile(FileParse source, String format)
305 throws java.io.IOException
307 // TODO: generalise mapping between format string and io. class instances
308 // using Constructor.invoke reflection
309 // This is exactly the same as the readFile method except we substitute
310 // 'inFile, type' with 'source'
311 this.inFile = source.getInFile();
312 String type = source.type;
315 if (format.equals("FASTA"))
317 afile = new FastaFile(source);
319 else if (format.equals("MSF"))
321 afile = new MSFfile(source);
323 else if (format.equals("PileUp"))
325 afile = new PileUpfile(source);
327 else if (format.equals("CLUSTAL"))
329 afile = new ClustalFile(source);
331 else if (format.equals("BLC"))
333 afile = new BLCFile(source);
335 else if (format.equals("PIR"))
337 afile = new PIRFile(source);
339 else if (format.equals("PFAM"))
341 afile = new PfamFile(source);
343 else if (format.equals("JnetFile"))
345 afile = new JPredFile(source);
346 ((JPredFile) afile).removeNonSequences();
348 else if (format.equals("PDB"))
350 afile = new MCview.PDBfile(source);
352 else if (format.equals("STH"))
354 afile = new StockholmFile(source);
356 else if (format.equals("RNAML"))
358 afile = new RnamlFile(source);
360 else if (format.equals("SimpleBLAST"))
362 afile = new SimpleBlastFile(source);
365 Alignment al = new Alignment(afile.getSeqsAsArray());
367 afile.addAnnotations(al);
370 } catch (Exception e)
373 System.err.println("Failed to read alignment using the '" + format
374 + "' reader.\n" + e);
376 if (e.getMessage() != null
377 && e.getMessage().startsWith(INVALID_CHARACTERS))
379 throw new java.io.IOException(e.getMessage());
382 // Finally test if the user has pasted just the sequence, no id
383 if (type.equalsIgnoreCase("Paste"))
387 // Possible sequence is just residues with no label
388 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
389 Alignment al = new Alignment(afile.getSeqsAsArray());
390 afile.addAnnotations(al);
393 } catch (Exception ex)
395 if (ex.toString().startsWith(INVALID_CHARACTERS))
397 throw new java.io.IOException(e.getMessage());
400 ex.printStackTrace();
404 // If we get to this stage, the format was not supported
405 throw new java.io.IOException(SUPPORTED_FORMATS);
410 * Construct an output class for an alignment in a particular filetype TODO:
411 * allow caller to detect errors and warnings encountered when generating
415 * string name of alignment format
417 * the alignment to be written out
419 * passed to AlnFile class controls whether /START-END is added to
422 * @return alignment flat file contents
424 public String formatSequences(String format, AlignmentI alignment,
429 AlignFile afile = null;
431 if (format.equalsIgnoreCase("FASTA"))
433 afile = new FastaFile();
435 else if (format.equalsIgnoreCase("MSF"))
437 afile = new MSFfile();
439 else if (format.equalsIgnoreCase("PileUp"))
441 afile = new PileUpfile();
443 else if (format.equalsIgnoreCase("CLUSTAL"))
445 afile = new ClustalFile();
447 else if (format.equalsIgnoreCase("BLC"))
449 afile = new BLCFile();
451 else if (format.equalsIgnoreCase("PIR"))
453 afile = new PIRFile();
455 else if (format.equalsIgnoreCase("PFAM"))
457 afile = new PfamFile();
459 else if (format.equalsIgnoreCase("STH"))
461 afile = new StockholmFile();
463 else if (format.equalsIgnoreCase("AMSA"))
465 afile = new AMSAFile(alignment);
467 else if (format.equalsIgnoreCase("RNAML"))
469 afile = new RnamlFile();
475 "Implementation error: Unknown file format string");
477 afile.setNewlineString(newline);
478 afile.addJVSuffix(jvsuffix);
480 afile.setSeqs(alignment.getSequencesArray());
482 String afileresp = afile.print();
483 if (afile.hasWarningMessage())
485 System.err.println("Warning raised when writing as " + format
486 + " : " + afile.getWarningMessage());
489 } catch (Exception e)
491 System.err.println("Failed to write alignment as a '" + format
499 public static String checkProtocol(String file)
501 String protocol = FILE;
502 String ft = file.toLowerCase().trim();
503 if (ft.indexOf("http:") ==0 || ft.indexOf("https:") ==0 || ft.indexOf("file:") == 0)
510 public static void main(String[] args)
513 while (i < args.length)
515 File f = new File(args[i]);
520 System.out.println("Reading file: " + f);
521 AppletFormatAdapter afa = new AppletFormatAdapter();
522 Runtime r = Runtime.getRuntime();
524 long memf = -r.totalMemory() + r.freeMemory();
525 long t1 = -System.currentTimeMillis();
526 Alignment al = afa.readFile(args[i], FILE,
527 new IdentifyFile().Identify(args[i], FILE));
528 t1 += System.currentTimeMillis();
530 memf += r.totalMemory() - r.freeMemory();
533 System.out.println("Alignment contains " + al.getHeight()
534 + " sequences and " + al.getWidth() + " columns.");
537 System.out.println(new AppletFormatAdapter().formatSequences(
539 } catch (Exception e)
542 .println("Couln't format the alignment for output as a FASTA file.");
543 e.printStackTrace(System.err);
548 System.out.println("Couldn't read alignment");
550 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
552 .println("Difference between free memory now and before is "
553 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
555 } catch (Exception e)
557 System.err.println("Exception when dealing with " + i
558 + "'th argument: " + args[i] + "\n" + e);
563 System.err.println("Ignoring argument '" + args[i] + "' (" + i
564 + "'th)- not a readable file.");
571 * try to discover how to access the given file as a valid datasource that
572 * will be identified as the given type.
576 * @return protocol that yields the data parsable as the given type
578 public static String resolveProtocol(String file, String format)
580 return resolveProtocol(file, format, false);
583 public static String resolveProtocol(String file, String format,
586 // TODO: test thoroughly!
587 String protocol = null;
590 System.out.println("resolving datasource started with:\n>>file\n"
591 + file + ">>endfile");
594 // This might throw a security exception in certain browsers
595 // Netscape Communicator for instance.
599 InputStream is = System.getSecurityManager().getClass()
600 .getResourceAsStream("/" + file);
608 System.err.println("Resource '" + file + "' was "
609 + (rtn ? "" : "not") + " located by classloader.");
614 protocol = AppletFormatAdapter.CLASSLOADER;
617 } catch (Exception ex)
620 .println("Exception checking resources: " + file + " " + ex);
623 if (file.indexOf("://") > -1)
625 protocol = AppletFormatAdapter.URL;
629 // skipping codebase prepend check.
630 protocol = AppletFormatAdapter.FILE;
637 System.out.println("Trying to get contents of resource as "
640 fp = new FileParse(file, protocol);
649 System.out.println("Successful.");
652 } catch (Exception e)
656 System.err.println("Exception when accessing content: " + e);
664 System.out.println("Accessing as paste.");
666 protocol = AppletFormatAdapter.PASTE;
670 fp = new FileParse(file, protocol);
675 } catch (Exception e)
677 System.err.println("Failed to access content as paste!");
686 if (format == null || format.length() == 0)
694 String idformat = new jalview.io.IdentifyFile().Identify(file,
696 if (idformat == null)
700 System.out.println("Format not identified. Inaccessible file.");
706 System.out.println("Format identified as " + idformat
707 + "and expected as " + format);
709 if (idformat.equals(format))
713 System.out.println("Protocol identified as " + protocol);
722 .println("File deemed not accessible via " + protocol);
727 } catch (Exception e)
731 System.err.println("File deemed not accessible via " + protocol);