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