Add support RNAML format
[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         //if (contient de l'ARN)
227         //  {
228           System.out.println(inFile); //donne le path
229           
230                 //new URL = http://paradise-ibmc.u-strasbg.fr/webservices/annotate3d?data=inFile;
231           //afile = new RnamlFile(inFile, type);
232                 
233           //}
234         afile = new MCview.PDBfile(inFile, type);
235         
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 Alignment 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();
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 || ft.indexOf("file:") == 0)
504     {
505       protocol = URL;
506     }
507     return protocol;
508   }
509
510   public static void main(String[] args)
511   {
512     int i = 0;
513     while (i < args.length)
514     {
515       File f = new File(args[i]);
516       if (f.exists())
517       {
518         try
519         {
520           System.out.println("Reading file: " + f);
521           AppletFormatAdapter afa = new AppletFormatAdapter();
522           Runtime r = Runtime.getRuntime();
523           System.gc();
524           long memf = -r.totalMemory() + r.freeMemory();
525           long t1 = -System.currentTimeMillis();
526           Alignment al = afa.readFile(args[i], FILE,
527                   new IdentifyFile().Identify(args[i], FILE));
528           t1 += System.currentTimeMillis();
529           System.gc();
530           memf += r.totalMemory() - r.freeMemory();
531           if (al != null)
532           {
533             System.out.println("Alignment contains " + al.getHeight()
534                     + " sequences and " + al.getWidth() + " columns.");
535             try
536             {
537               System.out.println(new AppletFormatAdapter().formatSequences(
538                       "FASTA", al, true));
539             } catch (Exception e)
540             {
541               System.err
542                       .println("Couln't format the alignment for output as a FASTA file.");
543               e.printStackTrace(System.err);
544             }
545           }
546           else
547           {
548             System.out.println("Couldn't read alignment");
549           }
550           System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
551           System.out
552                   .println("Difference between free memory now and before is "
553                           + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
554
555         } catch (Exception e)
556         {
557           System.err.println("Exception when dealing with " + i
558                   + "'th argument: " + args[i] + "\n" + e);
559         }
560       }
561       else
562       {
563         System.err.println("Ignoring argument '" + args[i] + "' (" + i
564                 + "'th)- not a readable file.");
565       }
566       i++;
567     }
568   }
569
570   /**
571    * try to discover how to access the given file as a valid datasource that
572    * will be identified as the given type.
573    * 
574    * @param file
575    * @param format
576    * @return protocol that yields the data parsable as the given type
577    */
578   public static String resolveProtocol(String file, String format)
579   {
580     return resolveProtocol(file, format, false);
581   }
582
583   public static String resolveProtocol(String file, String format,
584           boolean debug)
585   {
586     // TODO: test thoroughly!
587     String protocol = null;
588     if (debug)
589     {
590       System.out.println("resolving datasource started with:\n>>file\n"
591               + file + ">>endfile");
592     }
593
594     // This might throw a security exception in certain browsers
595     // Netscape Communicator for instance.
596     try
597     {
598       boolean rtn = false;
599       InputStream is = System.getSecurityManager().getClass()
600               .getResourceAsStream("/" + file);
601       if (is != null)
602       {
603         rtn = true;
604         is.close();
605       }
606       if (debug)
607       {
608         System.err.println("Resource '" + file + "' was "
609                 + (rtn ? "" : "not") + " located by classloader.");
610       }
611       ;
612       if (rtn)
613       {
614         protocol = AppletFormatAdapter.CLASSLOADER;
615       }
616
617     } catch (Exception ex)
618     {
619       System.err
620               .println("Exception checking resources: " + file + " " + ex);
621     }
622
623     if (file.indexOf("://") > -1)
624     {
625       protocol = AppletFormatAdapter.URL;
626     }
627     else
628     {
629       // skipping codebase prepend check.
630       protocol = AppletFormatAdapter.FILE;
631     }
632     FileParse fp = null;
633     try
634     {
635       if (debug)
636       {
637         System.out.println("Trying to get contents of resource as "
638                 + protocol + ":");
639       }
640       fp = new FileParse(file, protocol);
641       if (!fp.isValid())
642       {
643         fp = null;
644       }
645       else
646       {
647         if (debug)
648         {
649           System.out.println("Successful.");
650         }
651       }
652     } catch (Exception e)
653     {
654       if (debug)
655       {
656         System.err.println("Exception when accessing content: " + e);
657       }
658       fp = null;
659     }
660     if (fp == null)
661     {
662       if (debug)
663       {
664         System.out.println("Accessing as paste.");
665       }
666       protocol = AppletFormatAdapter.PASTE;
667       fp = null;
668       try
669       {
670         fp = new FileParse(file, protocol);
671         if (!fp.isValid())
672         {
673           fp = null;
674         }
675       } catch (Exception e)
676       {
677         System.err.println("Failed to access content as paste!");
678         e.printStackTrace();
679         fp = null;
680       }
681     }
682     if (fp == null)
683     {
684       return null;
685     }
686     if (format == null || format.length() == 0)
687     {
688       return protocol;
689     }
690     else
691     {
692       try
693       {
694         String idformat = new jalview.io.IdentifyFile().Identify(file,
695                 protocol);
696         if (idformat == null)
697         {
698           if (debug)
699           {
700             System.out.println("Format not identified. Inaccessible file.");
701           }
702           return null;
703         }
704         if (debug)
705         {
706           System.out.println("Format identified as " + idformat
707                   + "and expected as " + format);
708         }
709         if (idformat.equals(format))
710         {
711           if (debug)
712           {
713             System.out.println("Protocol identified as " + protocol);
714           }
715           return protocol;
716         }
717         else
718         {
719           if (debug)
720           {
721             System.out
722                     .println("File deemed not accessible via " + protocol);
723           }
724           fp.close();
725           return null;
726         }
727       } catch (Exception e)
728       {
729         if (debug)
730         {
731           System.err.println("File deemed not accessible via " + protocol);
732           e.printStackTrace();
733         }
734         ;
735
736       }
737     }
738     return null;
739   }
740 }