JAL-1355
[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(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
505       }
506       afile.setNewlineString(newline);
507       afile.addJVSuffix(jvsuffix);
508
509       afile.setSeqs(alignment.getSequencesArray());
510
511       String afileresp = afile.print();
512       if (afile.hasWarningMessage())
513       {
514         System.err.println("Warning raised when writing as " + format
515                 + " : " + afile.getWarningMessage());
516       }
517       return afileresp;
518     } catch (Exception e)
519     {
520       System.err.println("Failed to write alignment as a '" + format
521               + "' file\n");
522       e.printStackTrace();
523     }
524
525     return null;
526   }
527
528   public static String checkProtocol(String file)
529   {
530     String protocol = FILE;
531     String ft = file.toLowerCase().trim();
532     if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
533             || ft.indexOf("file:") == 0)
534     {
535       protocol = URL;
536     }
537     return protocol;
538   }
539
540   public static void main(String[] args)
541   {
542     int i = 0;
543     while (i < args.length)
544     {
545       File f = new File(args[i]);
546       if (f.exists())
547       {
548         try
549         {
550           System.out.println("Reading file: " + f);
551           AppletFormatAdapter afa = new AppletFormatAdapter();
552           Runtime r = Runtime.getRuntime();
553           System.gc();
554           long memf = -r.totalMemory() + r.freeMemory();
555           long t1 = -System.currentTimeMillis();
556           Alignment al = afa.readFile(args[i], FILE,
557                   new IdentifyFile().Identify(args[i], FILE));
558           t1 += System.currentTimeMillis();
559           System.gc();
560           memf += r.totalMemory() - r.freeMemory();
561           if (al != null)
562           {
563             System.out.println("Alignment contains " + al.getHeight()
564                     + " sequences and " + al.getWidth() + " columns.");
565             try
566             {
567               System.out.println(new AppletFormatAdapter().formatSequences(
568                       "FASTA", al, true));
569             } catch (Exception e)
570             {
571               System.err
572                       .println("Couln't format the alignment for output as a FASTA file.");
573               e.printStackTrace(System.err);
574             }
575           }
576           else
577           {
578             System.out.println("Couldn't read alignment");
579           }
580           System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
581           System.out
582                   .println("Difference between free memory now and before is "
583                           + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
584         } catch (Exception e)
585         {
586           System.err.println("Exception when dealing with " + i
587                   + "'th argument: " + args[i] + "\n" + e);
588         }
589       }
590       else
591       {
592         System.err.println("Ignoring argument '" + args[i] + "' (" + i
593                 + "'th)- not a readable file.");
594       }
595       i++;
596     }
597   }
598
599   /**
600    * try to discover how to access the given file as a valid datasource that
601    * will be identified as the given type.
602    * 
603    * @param file
604    * @param format
605    * @return protocol that yields the data parsable as the given type
606    */
607   public static String resolveProtocol(String file, String format)
608   {
609     return resolveProtocol(file, format, false);
610   }
611
612   public static String resolveProtocol(String file, String format,
613           boolean debug)
614   {
615     // TODO: test thoroughly!
616     String protocol = null;
617     if (debug)
618     {
619       System.out.println("resolving datasource started with:\n>>file\n"
620               + file + ">>endfile");
621     }
622
623     // This might throw a security exception in certain browsers
624     // Netscape Communicator for instance.
625     try
626     {
627       boolean rtn = false;
628       InputStream is = System.getSecurityManager().getClass()
629               .getResourceAsStream("/" + file);
630       if (is != null)
631       {
632         rtn = true;
633         is.close();
634       }
635       if (debug)
636       {
637         System.err.println("Resource '" + file + "' was "
638                 + (rtn ? "" : "not") + " located by classloader.");
639       }
640       ;
641       if (rtn)
642       {
643         protocol = AppletFormatAdapter.CLASSLOADER;
644       }
645
646     } catch (Exception ex)
647     {
648       System.err
649               .println("Exception checking resources: " + file + " " + ex);
650     }
651
652     if (file.indexOf("://") > -1)
653     {
654       protocol = AppletFormatAdapter.URL;
655     }
656     else
657     {
658       // skipping codebase prepend check.
659       protocol = AppletFormatAdapter.FILE;
660     }
661     FileParse fp = null;
662     try
663     {
664       if (debug)
665       {
666         System.out.println("Trying to get contents of resource as "
667                 + protocol + ":");
668       }
669       fp = new FileParse(file, protocol);
670       if (!fp.isValid())
671       {
672         fp = null;
673       }
674       else
675       {
676         if (debug)
677         {
678           System.out.println("Successful.");
679         }
680       }
681     } catch (Exception e)
682     {
683       if (debug)
684       {
685         System.err.println("Exception when accessing content: " + e);
686       }
687       fp = null;
688     }
689     if (fp == null)
690     {
691       if (debug)
692       {
693         System.out.println("Accessing as paste.");
694       }
695       protocol = AppletFormatAdapter.PASTE;
696       fp = null;
697       try
698       {
699         fp = new FileParse(file, protocol);
700         if (!fp.isValid())
701         {
702           fp = null;
703         }
704       } catch (Exception e)
705       {
706         System.err.println("Failed to access content as paste!");
707         e.printStackTrace();
708         fp = null;
709       }
710     }
711     if (fp == null)
712     {
713       return null;
714     }
715     if (format == null || format.length() == 0)
716     {
717       return protocol;
718     }
719     else
720     {
721       try
722       {
723         String idformat = new jalview.io.IdentifyFile().Identify(file,
724                 protocol);
725         if (idformat == null)
726         {
727           if (debug)
728           {
729             System.out.println("Format not identified. Inaccessible file.");
730           }
731           return null;
732         }
733         if (debug)
734         {
735           System.out.println("Format identified as " + idformat
736                   + "and expected as " + format);
737         }
738         if (idformat.equals(format))
739         {
740           if (debug)
741           {
742             System.out.println("Protocol identified as " + protocol);
743           }
744           return protocol;
745         }
746         else
747         {
748           if (debug)
749           {
750             System.out
751                     .println("File deemed not accessible via " + protocol);
752           }
753           fp.close();
754           return null;
755         }
756       } catch (Exception e)
757       {
758         if (debug)
759         {
760           System.err.println("File deemed not accessible via " + protocol);
761           e.printStackTrace();
762         }
763         ;
764
765       }
766     }
767     return null;
768   }
769 }