v2
[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" , "RNAML"}; // , "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","xml" }; // ,
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","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    * 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       else if (format.equals("RNAML"))
237       {
238         afile = new RnamlFile(inFile, type);
239       }
240       
241       Alignment al = new Alignment(afile.getSeqsAsArray());
242
243       afile.addAnnotations(al);
244
245       return al;
246     } catch (Exception e)
247     {
248       e.printStackTrace();
249       System.err.println("Failed to read alignment using the '" + format
250               + "' reader.\n" + e);
251
252       if (e.getMessage() != null
253               && e.getMessage().startsWith(INVALID_CHARACTERS))
254       {
255         throw new java.io.IOException(e.getMessage());
256       }
257
258       // Finally test if the user has pasted just the sequence, no id
259       if (type.equalsIgnoreCase("Paste"))
260       {
261         try
262         {
263           // Possible sequence is just residues with no label
264           afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
265           Alignment al = new Alignment(afile.getSeqsAsArray());
266           afile.addAnnotations(al);
267           return al;
268
269         } catch (Exception ex)
270         {
271           if (ex.toString().startsWith(INVALID_CHARACTERS))
272           {
273             throw new java.io.IOException(e.getMessage());
274           }
275
276           ex.printStackTrace();
277         }
278       }
279
280       // If we get to this stage, the format was not supported
281       throw new java.io.IOException(SUPPORTED_FORMATS);
282     }
283   }
284
285   /**
286    * Constructs the correct filetype parser for an already open datasource
287    * 
288    * @param source
289    *          an existing datasource
290    * @param format
291    *          File format of data that will be provided by datasource
292    * 
293    * @return DOCUMENT ME!
294    */
295   public Alignment readFromFile(FileParse source, String format)
296           throws java.io.IOException
297   {
298     // TODO: generalise mapping between format string and io. class instances
299     // using Constructor.invoke reflection
300     // This is exactly the same as the readFile method except we substitute
301     // 'inFile, type' with 'source'
302     this.inFile = source.getInFile();
303     String type = source.type;
304     try
305     {
306       if (format.equals("FASTA"))
307       {
308         afile = new FastaFile(source);
309       }
310       else if (format.equals("MSF"))
311       {
312         afile = new MSFfile(source);
313       }
314       else if (format.equals("PileUp"))
315       {
316         afile = new PileUpfile(source);
317       }
318       else if (format.equals("CLUSTAL"))
319       {
320         afile = new ClustalFile(source);
321       }
322       else if (format.equals("BLC"))
323       {
324         afile = new BLCFile(source);
325       }
326       else if (format.equals("PIR"))
327       {
328         afile = new PIRFile(source);
329       }
330       else if (format.equals("PFAM"))
331       {
332         afile = new PfamFile(source);
333       }
334       else if (format.equals("JnetFile"))
335       {
336         afile = new JPredFile(source);
337         ((JPredFile) afile).removeNonSequences();
338       }
339       else if (format.equals("PDB"))
340       {
341         afile = new MCview.PDBfile(source);
342       }
343       else if (format.equals("STH"))
344       {
345         afile = new StockholmFile(source);
346       }
347       else if (format.equals("RNAML"))
348       {
349         afile = new RnamlFile(source);
350       }
351       else if (format.equals("SimpleBLAST"))
352       {
353         afile = new SimpleBlastFile(source);
354       }
355
356       Alignment al = new Alignment(afile.getSeqsAsArray());
357
358       afile.addAnnotations(al);
359
360       return al;
361     } catch (Exception e)
362     {
363       e.printStackTrace();
364       System.err.println("Failed to read alignment using the '" + format
365               + "' reader.\n" + e);
366
367       if (e.getMessage() != null
368               && e.getMessage().startsWith(INVALID_CHARACTERS))
369       {
370         throw new java.io.IOException(e.getMessage());
371       }
372
373       // Finally test if the user has pasted just the sequence, no id
374       if (type.equalsIgnoreCase("Paste"))
375       {
376         try
377         {
378           // Possible sequence is just residues with no label
379           afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
380           Alignment al = new Alignment(afile.getSeqsAsArray());
381           afile.addAnnotations(al);
382           return al;
383
384         } catch (Exception ex)
385         {
386           if (ex.toString().startsWith(INVALID_CHARACTERS))
387           {
388             throw new java.io.IOException(e.getMessage());
389           }
390
391           ex.printStackTrace();
392         }
393       }
394
395       // If we get to this stage, the format was not supported
396       throw new java.io.IOException(SUPPORTED_FORMATS);
397     }
398   }
399
400   /**
401    * Construct an output class for an alignment in a particular filetype TODO:
402    * allow caller to detect errors and warnings encountered when generating
403    * output
404    * 
405    * @param format
406    *          string name of alignment format
407    * @param alignment
408    *          the alignment to be written out
409    * @param jvsuffix
410    *          passed to AlnFile class controls whether /START-END is added to
411    *          sequence names
412    * 
413    * @return alignment flat file contents
414    */
415   public String formatSequences(String format, AlignmentI alignment,
416           boolean jvsuffix)
417   {
418     try
419     {
420       AlignFile afile = null;
421
422       if (format.equalsIgnoreCase("FASTA"))
423       {
424         afile = new FastaFile();
425       }
426       else if (format.equalsIgnoreCase("MSF"))
427       {
428         afile = new MSFfile();
429       }
430       else if (format.equalsIgnoreCase("PileUp"))
431       {
432         afile = new PileUpfile();
433       }
434       else if (format.equalsIgnoreCase("CLUSTAL"))
435       {
436         afile = new ClustalFile();
437       }
438       else if (format.equalsIgnoreCase("BLC"))
439       {
440         afile = new BLCFile();
441       }
442       else if (format.equalsIgnoreCase("PIR"))
443       {
444         afile = new PIRFile();
445       }
446       else if (format.equalsIgnoreCase("PFAM"))
447       {
448         afile = new PfamFile();
449       }
450       else if (format.equalsIgnoreCase("STH"))
451       {
452         afile = new StockholmFile();
453       }
454       else if (format.equalsIgnoreCase("AMSA"))
455       {
456         afile = new AMSAFile(alignment);
457       }
458       else if (format.equalsIgnoreCase("RNAML"))
459       {
460         afile = new RnamlFile();
461       }
462       
463       else
464       {
465         throw new Exception(
466                 "Implementation error: Unknown file format string");
467       }
468       afile.setNewlineString(newline);
469       afile.addJVSuffix(jvsuffix);
470
471       afile.setSeqs(alignment.getSequencesArray());
472
473       String afileresp = afile.print();
474       if (afile.hasWarningMessage())
475       {
476         System.err.println("Warning raised when writing as " + format
477                 + " : " + afile.getWarningMessage());
478       }
479       return afileresp;
480     } catch (Exception e)
481     {
482       System.err.println("Failed to write alignment as a '" + format
483               + "' file\n");
484       e.printStackTrace();
485     }
486
487     return null;
488   }
489
490   public static String checkProtocol(String file)
491   {
492     String protocol = FILE;
493     String ft = file.toLowerCase().trim();
494     if (ft.indexOf("http:") ==0 || ft.indexOf("https:") ==0 || ft.indexOf("file:") == 0)
495     {
496       protocol = URL;
497     }
498     return protocol;
499   }
500
501   public static void main(String[] args)
502   {
503     int i = 0;
504     while (i < args.length)
505     {
506       File f = new File(args[i]);
507       if (f.exists())
508       {
509         try
510         {
511           System.out.println("Reading file: " + f);
512           AppletFormatAdapter afa = new AppletFormatAdapter();
513           Runtime r = Runtime.getRuntime();
514           System.gc();
515           long memf = -r.totalMemory() + r.freeMemory();
516           long t1 = -System.currentTimeMillis();
517           Alignment al = afa.readFile(args[i], FILE,
518                   new IdentifyFile().Identify(args[i], FILE));
519           t1 += System.currentTimeMillis();
520           System.gc();
521           memf += r.totalMemory() - r.freeMemory();
522           if (al != null)
523           {
524             System.out.println("Alignment contains " + al.getHeight()
525                     + " sequences and " + al.getWidth() + " columns.");
526             try
527             {
528               System.out.println(new AppletFormatAdapter().formatSequences(
529                       "FASTA", al, true));
530             } catch (Exception e)
531             {
532               System.err
533                       .println("Couln't format the alignment for output as a FASTA file.");
534               e.printStackTrace(System.err);
535             }
536           }
537           else
538           {
539             System.out.println("Couldn't read alignment");
540           }
541           System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
542           System.out
543                   .println("Difference between free memory now and before is "
544                           + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
545
546         } catch (Exception e)
547         {
548           System.err.println("Exception when dealing with " + i
549                   + "'th argument: " + args[i] + "\n" + e);
550         }
551       }
552       else
553       {
554         System.err.println("Ignoring argument '" + args[i] + "' (" + i
555                 + "'th)- not a readable file.");
556       }
557       i++;
558     }
559   }
560
561   /**
562    * try to discover how to access the given file as a valid datasource that
563    * will be identified as the given type.
564    * 
565    * @param file
566    * @param format
567    * @return protocol that yields the data parsable as the given type
568    */
569   public static String resolveProtocol(String file, String format)
570   {
571     return resolveProtocol(file, format, false);
572   }
573
574   public static String resolveProtocol(String file, String format,
575           boolean debug)
576   {
577     // TODO: test thoroughly!
578     String protocol = null;
579     if (debug)
580     {
581       System.out.println("resolving datasource started with:\n>>file\n"
582               + file + ">>endfile");
583     }
584
585     // This might throw a security exception in certain browsers
586     // Netscape Communicator for instance.
587     try
588     {
589       boolean rtn = false;
590       InputStream is = System.getSecurityManager().getClass()
591               .getResourceAsStream("/" + file);
592       if (is != null)
593       {
594         rtn = true;
595         is.close();
596       }
597       if (debug)
598       {
599         System.err.println("Resource '" + file + "' was "
600                 + (rtn ? "" : "not") + " located by classloader.");
601       }
602       ;
603       if (rtn)
604       {
605         protocol = AppletFormatAdapter.CLASSLOADER;
606       }
607
608     } catch (Exception ex)
609     {
610       System.err
611               .println("Exception checking resources: " + file + " " + ex);
612     }
613
614     if (file.indexOf("://") > -1)
615     {
616       protocol = AppletFormatAdapter.URL;
617     }
618     else
619     {
620       // skipping codebase prepend check.
621       protocol = AppletFormatAdapter.FILE;
622     }
623     FileParse fp = null;
624     try
625     {
626       if (debug)
627       {
628         System.out.println("Trying to get contents of resource as "
629                 + protocol + ":");
630       }
631       fp = new FileParse(file, protocol);
632       if (!fp.isValid())
633       {
634         fp = null;
635       }
636       else
637       {
638         if (debug)
639         {
640           System.out.println("Successful.");
641         }
642       }
643     } catch (Exception e)
644     {
645       if (debug)
646       {
647         System.err.println("Exception when accessing content: " + e);
648       }
649       fp = null;
650     }
651     if (fp == null)
652     {
653       if (debug)
654       {
655         System.out.println("Accessing as paste.");
656       }
657       protocol = AppletFormatAdapter.PASTE;
658       fp = null;
659       try
660       {
661         fp = new FileParse(file, protocol);
662         if (!fp.isValid())
663         {
664           fp = null;
665         }
666       } catch (Exception e)
667       {
668         System.err.println("Failed to access content as paste!");
669         e.printStackTrace();
670         fp = null;
671       }
672     }
673     if (fp == null)
674     {
675       return null;
676     }
677     if (format == null || format.length() == 0)
678     {
679       return protocol;
680     }
681     else
682     {
683       try
684       {
685         String idformat = new jalview.io.IdentifyFile().Identify(file,
686                 protocol);
687         if (idformat == null)
688         {
689           if (debug)
690           {
691             System.out.println("Format not identified. Inaccessible file.");
692           }
693           return null;
694         }
695         if (debug)
696         {
697           System.out.println("Format identified as " + idformat
698                   + "and expected as " + format);
699         }
700         if (idformat.equals(format))
701         {
702           if (debug)
703           {
704             System.out.println("Protocol identified as " + protocol);
705           }
706           return protocol;
707         }
708         else
709         {
710           if (debug)
711           {
712             System.out
713                     .println("File deemed not accessible via " + protocol);
714           }
715           fp.close();
716           return null;
717         }
718       } catch (Exception e)
719       {
720         if (debug)
721         {
722           System.err.println("File deemed not accessible via " + protocol);
723           e.printStackTrace();
724         }
725         ;
726
727       }
728     }
729     return null;
730   }
731 }