2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
24 import java.io.InputStream;
25 import java.util.List;
27 import jalview.api.AlignViewportI;
28 import jalview.datamodel.*;
29 import jalview.util.MessageManager;
32 * A low level class for alignment and feature IO with alignment formatting
33 * methods used by both applet and application for generating flat alignment
34 * files. It also holds the lists of magic format names that the applet and
35 * application will allow the user to read or write files with.
40 public class AppletFormatAdapter
43 * List of valid format strings used in the isValidFormat method
45 public static final String[] READABLE_FORMATS = new String[]
46 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
47 "PDB", "JnetFile", "RNAML" }; // , "SimpleBLAST" };
50 * List of valid format strings for use by callers of the formatSequences
53 public static final String[] WRITEABLE_FORMATS = new String[]
54 { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA", "STH" };
57 * List of extensions corresponding to file format types in WRITABLE_FNAMES
58 * that are writable by the application.
60 public static final String[] WRITABLE_EXTENSIONS = new String[]
61 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
62 "jvp", "sto,stk", "jar" };
65 * List of writable formats by the application. Order must correspond with the
66 * WRITABLE_EXTENSIONS list of formats.
68 public static final String[] WRITABLE_FNAMES = new String[]
69 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
73 * List of readable format file extensions by application in order
74 * corresponding to READABLE_FNAMES
76 public static final String[] READABLE_EXTENSIONS = new String[]
77 { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
78 "jar,jvp", "sto,stk", "xml,rnaml" }; // ".blast"
81 * List of readable formats by application in order corresponding to
84 public static final String[] READABLE_FNAMES = new String[]
85 { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
86 "Stockholm", "RNAML" };// ,
91 public static String INVALID_CHARACTERS = "Contains invalid characters";
93 // TODO: make these messages dynamic
94 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
95 + prettyPrint(READABLE_FORMATS);
100 * @return grammatically correct(ish) list consisting of els elements.
102 public static String prettyPrint(String[] els)
104 StringBuffer list = new StringBuffer();
105 for (int i = 0, iSize = els.length - 1; i < iSize; i++)
110 list.append(" and " + els[els.length - 1] + ".");
111 return list.toString();
114 public static String FILE = "File";
116 public static String URL = "URL";
118 public static String PASTE = "Paste";
120 public static String CLASSLOADER = "ClassLoader";
122 AlignFile afile = null;
127 * character used to write newlines
129 protected String newline = System.getProperty("line.separator");
131 public void setNewlineString(String nl)
136 public String getNewlineString()
142 * check that this format is valid for reading
145 * a format string to be compared with READABLE_FORMATS
146 * @return true if format is readable
148 public static final boolean isValidFormat(String format)
150 return isValidFormat(format, false);
154 * validate format is valid for IO
157 * a format string to be compared with either READABLE_FORMATS or
160 * when true, format is checked for containment in WRITEABLE_FORMATS
161 * @return true if format is valid
163 public static final boolean isValidFormat(String format,
166 boolean valid = false;
167 String[] format_list = (forwriting) ? WRITEABLE_FORMATS
169 for (int i = 0; i < format_list.length; i++)
171 if (format_list[i].equalsIgnoreCase(format))
181 * Constructs the correct filetype parser for a characterised datasource
188 * File format of data provided by datasource
190 * @return DOCUMENT ME!
192 public Alignment readFile(String inFile, String type, String format)
193 throws java.io.IOException
195 // TODO: generalise mapping between format string and io. class instances
196 // using Constructor.invoke reflection
197 this.inFile = inFile;
200 if (format.equals("FASTA"))
202 afile = new FastaFile(inFile, type);
204 else if (format.equals("MSF"))
206 afile = new MSFfile(inFile, type);
208 else if (format.equals("PileUp"))
210 afile = new PileUpfile(inFile, type);
212 else if (format.equals("CLUSTAL"))
214 afile = new ClustalFile(inFile, type);
216 else if (format.equals("BLC"))
218 afile = new BLCFile(inFile, type);
220 else if (format.equals("PIR"))
222 afile = new PIRFile(inFile, type);
224 else if (format.equals("PFAM"))
226 afile = new PfamFile(inFile, type);
228 else if (format.equals("JnetFile"))
230 afile = new JPredFile(inFile, type);
231 ((JPredFile) afile).removeNonSequences();
233 else if (format.equals("PDB"))
235 afile = new MCview.PDBfile(inFile, type);
236 // Uncomment to test Jmol data based PDB processing: JAL-1213
237 // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
239 else if (format.equals("STH"))
241 afile = new StockholmFile(inFile, type);
243 else if (format.equals("SimpleBLAST"))
245 afile = new SimpleBlastFile(inFile, type);
247 else if (format.equals("RNAML"))
249 afile = new RnamlFile(inFile, type);
252 Alignment al = new Alignment(afile.getSeqsAsArray());
254 afile.addAnnotations(al);
257 } catch (Exception e)
260 System.err.println("Failed to read alignment using the '" + format
261 + "' reader.\n" + e);
263 if (e.getMessage() != null
264 && e.getMessage().startsWith(INVALID_CHARACTERS))
266 throw new java.io.IOException(e.getMessage());
269 // Finally test if the user has pasted just the sequence, no id
270 if (type.equalsIgnoreCase("Paste"))
274 // Possible sequence is just residues with no label
275 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
276 Alignment al = new Alignment(afile.getSeqsAsArray());
277 afile.addAnnotations(al);
280 } catch (Exception ex)
282 if (ex.toString().startsWith(INVALID_CHARACTERS))
284 throw new java.io.IOException(e.getMessage());
287 ex.printStackTrace();
291 // If we get to this stage, the format was not supported
292 throw new java.io.IOException(SUPPORTED_FORMATS);
297 * Constructs the correct filetype parser for an already open datasource
300 * an existing datasource
302 * File format of data that will be provided by datasource
304 * @return DOCUMENT ME!
306 public AlignmentI readFromFile(FileParse source, String format)
307 throws java.io.IOException
309 // TODO: generalise mapping between format string and io. class instances
310 // using Constructor.invoke reflection
311 // This is exactly the same as the readFile method except we substitute
312 // 'inFile, type' with 'source'
313 this.inFile = source.getInFile();
314 String type = source.type;
317 if (format.equals("FASTA"))
319 afile = new FastaFile(source);
321 else if (format.equals("MSF"))
323 afile = new MSFfile(source);
325 else if (format.equals("PileUp"))
327 afile = new PileUpfile(source);
329 else if (format.equals("CLUSTAL"))
331 afile = new ClustalFile(source);
333 else if (format.equals("BLC"))
335 afile = new BLCFile(source);
337 else if (format.equals("PIR"))
339 afile = new PIRFile(source);
341 else if (format.equals("PFAM"))
343 afile = new PfamFile(source);
345 else if (format.equals("JnetFile"))
347 afile = new JPredFile(source);
348 ((JPredFile) afile).removeNonSequences();
350 else if (format.equals("PDB"))
352 afile = new MCview.PDBfile(source);
354 else if (format.equals("STH"))
356 afile = new StockholmFile(source);
358 else if (format.equals("RNAML"))
360 afile = new RnamlFile(source);
362 else if (format.equals("SimpleBLAST"))
364 afile = new SimpleBlastFile(source);
367 Alignment al = new Alignment(afile.getSeqsAsArray());
369 afile.addAnnotations(al);
372 } catch (Exception e)
375 System.err.println("Failed to read alignment using the '" + format
376 + "' reader.\n" + e);
378 if (e.getMessage() != null
379 && e.getMessage().startsWith(INVALID_CHARACTERS))
381 throw new java.io.IOException(e.getMessage());
384 // Finally test if the user has pasted just the sequence, no id
385 if (type.equalsIgnoreCase("Paste"))
389 // Possible sequence is just residues with no label
390 afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
391 Alignment al = new Alignment(afile.getSeqsAsArray());
392 afile.addAnnotations(al);
395 } catch (Exception ex)
397 if (ex.toString().startsWith(INVALID_CHARACTERS))
399 throw new java.io.IOException(e.getMessage());
402 ex.printStackTrace();
406 // If we get to this stage, the format was not supported
407 throw new java.io.IOException(SUPPORTED_FORMATS);
413 * create an alignment flatfile from a Jalview alignment view
417 * @param selectedOnly
418 * @return flatfile in a string
420 public String formatSequences(String format, boolean jvsuffix,
421 AlignViewportI av, boolean selectedOnly)
424 AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
425 AlignmentI aselview = selvew.getVisibleAlignment(av
427 List<AlignmentAnnotation> ala = (av
428 .getVisibleAlignmentAnnotation(selectedOnly));
431 for (AlignmentAnnotation aa : ala)
433 aselview.addAnnotation(aa);
437 return formatSequences(format, aselview, jvsuffix);
441 * Construct an output class for an alignment in a particular filetype TODO:
442 * allow caller to detect errors and warnings encountered when generating
446 * string name of alignment format
448 * the alignment to be written out
450 * passed to AlnFile class controls whether /START-END is added to
453 * @return alignment flat file contents
455 public String formatSequences(String format, AlignmentI alignment,
460 AlignFile afile = null;
462 if (format.equalsIgnoreCase("FASTA"))
464 afile = new FastaFile();
466 else if (format.equalsIgnoreCase("MSF"))
468 afile = new MSFfile();
470 else if (format.equalsIgnoreCase("PileUp"))
472 afile = new PileUpfile();
474 else if (format.equalsIgnoreCase("CLUSTAL"))
476 afile = new ClustalFile();
478 else if (format.equalsIgnoreCase("BLC"))
480 afile = new BLCFile();
482 else if (format.equalsIgnoreCase("PIR"))
484 afile = new PIRFile();
486 else if (format.equalsIgnoreCase("PFAM"))
488 afile = new PfamFile();
490 else if (format.equalsIgnoreCase("STH"))
492 afile = new StockholmFile(alignment);
494 else if (format.equalsIgnoreCase("AMSA"))
496 afile = new AMSAFile(alignment);
498 else if (format.equalsIgnoreCase("RNAML"))
500 afile = new RnamlFile();
505 throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
507 afile.setNewlineString(newline);
508 afile.addJVSuffix(jvsuffix);
510 afile.setSeqs(alignment.getSequencesArray());
512 String afileresp = afile.print();
513 if (afile.hasWarningMessage())
515 System.err.println("Warning raised when writing as " + format
516 + " : " + afile.getWarningMessage());
519 } catch (Exception e)
521 System.err.println("Failed to write alignment as a '" + format
529 public static String checkProtocol(String file)
531 String protocol = FILE;
532 String ft = file.toLowerCase().trim();
533 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
534 || ft.indexOf("file:") == 0)
541 public static void main(String[] args)
544 while (i < args.length)
546 File f = new File(args[i]);
551 System.out.println("Reading file: " + f);
552 AppletFormatAdapter afa = new AppletFormatAdapter();
553 Runtime r = Runtime.getRuntime();
555 long memf = -r.totalMemory() + r.freeMemory();
556 long t1 = -System.currentTimeMillis();
557 Alignment al = afa.readFile(args[i], FILE,
558 new IdentifyFile().Identify(args[i], FILE));
559 t1 += System.currentTimeMillis();
561 memf += r.totalMemory() - r.freeMemory();
564 System.out.println("Alignment contains " + al.getHeight()
565 + " sequences and " + al.getWidth() + " columns.");
568 System.out.println(new AppletFormatAdapter().formatSequences(
570 } catch (Exception e)
573 .println("Couln't format the alignment for output as a FASTA file.");
574 e.printStackTrace(System.err);
579 System.out.println("Couldn't read alignment");
581 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
583 .println("Difference between free memory now and before is "
584 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
585 } catch (Exception e)
587 System.err.println("Exception when dealing with " + i
588 + "'th argument: " + args[i] + "\n" + e);
593 System.err.println("Ignoring argument '" + args[i] + "' (" + i
594 + "'th)- not a readable file.");
601 * try to discover how to access the given file as a valid datasource that
602 * will be identified as the given type.
606 * @return protocol that yields the data parsable as the given type
608 public static String resolveProtocol(String file, String format)
610 return resolveProtocol(file, format, false);
613 public static String resolveProtocol(String file, String format,
616 // TODO: test thoroughly!
617 String protocol = null;
620 System.out.println("resolving datasource started with:\n>>file\n"
621 + file + ">>endfile");
624 // This might throw a security exception in certain browsers
625 // Netscape Communicator for instance.
629 InputStream is = System.getSecurityManager().getClass()
630 .getResourceAsStream("/" + file);
638 System.err.println("Resource '" + file + "' was "
639 + (rtn ? "" : "not") + " located by classloader.");
644 protocol = AppletFormatAdapter.CLASSLOADER;
647 } catch (Exception ex)
650 .println("Exception checking resources: " + file + " " + ex);
653 if (file.indexOf("://") > -1)
655 protocol = AppletFormatAdapter.URL;
659 // skipping codebase prepend check.
660 protocol = AppletFormatAdapter.FILE;
667 System.out.println("Trying to get contents of resource as "
670 fp = new FileParse(file, protocol);
679 System.out.println("Successful.");
682 } catch (Exception e)
686 System.err.println("Exception when accessing content: " + e);
694 System.out.println("Accessing as paste.");
696 protocol = AppletFormatAdapter.PASTE;
700 fp = new FileParse(file, protocol);
705 } catch (Exception e)
707 System.err.println("Failed to access content as paste!");
716 if (format == null || format.length() == 0)
724 String idformat = new jalview.io.IdentifyFile().Identify(file,
726 if (idformat == null)
730 System.out.println("Format not identified. Inaccessible file.");
736 System.out.println("Format identified as " + idformat
737 + "and expected as " + format);
739 if (idformat.equals(format))
743 System.out.println("Protocol identified as " + protocol);
752 .println("File deemed not accessible via " + protocol);
757 } catch (Exception e)
761 System.err.println("File deemed not accessible via " + protocol);