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