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