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