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