JAL-1683 replace year/version strings with tokens in source
[jalview.git] / src / jalview / io / AppletFormatAdapter.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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
10  * of the License, or (at your option) any later version.
11  *
12  * Jalview is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15  * PURPOSE.  See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.io;
22
23 import jalview.api.AlignViewportI;
24 import jalview.datamodel.Alignment;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.AlignmentView;
28 import jalview.util.MessageManager;
29
30 import java.io.File;
31 import java.io.InputStream;
32 import java.util.List;
33
34 /**
35  * A low level class for alignment and feature IO with alignment formatting
36  * methods used by both applet and application for generating flat alignment
37  * files. It also holds the lists of magic format names that the applet and
38  * application will allow the user to read or write files with.
39  *
40  * @author $author$
41  * @version $Revision$
42  */
43 public class AppletFormatAdapter
44 {
45   /**
46    * List of valid format strings used in the isValidFormat method
47    */
48   public static final String[] READABLE_FORMATS = new String[]
49           { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
50       "PDB", "JnetFile", "RNAML", PhylipFile.FILE_DESC, "HTML" }; // ,
51                                                                               // "SimpleBLAST"
52                                                                               // };
53
54   /**
55    * List of valid format strings for use by callers of the formatSequences
56    * method
57    */
58   public static final String[] WRITEABLE_FORMATS = new String[]
59           { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
60     "STH", PhylipFile.FILE_DESC };
61
62   /**
63    * List of extensions corresponding to file format types in WRITABLE_FNAMES
64    * that are writable by the application.
65    */
66   public static final String[] WRITABLE_EXTENSIONS = new String[]
67   { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
68       "sto,stk", PhylipFile.FILE_EXT, "jvp" };
69
70   /**
71    * List of writable formats by the application. Order must correspond with the
72    * WRITABLE_EXTENSIONS list of formats.
73    */
74   public static final String[] WRITABLE_FNAMES = new String[]
75   { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
76       PhylipFile.FILE_DESC, "Jalview" };
77
78   /**
79    * List of readable format file extensions by application in order
80    * corresponding to READABLE_FNAMES
81    */
82   public static final String[] READABLE_EXTENSIONS = new String[]
83           { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
84       "jar,jvp", "sto,stk", "xml,rnaml", PhylipFile.FILE_EXT,
85  "html" }; // ".blast"
86
87   /**
88    * List of readable formats by application in order corresponding to
89    * READABLE_EXTENSIONS
90    */
91   public static final String[] READABLE_FNAMES = new String[]
92           { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview",
93       "Stockholm", "RNAML", PhylipFile.FILE_DESC, "HTML" };// ,
94
95   // "SimpleBLAST"
96   // };
97
98   public static String INVALID_CHARACTERS = "Contains invalid characters";
99
100   // TODO: make these messages dynamic
101   public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
102           + prettyPrint(READABLE_FORMATS);
103
104   /**
105    *
106    * @param els
107    * @return grammatically correct(ish) list consisting of els elements.
108    */
109   public static String prettyPrint(String[] els)
110   {
111     StringBuffer list = new StringBuffer();
112     for (int i = 0, iSize = els.length - 1; i < iSize; i++)
113     {
114       list.append(els[i]);
115       list.append(", ");
116     }
117     list.append(" and " + els[els.length - 1] + ".");
118     return list.toString();
119   }
120
121   public static String FILE = "File";
122
123   public static String URL = "URL";
124
125   public static String PASTE = "Paste";
126
127   public static String CLASSLOADER = "ClassLoader";
128
129   /**
130    * add jalview-derived non-secondary structure annotation from PDB structure
131    */
132   boolean annotFromStructure = false;
133
134   /**
135    * add secondary structure from PDB data with built-in algorithms
136    */
137   boolean localSecondaryStruct = false;
138
139   /**
140    * process PDB data with web services
141    */
142   boolean serviceSecondaryStruct = false;
143
144   AlignFile afile = null;
145
146   String inFile;
147
148   /**
149    * character used to write newlines
150    */
151   protected String newline = System.getProperty("line.separator");
152
153   public void setNewlineString(String nl)
154   {
155     newline = nl;
156   }
157
158   public String getNewlineString()
159   {
160     return newline;
161   }
162
163   /**
164    * check that this format is valid for reading
165    *
166    * @param format
167    *          a format string to be compared with READABLE_FORMATS
168    * @return true if format is readable
169    */
170   public static final boolean isValidFormat(String format)
171   {
172     return isValidFormat(format, false);
173   }
174
175   /**
176    * validate format is valid for IO
177    *
178    * @param format
179    *          a format string to be compared with either READABLE_FORMATS or
180    *          WRITEABLE_FORMATS
181    * @param forwriting
182    *          when true, format is checked for containment in WRITEABLE_FORMATS
183    * @return true if format is valid
184    */
185   public static final boolean isValidFormat(String format,
186           boolean forwriting)
187   {
188     boolean valid = false;
189     String[] format_list = (forwriting) ? WRITEABLE_FORMATS
190             : READABLE_FORMATS;
191     for (String element : format_list)
192     {
193       if (element.equalsIgnoreCase(format))
194       {
195         return true;
196       }
197     }
198
199     return valid;
200   }
201
202   /**
203    * Constructs the correct filetype parser for a characterised datasource
204    *
205    * @param inFile
206    *          data/data location
207    * @param type
208    *          type of datasource
209    * @param format
210    *          File format of data provided by datasource
211    *
212    * @return DOCUMENT ME!
213    */
214   public Alignment readFile(String inFile, String type, String format)
215           throws java.io.IOException
216   {
217     // TODO: generalise mapping between format string and io. class instances
218     // using Constructor.invoke reflection
219     this.inFile = inFile;
220     try
221     {
222       if (format.equals("FASTA"))
223       {
224         afile = new FastaFile(inFile, type);
225       }
226       else if (format.equals("MSF"))
227       {
228         afile = new MSFfile(inFile, type);
229       }
230       else if (format.equals("PileUp"))
231       {
232         afile = new PileUpfile(inFile, type);
233       }
234       else if (format.equals("CLUSTAL"))
235       {
236         afile = new ClustalFile(inFile, type);
237       }
238       else if (format.equals("BLC"))
239       {
240         afile = new BLCFile(inFile, type);
241       }
242       else if (format.equals("PIR"))
243       {
244         afile = new PIRFile(inFile, type);
245       }
246       else if (format.equals("PFAM"))
247       {
248         afile = new PfamFile(inFile, type);
249       }
250       else if (format.equals("JnetFile"))
251       {
252         afile = new JPredFile(inFile, type);
253         ((JPredFile) afile).removeNonSequences();
254       }
255       else if (format.equals("PDB"))
256       {
257         afile = new MCview.PDBfile(annotFromStructure,
258                 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
259         // Uncomment to test Jmol data based PDB processing: JAL-1213
260         // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
261       }
262       else if (format.equals("STH"))
263       {
264         afile = new StockholmFile(inFile, type);
265       }
266       else if (format.equals("SimpleBLAST"))
267       {
268         afile = new SimpleBlastFile(inFile, type);
269       }
270       else if (format.equals(PhylipFile.FILE_DESC))
271       {
272         afile = new PhylipFile(inFile, type);
273       }
274       // else if (format.equals(HtmlFile.FILE_DESC))
275       // {
276       // afile = new HtmlFile(inFile, type);
277       // }
278       else if (format.equals("RNAML"))
279       {
280         afile = new RnamlFile(inFile, type);
281       }
282
283       Alignment al = new Alignment(afile.getSeqsAsArray());
284
285       afile.addAnnotations(al);
286
287       return al;
288     } catch (Exception e)
289     {
290       e.printStackTrace();
291       System.err.println("Failed to read alignment using the '" + format
292               + "' reader.\n" + e);
293
294       if (e.getMessage() != null
295               && e.getMessage().startsWith(INVALID_CHARACTERS))
296       {
297         throw new java.io.IOException(e.getMessage());
298       }
299
300       // Finally test if the user has pasted just the sequence, no id
301       if (type.equalsIgnoreCase("Paste"))
302       {
303         try
304         {
305           // Possible sequence is just residues with no label
306           afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
307           Alignment al = new Alignment(afile.getSeqsAsArray());
308           afile.addAnnotations(al);
309           return al;
310
311         } catch (Exception ex)
312         {
313           if (ex.toString().startsWith(INVALID_CHARACTERS))
314           {
315             throw new java.io.IOException(e.getMessage());
316           }
317
318           ex.printStackTrace();
319         }
320       }
321
322       // If we get to this stage, the format was not supported
323       throw new java.io.IOException(SUPPORTED_FORMATS);
324     }
325   }
326
327   /**
328    * Constructs the correct filetype parser for an already open datasource
329    *
330    * @param source
331    *          an existing datasource
332    * @param format
333    *          File format of data that will be provided by datasource
334    *
335    * @return DOCUMENT ME!
336    */
337   public AlignmentI readFromFile(FileParse source, String format)
338           throws java.io.IOException
339   {
340     // TODO: generalise mapping between format string and io. class instances
341     // using Constructor.invoke reflection
342     // This is exactly the same as the readFile method except we substitute
343     // 'inFile, type' with 'source'
344     this.inFile = source.getInFile();
345     String type = source.type;
346     try
347     {
348       if (format.equals("FASTA"))
349       {
350         afile = new FastaFile(source);
351       }
352       else if (format.equals("MSF"))
353       {
354         afile = new MSFfile(source);
355       }
356       else if (format.equals("PileUp"))
357       {
358         afile = new PileUpfile(source);
359       }
360       else if (format.equals("CLUSTAL"))
361       {
362         afile = new ClustalFile(source);
363       }
364       else if (format.equals("BLC"))
365       {
366         afile = new BLCFile(source);
367       }
368       else if (format.equals("PIR"))
369       {
370         afile = new PIRFile(source);
371       }
372       else if (format.equals("PFAM"))
373       {
374         afile = new PfamFile(source);
375       }
376       else if (format.equals("JnetFile"))
377       {
378         afile = new JPredFile(source);
379         ((JPredFile) afile).removeNonSequences();
380       }
381       else if (format.equals("PDB"))
382       {
383         afile = new MCview.PDBfile(annotFromStructure,
384                 localSecondaryStruct, serviceSecondaryStruct, source);
385       }
386       else if (format.equals("STH"))
387       {
388         afile = new StockholmFile(source);
389       }
390       else if (format.equals("RNAML"))
391       {
392         afile = new RnamlFile(source);
393       }
394       else if (format.equals("SimpleBLAST"))
395       {
396         afile = new SimpleBlastFile(source);
397       }
398       else if (format.equals(PhylipFile.FILE_DESC))
399       {
400         afile = new PhylipFile(source);
401       }
402       // else if (format.equals(HtmlFile.FILE_DESC))
403       // {
404       // afile = new HtmlFile(source);
405       // }
406       Alignment al = new Alignment(afile.getSeqsAsArray());
407
408       afile.addAnnotations(al);
409
410       return al;
411     } catch (Exception e)
412     {
413       e.printStackTrace();
414       System.err.println("Failed to read alignment using the '" + format
415               + "' reader.\n" + e);
416
417       if (e.getMessage() != null
418               && e.getMessage().startsWith(INVALID_CHARACTERS))
419       {
420         throw new java.io.IOException(e.getMessage());
421       }
422
423       // Finally test if the user has pasted just the sequence, no id
424       if (type.equalsIgnoreCase("Paste"))
425       {
426         try
427         {
428           // Possible sequence is just residues with no label
429           afile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
430           Alignment al = new Alignment(afile.getSeqsAsArray());
431           afile.addAnnotations(al);
432           return al;
433
434         } catch (Exception ex)
435         {
436           if (ex.toString().startsWith(INVALID_CHARACTERS))
437           {
438             throw new java.io.IOException(e.getMessage());
439           }
440
441           ex.printStackTrace();
442         }
443       }
444
445       // If we get to this stage, the format was not supported
446       throw new java.io.IOException(SUPPORTED_FORMATS);
447     }
448   }
449
450
451   /**
452    * create an alignment flatfile from a Jalview alignment view
453    * @param format
454    * @param jvsuffix
455    * @param av
456    * @param selectedOnly
457    * @return flatfile in a string
458    */
459   public String formatSequences(String format, boolean jvsuffix,
460           AlignViewportI av, boolean selectedOnly)
461   {
462
463     AlignmentView selvew = av.getAlignmentView(selectedOnly, false);
464     AlignmentI aselview = selvew.getVisibleAlignment(av
465             .getGapCharacter());
466     List<AlignmentAnnotation> ala = (av
467             .getVisibleAlignmentAnnotation(selectedOnly));
468     if (ala != null)
469     {
470       for (AlignmentAnnotation aa : ala)
471       {
472         aselview.addAnnotation(aa);
473       }
474     }
475
476     return formatSequences(format, aselview, jvsuffix);
477   }
478
479   /**
480    * Construct an output class for an alignment in a particular filetype TODO:
481    * allow caller to detect errors and warnings encountered when generating
482    * output
483    *
484    * @param format
485    *          string name of alignment format
486    * @param alignment
487    *          the alignment to be written out
488    * @param jvsuffix
489    *          passed to AlnFile class controls whether /START-END is added to
490    *          sequence names
491    *
492    * @return alignment flat file contents
493    */
494   public String formatSequences(String format, AlignmentI alignment,
495           boolean jvsuffix)
496   {
497     try
498     {
499       AlignFile afile = null;
500
501       if (format.equalsIgnoreCase("FASTA"))
502       {
503         afile = new FastaFile();
504       }
505       else if (format.equalsIgnoreCase("MSF"))
506       {
507         afile = new MSFfile();
508       }
509       else if (format.equalsIgnoreCase("PileUp"))
510       {
511         afile = new PileUpfile();
512       }
513       else if (format.equalsIgnoreCase("CLUSTAL"))
514       {
515         afile = new ClustalFile();
516       }
517       else if (format.equalsIgnoreCase("BLC"))
518       {
519         afile = new BLCFile();
520       }
521       else if (format.equalsIgnoreCase("PIR"))
522       {
523         afile = new PIRFile();
524       }
525       else if (format.equalsIgnoreCase("PFAM"))
526       {
527         afile = new PfamFile();
528       }
529       else if (format.equalsIgnoreCase("STH"))
530       {
531         afile = new StockholmFile(alignment);
532       }
533       else if (format.equalsIgnoreCase("AMSA"))
534       {
535         afile = new AMSAFile(alignment);
536       }
537       else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
538       {
539         afile = new PhylipFile();
540       }
541       // else if (format.equalsIgnoreCase(HtmlFile.FILE_DESC))
542       // {
543       // afile = new HtmlFile();
544       // }
545       else if (format.equalsIgnoreCase("RNAML"))
546       {
547         afile = new RnamlFile();
548       }
549
550       else
551       {
552         throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
553       }
554       afile.setNewlineString(newline);
555       afile.addJVSuffix(jvsuffix);
556
557       afile.setSeqs(alignment.getSequencesArray());
558
559       String afileresp = afile.print();
560       if (afile.hasWarningMessage())
561       {
562         System.err.println("Warning raised when writing as " + format
563                 + " : " + afile.getWarningMessage());
564       }
565       return afileresp;
566     } catch (Exception e)
567     {
568       System.err.println("Failed to write alignment as a '" + format
569               + "' file\n");
570       e.printStackTrace();
571     }
572
573     return null;
574   }
575
576   public static String checkProtocol(String file)
577   {
578     String protocol = FILE;
579     String ft = file.toLowerCase().trim();
580     if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
581             || ft.indexOf("file:") == 0)
582     {
583       protocol = URL;
584     }
585     return protocol;
586   }
587
588   public static void main(String[] args)
589   {
590     int i = 0;
591     while (i < args.length)
592     {
593       File f = new File(args[i]);
594       if (f.exists())
595       {
596         try
597         {
598           System.out.println("Reading file: " + f);
599           AppletFormatAdapter afa = new AppletFormatAdapter();
600           Runtime r = Runtime.getRuntime();
601           System.gc();
602           long memf = -r.totalMemory() + r.freeMemory();
603           long t1 = -System.currentTimeMillis();
604           Alignment al = afa.readFile(args[i], FILE,
605                   new IdentifyFile().Identify(args[i], FILE));
606           t1 += System.currentTimeMillis();
607           System.gc();
608           memf += r.totalMemory() - r.freeMemory();
609           if (al != null)
610           {
611             System.out.println("Alignment contains " + al.getHeight()
612                     + " sequences and " + al.getWidth() + " columns.");
613             try
614             {
615               System.out.println(new AppletFormatAdapter().formatSequences(
616                       "FASTA", al, true));
617             } catch (Exception e)
618             {
619               System.err
620               .println("Couln't format the alignment for output as a FASTA file.");
621               e.printStackTrace(System.err);
622             }
623           }
624           else
625           {
626             System.out.println("Couldn't read alignment");
627           }
628           System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
629           System.out
630           .println("Difference between free memory now and before is "
631                   + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
632         } catch (Exception e)
633         {
634           System.err.println("Exception when dealing with " + i
635                   + "'th argument: " + args[i] + "\n" + e);
636         }
637       }
638       else
639       {
640         System.err.println("Ignoring argument '" + args[i] + "' (" + i
641                 + "'th)- not a readable file.");
642       }
643       i++;
644     }
645   }
646
647   /**
648    * try to discover how to access the given file as a valid datasource that
649    * will be identified as the given type.
650    *
651    * @param file
652    * @param format
653    * @return protocol that yields the data parsable as the given type
654    */
655   public static String resolveProtocol(String file, String format)
656   {
657     return resolveProtocol(file, format, false);
658   }
659
660   public static String resolveProtocol(String file, String format,
661           boolean debug)
662   {
663     // TODO: test thoroughly!
664     String protocol = null;
665     if (debug)
666     {
667       System.out.println("resolving datasource started with:\n>>file\n"
668               + file + ">>endfile");
669     }
670
671     // This might throw a security exception in certain browsers
672     // Netscape Communicator for instance.
673     try
674     {
675       boolean rtn = false;
676       InputStream is = System.getSecurityManager().getClass()
677               .getResourceAsStream("/" + file);
678       if (is != null)
679       {
680         rtn = true;
681         is.close();
682       }
683       if (debug)
684       {
685         System.err.println("Resource '" + file + "' was "
686                 + (rtn ? "" : "not") + " located by classloader.");
687       }
688       ;
689       if (rtn)
690       {
691         protocol = AppletFormatAdapter.CLASSLOADER;
692       }
693
694     } catch (Exception ex)
695     {
696       System.err
697       .println("Exception checking resources: " + file + " " + ex);
698     }
699
700     if (file.indexOf("://") > -1)
701     {
702       protocol = AppletFormatAdapter.URL;
703     }
704     else
705     {
706       // skipping codebase prepend check.
707       protocol = AppletFormatAdapter.FILE;
708     }
709     FileParse fp = null;
710     try
711     {
712       if (debug)
713       {
714         System.out.println("Trying to get contents of resource as "
715                 + protocol + ":");
716       }
717       fp = new FileParse(file, protocol);
718       if (!fp.isValid())
719       {
720         fp = null;
721       }
722       else
723       {
724         if (debug)
725         {
726           System.out.println("Successful.");
727         }
728       }
729     } catch (Exception e)
730     {
731       if (debug)
732       {
733         System.err.println("Exception when accessing content: " + e);
734       }
735       fp = null;
736     }
737     if (fp == null)
738     {
739       if (debug)
740       {
741         System.out.println("Accessing as paste.");
742       }
743       protocol = AppletFormatAdapter.PASTE;
744       fp = null;
745       try
746       {
747         fp = new FileParse(file, protocol);
748         if (!fp.isValid())
749         {
750           fp = null;
751         }
752       } catch (Exception e)
753       {
754         System.err.println("Failed to access content as paste!");
755         e.printStackTrace();
756         fp = null;
757       }
758     }
759     if (fp == null)
760     {
761       return null;
762     }
763     if (format == null || format.length() == 0)
764     {
765       return protocol;
766     }
767     else
768     {
769       try
770       {
771         String idformat = new jalview.io.IdentifyFile().Identify(file,
772                 protocol);
773         if (idformat == null)
774         {
775           if (debug)
776           {
777             System.out.println("Format not identified. Inaccessible file.");
778           }
779           return null;
780         }
781         if (debug)
782         {
783           System.out.println("Format identified as " + idformat
784                   + "and expected as " + format);
785         }
786         if (idformat.equals(format))
787         {
788           if (debug)
789           {
790             System.out.println("Protocol identified as " + protocol);
791           }
792           return protocol;
793         }
794         else
795         {
796           if (debug)
797           {
798             System.out
799             .println("File deemed not accessible via " + protocol);
800           }
801           fp.close();
802           return null;
803         }
804       } catch (Exception e)
805       {
806         if (debug)
807         {
808           System.err.println("File deemed not accessible via " + protocol);
809           e.printStackTrace();
810         }
811         ;
812
813       }
814     }
815     return null;
816   }
817 }