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