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