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