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