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