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