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