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