refactored to decouple dependencies due to FileParse's derived classes
[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 String checkProtocol(String file)
467   {
468     String protocol = FILE;
469   
470     if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
471     {
472       protocol = URL;
473     }
474     return protocol;
475   }
476
477   public static void main(String[] args)
478   {
479     int i = 0;
480     while (i < args.length)
481     {
482       File f = new File(args[i]);
483       if (f.exists())
484       {
485         try
486         {
487           System.out.println("Reading file: " + f);
488           AppletFormatAdapter afa = new AppletFormatAdapter();
489           Runtime r = Runtime.getRuntime();
490           System.gc();
491           long memf = -r.totalMemory() + r.freeMemory();
492           long t1 = -System.currentTimeMillis();
493           Alignment al = afa.readFile(args[i], FILE,
494                   new IdentifyFile().Identify(args[i], FILE));
495           t1 += System.currentTimeMillis();
496           System.gc();
497           memf += r.totalMemory() - r.freeMemory();
498           if (al != null)
499           {
500             System.out.println("Alignment contains " + al.getHeight()
501                     + " sequences and " + al.getWidth() + " columns.");
502             try
503             {
504               System.out.println(new AppletFormatAdapter().formatSequences(
505                       "FASTA", al, true));
506             } catch (Exception e)
507             {
508               System.err
509                       .println("Couln't format the alignment for output as a FASTA file.");
510               e.printStackTrace(System.err);
511             }
512           }
513           else
514           {
515             System.out.println("Couldn't read alignment");
516           }
517           System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
518           System.out
519                   .println("Difference between free memory now and before is "
520                           + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
521
522         } catch (Exception e)
523         {
524           System.err.println("Exception when dealing with " + i
525                   + "'th argument: " + args[i] + "\n" + e);
526         }
527       }
528       else
529       {
530         System.err.println("Ignoring argument '" + args[i] + "' (" + i
531                 + "'th)- not a readable file.");
532       }
533       i++;
534     }
535   }
536
537   /**
538    * try to discover how to access the given file as a valid datasource that
539    * will be identified as the given type.
540    * 
541    * @param file
542    * @param format
543    * @return protocol that yields the data parsable as the given type
544    */
545   public static String resolveProtocol(String file, String format)
546   {
547     return resolveProtocol(file, format, false);
548   }
549
550   public static String resolveProtocol(String file, String format,
551           boolean debug)
552   {
553     // TODO: test thoroughly!
554     String protocol = null;
555     if (debug)
556     {
557       System.out.println("resolving datasource started with:\n>>file\n"
558               + file + ">>endfile");
559     }
560
561     // This might throw a security exception in certain browsers
562     // Netscape Communicator for instance.
563     try
564     {
565       boolean rtn = false;
566       InputStream is = System.getSecurityManager().getClass()
567               .getResourceAsStream("/" + file);
568       if (is != null)
569       {
570         rtn = true;
571         is.close();
572       }
573       if (debug)
574       {
575         System.err.println("Resource '" + file + "' was "
576                 + (rtn ? "" : "not") + " located by classloader.");
577       }
578       ;
579       if (rtn)
580       {
581         protocol = AppletFormatAdapter.CLASSLOADER;
582       }
583
584     } catch (Exception ex)
585     {
586       System.err
587               .println("Exception checking resources: " + file + " " + ex);
588     }
589
590     if (file.indexOf("://") > -1)
591     {
592       protocol = AppletFormatAdapter.URL;
593     }
594     else
595     {
596       // skipping codebase prepend check.
597       protocol = AppletFormatAdapter.FILE;
598     }
599     FileParse fp = null;
600     try
601     {
602       if (debug)
603       {
604         System.out.println("Trying to get contents of resource as "
605                 + protocol + ":");
606       }
607       fp = new FileParse(file, protocol);
608       if (!fp.isValid())
609       {
610         fp = null;
611       }
612       else
613       {
614         if (debug)
615         {
616           System.out.println("Successful.");
617         }
618       }
619     } catch (Exception e)
620     {
621       if (debug)
622       {
623         System.err.println("Exception when accessing content: " + e);
624       }
625       fp = null;
626     }
627     if (fp == null)
628     {
629       if (debug)
630       {
631         System.out.println("Accessing as paste.");
632       }
633       protocol = AppletFormatAdapter.PASTE;
634       fp = null;
635       try
636       {
637         fp = new FileParse(file, protocol);
638         if (!fp.isValid())
639         {
640           fp = null;
641         }
642       } catch (Exception e)
643       {
644         System.err.println("Failed to access content as paste!");
645         e.printStackTrace();
646         fp = null;
647       }
648     }
649     if (fp == null)
650     {
651       return null;
652     }
653     if (format == null || format.length() == 0)
654     {
655       return protocol;
656     }
657     else
658     {
659       try
660       {
661         String idformat = new jalview.io.IdentifyFile().Identify(file,
662                 protocol);
663         if (idformat == null)
664         {
665           if (debug)
666           {
667             System.out.println("Format not identified. Inaccessible file.");
668           }
669           return null;
670         }
671         if (debug)
672         {
673           System.out.println("Format identified as " + idformat
674                   + "and expected as " + format);
675         }
676         if (idformat.equals(format))
677         {
678           if (debug)
679           {
680             System.out.println("Protocol identified as " + protocol);
681           }
682           return protocol;
683         }
684         else
685         {
686           if (debug)
687           {
688             System.out
689                     .println("File deemed not accessible via " + protocol);
690           }
691           fp.close();
692           return null;
693         }
694       } catch (Exception e)
695       {
696         if (debug)
697         {
698           System.err.println("File deemed not accessible via " + protocol);
699           e.printStackTrace();
700         }
701         ;
702
703       }
704     }
705     return null;
706   }
707 }