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 import jalview.util.MessageManager;
30
31 /**
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.
36  * 
37  * @author $author$
38  * @version $Revision$
39  */
40 public class AppletFormatAdapter
41 {
42   /**
43    * List of valid format strings used in the isValidFormat method
44    */
45   public static final String[] READABLE_FORMATS = new String[]
46   { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
47       "PDB", "JnetFile", "RNAML" }; // , "SimpleBLAST" };
48
49   /**
50    * List of valid format strings for use by callers of the formatSequences
51    * method
52    */
53   public static final String[] WRITEABLE_FORMATS = new String[]
54   { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA", "STH" };
55
56   /**
57    * List of extensions corresponding to file format types in WRITABLE_FNAMES
58    * that are writable by the application.
59    */
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" };
63
64   /**
65    * List of writable formats by the application. Order must correspond with the
66    * WRITABLE_EXTENSIONS list of formats.
67    */
68   public static final String[] WRITABLE_FNAMES = new String[]
69   { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
70       "STH", "Jalview" };
71
72   /**
73    * List of readable format file extensions by application in order
74    * corresponding to READABLE_FNAMES
75    */
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"
79
80   /**
81    * List of readable formats by application in order corresponding to
82    * READABLE_EXTENSIONS
83    */
84   public static final String[] READABLE_FNAMES = new String[]
85   { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
86       "Stockholm", "RNAML" };// ,
87
88   // "SimpleBLAST"
89   // };
90
91   public static String INVALID_CHARACTERS = "Contains invalid characters";
92
93   // TODO: make these messages dynamic
94   public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
95           + prettyPrint(READABLE_FORMATS);
96
97   /**
98    * 
99    * @param els
100    * @return grammatically correct(ish) list consisting of els elements.
101    */
102   public static String prettyPrint(String[] els)
103   {
104     StringBuffer list = new StringBuffer();
105     for (int i = 0, iSize = els.length - 1; i < iSize; i++)
106     {
107       list.append(els[i]);
108       list.append(",");
109     }
110     list.append(" and " + els[els.length - 1] + ".");
111     return list.toString();
112   }
113
114   public static String FILE = "File";
115
116   public static String URL = "URL";
117
118   public static String PASTE = "Paste";
119
120   public static String CLASSLOADER = "ClassLoader";
121
122   AlignFile afile = null;
123
124   String inFile;
125
126   /**
127    * character used to write newlines
128    */
129   protected String newline = System.getProperty("line.separator");
130
131   public void setNewlineString(String nl)
132   {
133     newline = nl;
134   }
135
136   public String getNewlineString()
137   {
138     return newline;
139   }
140
141   /**
142    * check that this format is valid for reading
143    * 
144    * @param format
145    *          a format string to be compared with READABLE_FORMATS
146    * @return true if format is readable
147    */
148   public static final boolean isValidFormat(String format)
149   {
150     return isValidFormat(format, false);
151   }
152
153   /**
154    * validate format is valid for IO
155    * 
156    * @param format
157    *          a format string to be compared with either READABLE_FORMATS or
158    *          WRITEABLE_FORMATS
159    * @param forwriting
160    *          when true, format is checked for containment in WRITEABLE_FORMATS
161    * @return true if format is valid
162    */
163   public static final boolean isValidFormat(String format,
164           boolean forwriting)
165   {
166     boolean valid = false;
167     String[] format_list = (forwriting) ? WRITEABLE_FORMATS
168             : READABLE_FORMATS;
169     for (int i = 0; i < format_list.length; i++)
170     {
171       if (format_list[i].equalsIgnoreCase(format))
172       {
173         return true;
174       }
175     }
176
177     return valid;
178   }
179
180   /**
181    * Constructs the correct filetype parser for a characterised datasource
182    * 
183    * @param inFile
184    *          data/data location
185    * @param type
186    *          type of datasource
187    * @param format
188    *          File format of data provided by datasource
189    * 
190    * @return DOCUMENT ME!
191    */
192   public Alignment readFile(String inFile, String type, String format)
193           throws java.io.IOException
194   {
195     // TODO: generalise mapping between format string and io. class instances
196     // using Constructor.invoke reflection
197     this.inFile = inFile;
198     try
199     {
200       if (format.equals("FASTA"))
201       {
202         afile = new FastaFile(inFile, type);
203       }
204       else if (format.equals("MSF"))
205       {
206         afile = new MSFfile(inFile, type);
207       }
208       else if (format.equals("PileUp"))
209       {
210         afile = new PileUpfile(inFile, type);
211       }
212       else if (format.equals("CLUSTAL"))
213       {
214         afile = new ClustalFile(inFile, type);
215       }
216       else if (format.equals("BLC"))
217       {
218         afile = new BLCFile(inFile, type);
219       }
220       else if (format.equals("PIR"))
221       {
222         afile = new PIRFile(inFile, type);
223       }
224       else if (format.equals("PFAM"))
225       {
226         afile = new PfamFile(inFile, type);
227       }
228       else if (format.equals("JnetFile"))
229       {
230         afile = new JPredFile(inFile, type);
231         ((JPredFile) afile).removeNonSequences();
232       }
233       else if (format.equals("PDB"))
234       {
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);
238       }
239       else if (format.equals("STH"))
240       {
241         afile = new StockholmFile(inFile, type);
242       }
243       else if (format.equals("SimpleBLAST"))
244       {
245         afile = new SimpleBlastFile(inFile, type);
246       }
247       else if (format.equals("RNAML"))
248       {
249         afile = new RnamlFile(inFile, type);
250       }
251
252       Alignment al = new Alignment(afile.getSeqsAsArray());
253
254       afile.addAnnotations(al);
255
256       return al;
257     } catch (Exception e)
258     {
259       e.printStackTrace();
260       System.err.println("Failed to read alignment using the '" + format
261               + "' reader.\n" + e);
262
263       if (e.getMessage() != null
264               && e.getMessage().startsWith(INVALID_CHARACTERS))
265       {
266         throw new java.io.IOException(e.getMessage());
267       }
268
269       // Finally test if the user has pasted just the sequence, no id
270       if (type.equalsIgnoreCase("Paste"))
271       {
272         try
273         {
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);
278           return al;
279
280         } catch (Exception ex)
281         {
282           if (ex.toString().startsWith(INVALID_CHARACTERS))
283           {
284             throw new java.io.IOException(e.getMessage());
285           }
286
287           ex.printStackTrace();
288         }
289       }
290
291       // If we get to this stage, the format was not supported
292       throw new java.io.IOException(SUPPORTED_FORMATS);
293     }
294   }
295
296   /**
297    * Constructs the correct filetype parser for an already open datasource
298    * 
299    * @param source
300    *          an existing datasource
301    * @param format
302    *          File format of data that will be provided by datasource
303    * 
304    * @return DOCUMENT ME!
305    */
306   public AlignmentI readFromFile(FileParse source, String format)
307           throws java.io.IOException
308   {
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;
315     try
316     {
317       if (format.equals("FASTA"))
318       {
319         afile = new FastaFile(source);
320       }
321       else if (format.equals("MSF"))
322       {
323         afile = new MSFfile(source);
324       }
325       else if (format.equals("PileUp"))
326       {
327         afile = new PileUpfile(source);
328       }
329       else if (format.equals("CLUSTAL"))
330       {
331         afile = new ClustalFile(source);
332       }
333       else if (format.equals("BLC"))
334       {
335         afile = new BLCFile(source);
336       }
337       else if (format.equals("PIR"))
338       {
339         afile = new PIRFile(source);
340       }
341       else if (format.equals("PFAM"))
342       {
343         afile = new PfamFile(source);
344       }
345       else if (format.equals("JnetFile"))
346       {
347         afile = new JPredFile(source);
348         ((JPredFile) afile).removeNonSequences();
349       }
350       else if (format.equals("PDB"))
351       {
352         afile = new MCview.PDBfile(source);
353       }
354       else if (format.equals("STH"))
355       {
356         afile = new StockholmFile(source);
357       }
358       else if (format.equals("RNAML"))
359       {
360         afile = new RnamlFile(source);
361       }
362       else if (format.equals("SimpleBLAST"))
363       {
364         afile = new SimpleBlastFile(source);
365       }
366
367       Alignment al = new Alignment(afile.getSeqsAsArray());
368
369       afile.addAnnotations(al);
370
371       return al;
372     } catch (Exception e)
373     {
374       e.printStackTrace();
375       System.err.println("Failed to read alignment using the '" + format
376               + "' reader.\n" + e);
377
378       if (e.getMessage() != null
379               && e.getMessage().startsWith(INVALID_CHARACTERS))
380       {
381         throw new java.io.IOException(e.getMessage());
382       }
383
384       // Finally test if the user has pasted just the sequence, no id
385       if (type.equalsIgnoreCase("Paste"))
386       {
387         try
388         {
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);
393           return al;
394
395         } catch (Exception ex)
396         {
397           if (ex.toString().startsWith(INVALID_CHARACTERS))
398           {
399             throw new java.io.IOException(e.getMessage());
400           }
401
402           ex.printStackTrace();
403         }
404       }
405
406       // If we get to this stage, the format was not supported
407       throw new java.io.IOException(SUPPORTED_FORMATS);
408     }
409   }
410
411
412   /**
413    * create an alignment flatfile from a Jalview alignment view 
414    * @param format
415    * @param jvsuffix
416    * @param av
417    * @param selectedOnly
418    * @return flatfile in a string
419    */
420   public String formatSequences(String format, boolean jvsuffix,
421           AlignViewportI av, boolean selectedOnly)
422   {
423
424     AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
425     AlignmentI aselview = selvew.getVisibleAlignment(av
426             .getGapCharacter());
427     List<AlignmentAnnotation> ala = (av
428             .getVisibleAlignmentAnnotation(selectedOnly));
429     if (ala != null)
430     {
431       for (AlignmentAnnotation aa : ala)
432       {
433         aselview.addAnnotation(aa);
434       }
435     }
436     
437     return formatSequences(format, aselview, jvsuffix);
438   }
439   
440   /**
441    * Construct an output class for an alignment in a particular filetype TODO:
442    * allow caller to detect errors and warnings encountered when generating
443    * output
444    * 
445    * @param format
446    *          string name of alignment format
447    * @param alignment
448    *          the alignment to be written out
449    * @param jvsuffix
450    *          passed to AlnFile class controls whether /START-END is added to
451    *          sequence names
452    * 
453    * @return alignment flat file contents
454    */
455   public String formatSequences(String format, AlignmentI alignment,
456           boolean jvsuffix)
457   {
458     try
459     {
460       AlignFile afile = null;
461
462       if (format.equalsIgnoreCase("FASTA"))
463       {
464         afile = new FastaFile();
465       }
466       else if (format.equalsIgnoreCase("MSF"))
467       {
468         afile = new MSFfile();
469       }
470       else if (format.equalsIgnoreCase("PileUp"))
471       {
472         afile = new PileUpfile();
473       }
474       else if (format.equalsIgnoreCase("CLUSTAL"))
475       {
476         afile = new ClustalFile();
477       }
478       else if (format.equalsIgnoreCase("BLC"))
479       {
480         afile = new BLCFile();
481       }
482       else if (format.equalsIgnoreCase("PIR"))
483       {
484         afile = new PIRFile();
485       }
486       else if (format.equalsIgnoreCase("PFAM"))
487       {
488         afile = new PfamFile();
489       }
490       else if (format.equalsIgnoreCase("STH"))
491       {
492         afile = new StockholmFile(alignment);
493       }
494       else if (format.equalsIgnoreCase("AMSA"))
495       {
496         afile = new AMSAFile(alignment);
497       }
498       else if (format.equalsIgnoreCase("RNAML"))
499       {
500         afile = new RnamlFile();
501       }
502
503       else
504       {
505         throw new Exception(MessageManager.getString("error.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 }