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