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