Jalview 2.6 source licence
[jalview.git] / src / jalview / io / AppletFormatAdapter.java
1 /*
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
4  * 
5  * This file is part of Jalview.
6  * 
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.
10  * 
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.
15  * 
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  */
18 package jalview.io;
19
20 import java.io.File;
21 import java.io.InputStream;
22
23 import jalview.datamodel.*;
24
25 /**
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.
30  * 
31  * @author $author$
32  * @version $Revision$
33  */
34 public class AppletFormatAdapter
35 {
36   /**
37    * List of valid format strings used in the isValidFormat method
38    */
39   public static final String[] READABLE_FORMATS = new String[]
40   { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
41       "PDB", "JnetFile" }; // , "SimpleBLAST" };
42
43   /**
44    * List of valid format strings for use by callers of the formatSequences
45    * method
46    */
47   public static final String[] WRITEABLE_FORMATS = new String[]
48   { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA" };
49
50   /**
51    * List of extensions corresponding to file format types in WRITABLE_FNAMES
52    * that are writable by the application.
53    */
54   public static final String[] WRITABLE_EXTENSIONS = new String[]
55   { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar" };
56
57   /**
58    * List of writable formats by the application. Order must correspond with the
59    * WRITABLE_EXTENSIONS list of formats.
60    */
61   public static final String[] WRITABLE_FNAMES = new String[]
62   { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview" };
63
64   /**
65    * List of readable format file extensions by application in order
66    * corresponding to READABLE_FNAMES
67    */
68   public static final String[] READABLE_EXTENSIONS = new String[]
69   { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa", "jar",
70       "sto" }; // ,
71
72   // ".blast"
73   // };
74
75   /**
76    * List of readable formats by application in order corresponding to
77    * READABLE_EXTENSIONS
78    */
79   public static final String[] READABLE_FNAMES = new String[]
80   { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
81       "Stockholm" };// ,
82
83   // "SimpleBLAST"
84   // };
85
86   public static String INVALID_CHARACTERS = "Contains invalid characters";
87
88   // TODO: make these messages dynamic
89   public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
90           + prettyPrint(READABLE_FORMATS);
91
92   /**
93    * 
94    * @param els
95    * @return grammatically correct(ish) list consisting of els elements.
96    */
97   public static String prettyPrint(String[] els)
98   {
99     StringBuffer list = new StringBuffer();
100     for (int i = 0, iSize = els.length - 1; i < iSize; i++)
101     {
102       list.append(els[i]);
103       list.append(",");
104     }
105     list.append(" and " + els[els.length - 1] + ".");
106     return list.toString();
107   }
108
109   public static String FILE = "File";
110
111   public static String URL = "URL";
112
113   public static String PASTE = "Paste";
114
115   public static String CLASSLOADER = "ClassLoader";
116
117   AlignFile afile = null;
118
119   String inFile;
120
121   /**
122    * check that this format is valid for reading
123    * 
124    * @param format
125    *          a format string to be compared with READABLE_FORMATS
126    * @return true if format is readable
127    */
128   public static final boolean isValidFormat(String format)
129   {
130     return isValidFormat(format, false);
131   }
132
133   /**
134    * validate format is valid for IO
135    * 
136    * @param format
137    *          a format string to be compared with either READABLE_FORMATS or
138    *          WRITEABLE_FORMATS
139    * @param forwriting
140    *          when true, format is checked for containment in WRITEABLE_FORMATS
141    * @return true if format is valid
142    */
143   public static final boolean isValidFormat(String format,
144           boolean forwriting)
145   {
146     boolean valid = false;
147     String[] format_list = (forwriting) ? WRITEABLE_FORMATS
148             : READABLE_FORMATS;
149     for (int i = 0; i < format_list.length; i++)
150     {
151       if (format_list[i].equalsIgnoreCase(format))
152       {
153         return true;
154       }
155     }
156
157     return valid;
158   }
159
160   /**
161    * Constructs the correct filetype parser for a characterised datasource
162    * 
163    * @param inFile
164    *          data/data location
165    * @param type
166    *          type of datasource
167    * @param format
168    *          File format of data provided by datasource
169    * 
170    * @return DOCUMENT ME!
171    */
172   public Alignment readFile(String inFile, String type, String format)
173           throws java.io.IOException
174   {
175     // TODO: generalise mapping between format string and io. class instances
176     // using Constructor.invoke reflection
177     this.inFile = inFile;
178     try
179     {
180       if (format.equals("FASTA"))
181       {
182         afile = new FastaFile(inFile, type);
183       }
184       else if (format.equals("MSF"))
185       {
186         afile = new MSFfile(inFile, type);
187       }
188       else if (format.equals("PileUp"))
189       {
190         afile = new PileUpfile(inFile, type);
191       }
192       else if (format.equals("CLUSTAL"))
193       {
194         afile = new ClustalFile(inFile, type);
195       }
196       else if (format.equals("BLC"))
197       {
198         afile = new BLCFile(inFile, type);
199       }
200       else if (format.equals("PIR"))
201       {
202         afile = new PIRFile(inFile, type);
203       }
204       else if (format.equals("PFAM"))
205       {
206         afile = new PfamFile(inFile, type);
207       }
208       else if (format.equals("JnetFile"))
209       {
210         afile = new JPredFile(inFile, type);
211         ((JPredFile) afile).removeNonSequences();
212       }
213       else if (format.equals("PDB"))
214       {
215         afile = new MCview.PDBfile(inFile, type);
216       }
217       else if (format.equals("STH"))
218       {
219         afile = new StockholmFile(inFile, type);
220       }
221       else if (format.equals("SimpleBLAST"))
222       {
223         afile = new SimpleBlastFile(inFile, type);
224       }
225
226       Alignment al = new Alignment(afile.getSeqsAsArray());
227
228       afile.addAnnotations(al);
229
230       return al;
231     } catch (Exception e)
232     {
233       e.printStackTrace();
234       System.err.println("Failed to read alignment using the '" + format
235               + "' reader.\n" + e);
236
237       if (e.getMessage() != null
238               && e.getMessage().startsWith(INVALID_CHARACTERS))
239       {
240         throw new java.io.IOException(e.getMessage());
241       }
242
243       // Finally test if the user has pasted just the sequence, no id
244       if (type.equalsIgnoreCase("Paste"))
245       {
246         try
247         {
248           // Possible sequence is just residues with no label
249           afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
250           Alignment al = new Alignment(afile.getSeqsAsArray());
251           afile.addAnnotations(al);
252           return al;
253
254         } catch (Exception ex)
255         {
256           if (ex.toString().startsWith(INVALID_CHARACTERS))
257           {
258             throw new java.io.IOException(e.getMessage());
259           }
260
261           ex.printStackTrace();
262         }
263       }
264
265       // If we get to this stage, the format was not supported
266       throw new java.io.IOException(SUPPORTED_FORMATS);
267     }
268   }
269
270   /**
271    * Constructs the correct filetype parser for an already open datasource
272    * 
273    * @param source
274    *          an existing datasource
275    * @param format
276    *          File format of data that will be provided by datasource
277    * 
278    * @return DOCUMENT ME!
279    */
280   public Alignment readFromFile(FileParse source, String format)
281           throws java.io.IOException
282   {
283     // TODO: generalise mapping between format string and io. class instances
284     // using Constructor.invoke reflection
285     // This is exactly the same as the readFile method except we substitute
286     // 'inFile, type' with 'source'
287     this.inFile = source.getInFile();
288     String type = source.type;
289     try
290     {
291       if (format.equals("FASTA"))
292       {
293         afile = new FastaFile(source);
294       }
295       else if (format.equals("MSF"))
296       {
297         afile = new MSFfile(source);
298       }
299       else if (format.equals("PileUp"))
300       {
301         afile = new PileUpfile(source);
302       }
303       else if (format.equals("CLUSTAL"))
304       {
305         afile = new ClustalFile(source);
306       }
307       else if (format.equals("BLC"))
308       {
309         afile = new BLCFile(source);
310       }
311       else if (format.equals("PIR"))
312       {
313         afile = new PIRFile(source);
314       }
315       else if (format.equals("PFAM"))
316       {
317         afile = new PfamFile(source);
318       }
319       else if (format.equals("JnetFile"))
320       {
321         afile = new JPredFile(source);
322         ((JPredFile) afile).removeNonSequences();
323       }
324       else if (format.equals("PDB"))
325       {
326         afile = new MCview.PDBfile(source);
327       }
328       else if (format.equals("STH"))
329       {
330         afile = new StockholmFile(source);
331       }
332       else if (format.equals("SimpleBLAST"))
333       {
334         afile = new SimpleBlastFile(source);
335       }
336
337       Alignment al = new Alignment(afile.getSeqsAsArray());
338
339       afile.addAnnotations(al);
340
341       return al;
342     } catch (Exception e)
343     {
344       e.printStackTrace();
345       System.err.println("Failed to read alignment using the '" + format
346               + "' reader.\n" + e);
347
348       if (e.getMessage() != null
349               && e.getMessage().startsWith(INVALID_CHARACTERS))
350       {
351         throw new java.io.IOException(e.getMessage());
352       }
353
354       // Finally test if the user has pasted just the sequence, no id
355       if (type.equalsIgnoreCase("Paste"))
356       {
357         try
358         {
359           // Possible sequence is just residues with no label
360           afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
361           Alignment al = new Alignment(afile.getSeqsAsArray());
362           afile.addAnnotations(al);
363           return al;
364
365         } catch (Exception ex)
366         {
367           if (ex.toString().startsWith(INVALID_CHARACTERS))
368           {
369             throw new java.io.IOException(e.getMessage());
370           }
371
372           ex.printStackTrace();
373         }
374       }
375
376       // If we get to this stage, the format was not supported
377       throw new java.io.IOException(SUPPORTED_FORMATS);
378     }
379   }
380
381   /**
382    * Construct an output class for an alignment in a particular filetype TODO:
383    * allow caller to detect errors and warnings encountered when generating
384    * output
385    * 
386    * @param format
387    *          string name of alignment format
388    * @param alignment
389    *          the alignment to be written out
390    * @param jvsuffix
391    *          passed to AlnFile class controls whether /START-END is added to
392    *          sequence names
393    * 
394    * @return alignment flat file contents
395    */
396   public String formatSequences(String format, AlignmentI alignment,
397           boolean jvsuffix)
398   {
399     try
400     {
401       AlignFile afile = null;
402
403       if (format.equalsIgnoreCase("FASTA"))
404       {
405         afile = new FastaFile();
406       }
407       else if (format.equalsIgnoreCase("MSF"))
408       {
409         afile = new MSFfile();
410       }
411       else if (format.equalsIgnoreCase("PileUp"))
412       {
413         afile = new PileUpfile();
414       }
415       else if (format.equalsIgnoreCase("CLUSTAL"))
416       {
417         afile = new ClustalFile();
418       }
419       else if (format.equalsIgnoreCase("BLC"))
420       {
421         afile = new BLCFile();
422       }
423       else if (format.equalsIgnoreCase("PIR"))
424       {
425         afile = new PIRFile();
426       }
427       else if (format.equalsIgnoreCase("PFAM"))
428       {
429         afile = new PfamFile();
430       }
431       else if (format.equalsIgnoreCase("STH"))
432       {
433         afile = new StockholmFile();
434       }
435       else if (format.equalsIgnoreCase("AMSA"))
436       {
437         afile = new AMSAFile(alignment);
438       }
439       else
440       {
441         throw new Exception(
442                 "Implementation error: Unknown file format string");
443       }
444
445       afile.addJVSuffix(jvsuffix);
446
447       afile.setSeqs(alignment.getSequencesArray());
448
449       String afileresp = afile.print();
450       if (afile.hasWarningMessage())
451       {
452         System.err.println("Warning raised when writing as " + format
453                 + " : " + afile.getWarningMessage());
454       }
455       return afileresp;
456     } catch (Exception e)
457     {
458       System.err.println("Failed to write alignment as a '" + format
459               + "' file\n");
460       e.printStackTrace();
461     }
462
463     return null;
464   }
465
466   public static void main(String[] args)
467   {
468     int i = 0;
469     while (i < args.length)
470     {
471       File f = new File(args[i]);
472       if (f.exists())
473       {
474         try
475         {
476           System.out.println("Reading file: " + f);
477           AppletFormatAdapter afa = new AppletFormatAdapter();
478           Runtime r = Runtime.getRuntime();
479           System.gc();
480           long memf = -r.totalMemory() + r.freeMemory();
481           long t1 = -System.currentTimeMillis();
482           Alignment al = afa.readFile(args[i], FILE,
483                   new IdentifyFile().Identify(args[i], FILE));
484           t1 += System.currentTimeMillis();
485           System.gc();
486           memf += r.totalMemory() - r.freeMemory();
487           if (al != null)
488           {
489             System.out.println("Alignment contains " + al.getHeight()
490                     + " sequences and " + al.getWidth() + " columns.");
491             try
492             {
493               System.out.println(new AppletFormatAdapter().formatSequences(
494                       "FASTA", al, true));
495             } catch (Exception e)
496             {
497               System.err
498                       .println("Couln't format the alignment for output as a FASTA file.");
499               e.printStackTrace(System.err);
500             }
501           }
502           else
503           {
504             System.out.println("Couldn't read alignment");
505           }
506           System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
507           System.out
508                   .println("Difference between free memory now and before is "
509                           + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
510
511         } catch (Exception e)
512         {
513           System.err.println("Exception when dealing with " + i
514                   + "'th argument: " + args[i] + "\n" + e);
515         }
516       }
517       else
518       {
519         System.err.println("Ignoring argument '" + args[i] + "' (" + i
520                 + "'th)- not a readable file.");
521       }
522       i++;
523     }
524   }
525
526   /**
527    * try to discover how to access the given file as a valid datasource that
528    * will be identified as the given type.
529    * 
530    * @param file
531    * @param format
532    * @return protocol that yields the data parsable as the given type
533    */
534   public static String resolveProtocol(String file, String format)
535   {
536     return resolveProtocol(file, format, false);
537   }
538
539   public static String resolveProtocol(String file, String format,
540           boolean debug)
541   {
542     // TODO: test thoroughly!
543     String protocol = null;
544     if (debug)
545     {
546       System.out.println("resolving datasource started with:\n>>file\n"
547               + file + ">>endfile");
548     }
549
550     // This might throw a security exception in certain browsers
551     // Netscape Communicator for instance.
552     try
553     {
554       boolean rtn = false;
555       InputStream is = System.getSecurityManager().getClass()
556               .getResourceAsStream("/" + file);
557       if (is != null)
558       {
559         rtn = true;
560         is.close();
561       }
562       if (debug)
563       {
564         System.err.println("Resource '" + file + "' was "
565                 + (rtn ? "" : "not") + " located by classloader.");
566       }
567       ;
568       if (rtn)
569       {
570         protocol = AppletFormatAdapter.CLASSLOADER;
571       }
572
573     } catch (Exception ex)
574     {
575       System.err
576               .println("Exception checking resources: " + file + " " + ex);
577     }
578
579     if (file.indexOf("://") > -1)
580     {
581       protocol = AppletFormatAdapter.URL;
582     }
583     else
584     {
585       // skipping codebase prepend check.
586       protocol = AppletFormatAdapter.FILE;
587     }
588     FileParse fp = null;
589     try
590     {
591       if (debug)
592       {
593         System.out.println("Trying to get contents of resource as "
594                 + protocol + ":");
595       }
596       fp = new FileParse(file, protocol);
597       if (!fp.isValid())
598       {
599         fp = null;
600       } else {
601       if (debug)
602       {
603         System.out.println("Successful.");
604       }}
605     } catch (Exception e)
606     {
607       if (debug)
608       {
609         System.err.println("Exception when accessing content: " + e);
610       }
611       fp = null;
612     }
613     if (fp == null)
614     {
615       if (debug)
616       {
617         System.out.println("Accessing as paste.");
618       }
619       protocol = AppletFormatAdapter.PASTE;
620       fp = null;
621       try
622       {
623         fp = new FileParse(file, protocol);
624         if (!fp.isValid())
625         {
626           fp = null;
627         }
628       } catch (Exception e)
629       {
630         System.err.println("Failed to access content as paste!");
631         e.printStackTrace();
632         fp = null;
633       }
634     }
635     if (fp == null)
636     {
637       return null;
638     }
639     if (format == null || format.length() == 0)
640     {
641       return protocol;
642     }
643     else
644     {
645       try
646       {
647         String idformat = new jalview.io.IdentifyFile().Identify(file,
648                 protocol);
649         if (idformat == null)
650         {
651           if (debug)
652           {
653             System.out.println("Format not identified. Inaccessible file.");
654           }
655           return null;
656         }
657         if (debug)
658         {
659           System.out.println("Format identified as " + idformat
660                   + "and expected as " + format);
661         }
662         if (idformat.equals(format))
663         {
664           if (debug)
665           {
666             System.out.println("Protocol identified as " + protocol);
667           }
668           return protocol;
669         }
670         else
671         {
672           if (debug)
673           {
674             System.out
675                     .println("File deemed not accessible via " + protocol);
676           }
677           fp.close();
678           return null;
679         }
680       } catch (Exception e)
681       {
682         if (debug)
683         {
684           System.err.println("File deemed not accessible via " + protocol);
685           e.printStackTrace();
686         }
687         ;
688
689       }
690     }
691     return null;
692   }
693 }