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