JAL-3032 part2 local file reading by JFileChooser
[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.AlignExportSettingI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.AlignmentView;
29 import jalview.datamodel.PDBEntry.Type;
30 import jalview.datamodel.SequenceI;
31 import jalview.ext.jmol.JmolParser;
32 import jalview.structure.StructureImportSettings;
33
34 import java.io.File;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.util.List;
38
39 /**
40  * A low level class for alignment and feature IO with alignment formatting
41  * methods used by both applet and application for generating flat alignment
42  * files. It also holds the lists of magic format names that the applet and
43  * application will allow the user to read or write files with.
44  *
45  * @author $author$
46  * @version $Revision$
47  */
48 public class AppletFormatAdapter
49 {
50   private AlignmentViewPanel viewpanel;
51
52   /**
53    * add jalview-derived non-secondary structure annotation from PDB structure
54    */
55   boolean annotFromStructure = false;
56
57   /**
58    * add secondary structure from PDB data with built-in algorithms
59    */
60   boolean localSecondaryStruct = false;
61
62   /**
63    * process PDB data with web services
64    */
65   boolean serviceSecondaryStruct = false;
66
67   private AlignmentFileReaderI alignFile = null;
68
69   String inFile;
70
71   /**
72    * character used to write newlines
73    */
74   protected String newline = System.getProperty("line.separator");
75
76   private AlignExportSettingI exportSettings;
77
78   private File selectedFile;
79
80   public static String INVALID_CHARACTERS = "Contains invalid characters";
81
82   /**
83    * Returns an error message with a list of supported readable file formats
84    * 
85    * @return
86    */
87   public static String getSupportedFormats()
88   {
89     return "Formats currently supported are\n"
90             + prettyPrint(FileFormats.getInstance().getReadableFormats());
91   }
92
93   public AppletFormatAdapter()
94   {
95   }
96
97   public AppletFormatAdapter(AlignmentViewPanel viewpanel)
98   {
99     this.viewpanel = viewpanel;
100   }
101
102   public AppletFormatAdapter(AlignmentViewPanel alignPanel,
103           AlignExportSettingI settings)
104   {
105     viewpanel = alignPanel;
106     exportSettings = settings;
107   }
108
109   /**
110    * Formats a grammatically correct(ish) list consisting of the given objects
111    * 
112    * @param things
113    * @return
114    */
115   public static String prettyPrint(List<? extends Object> things)
116   {
117     StringBuffer list = new StringBuffer();
118     for (int i = 0, iSize = things.size() - 1; i < iSize; i++)
119     {
120       list.append(things.get(i).toString());
121       list.append(", ");
122     }
123     // could i18n 'and' here
124     list.append(" and " + things.get(things.size() - 1).toString() + ".");
125     return list.toString();
126   }
127
128   public void setNewlineString(String nl)
129   {
130     newline = nl;
131   }
132
133   public String getNewlineString()
134   {
135     return newline;
136   }
137
138   /**
139    * Constructs the correct filetype parser for a characterised datasource
140    *
141    * @param inFile
142    *          data/data location
143    * @param sourceType
144    *          type of datasource
145    * @param fileFormat
146    *
147    * @return
148    */
149   public AlignmentI readFile(String file, DataSourceType sourceType,
150           FileFormatI fileFormat) throws IOException
151   {
152     return readFile(null, file, sourceType, fileFormat);
153   }
154   
155   public AlignmentI readFile(File selectedFile, String file, DataSourceType sourceType,
156           FileFormatI fileFormat) throws IOException
157   {
158
159     this.selectedFile = selectedFile;
160     if (selectedFile != null)
161       this.inFile = selectedFile.getPath();
162     this.inFile = file;
163     try
164     {
165       if (fileFormat.isStructureFile())
166       {
167         String structureParser = StructureImportSettings
168                 .getDefaultPDBFileParser();
169         boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
170                 StructureImportSettings.StructureParser.JMOL_PARSER
171                         .toString());
172         StructureImportSettings.addSettings(annotFromStructure,
173                 localSecondaryStruct, serviceSecondaryStruct);
174         if (isParseWithJMOL)
175         {
176           // needs a File option
177           alignFile = new JmolParser(inFile, sourceType);
178         }
179         else
180         {
181           // todo is MCview parsing obsolete yet? JAL-2120
182           StructureImportSettings.setShowSeqFeatures(true);
183           alignFile = new MCview.PDBfile(annotFromStructure,
184                   localSecondaryStruct, serviceSecondaryStruct, inFile,
185                   sourceType);
186         }
187         ((StructureFile) alignFile).setDbRefType(
188                 FileFormat.PDB.equals(fileFormat) ? Type.PDB : Type.MMCIF);
189       }
190       else if (selectedFile != null) {
191         alignFile = fileFormat.getReader(new FileParse(selectedFile, sourceType));
192       } else 
193       {
194         // alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
195         alignFile = fileFormat.getReader(new FileParse(inFile, sourceType));
196       }
197       return buildAlignmentFromFile();
198     } catch (Exception e)
199     {
200       e.printStackTrace();
201       System.err.println("Failed to read alignment using the '" + fileFormat
202               + "' reader.\n" + e);
203
204       if (e.getMessage() != null
205               && e.getMessage().startsWith(INVALID_CHARACTERS))
206       {
207         throw new IOException(e.getMessage());
208       }
209
210       // Finally test if the user has pasted just the sequence, no id
211       if (sourceType == DataSourceType.PASTE)
212       {
213         try
214         {
215           // Possible sequence is just residues with no label
216           alignFile = new FastaFile(">UNKNOWN\n" + inFile,
217                   DataSourceType.PASTE);
218           return buildAlignmentFromFile();
219
220         } catch (Exception ex)
221         {
222           if (ex.toString().startsWith(INVALID_CHARACTERS))
223           {
224             throw new IOException(e.getMessage());
225           }
226
227           ex.printStackTrace();
228         }
229       }
230       if (FileFormat.Html.equals(fileFormat))
231       {
232         throw new IOException(e.getMessage());
233       }
234     }
235     throw new FileFormatException(getSupportedFormats());
236   }
237
238   /**
239    * Constructs the correct filetype parser for an already open datasource
240    *
241    * @param source
242    *          an existing datasource
243    * @param format
244    *          File format of data that will be provided by datasource
245    *
246    * @return
247    */
248   public AlignmentI readFromFile(FileParse source, FileFormatI format)
249           throws IOException
250   {
251     this.inFile = source.getInFile();
252     DataSourceType type = source.dataSourceType;
253     try
254     {
255       if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
256       {
257         // TODO obtain config value from preference settings
258         boolean isParseWithJMOL = false;
259         if (isParseWithJMOL)
260         {
261           StructureImportSettings.addSettings(annotFromStructure,
262                   localSecondaryStruct, serviceSecondaryStruct);
263           alignFile = new JmolParser(source);
264         }
265         else
266         {
267           StructureImportSettings.setShowSeqFeatures(true);
268           alignFile = new MCview.PDBfile(annotFromStructure,
269                   localSecondaryStruct, serviceSecondaryStruct, source);
270         }
271         ((StructureFile) alignFile).setDbRefType(Type.PDB);
272       }
273       else
274       {
275         alignFile = format.getReader(source);
276       }
277
278       return buildAlignmentFromFile();
279
280     } catch (Exception e)
281     {
282       e.printStackTrace();
283       System.err.println("Failed to read alignment using the '" + format
284               + "' reader.\n" + e);
285
286       if (e.getMessage() != null
287               && e.getMessage().startsWith(INVALID_CHARACTERS))
288       {
289         throw new FileFormatException(e.getMessage());
290       }
291
292       // Finally test if the user has pasted just the sequence, no id
293       if (type == DataSourceType.PASTE)
294       {
295         try
296         {
297           // Possible sequence is just residues with no label
298           alignFile = new FastaFile(">UNKNOWN\n" + inFile,
299                   DataSourceType.PASTE);
300           return buildAlignmentFromFile();
301
302         } catch (Exception ex)
303         {
304           if (ex.toString().startsWith(INVALID_CHARACTERS))
305           {
306             throw new IOException(e.getMessage());
307           }
308
309           ex.printStackTrace();
310         }
311       }
312
313       // If we get to this stage, the format was not supported
314       throw new FileFormatException(getSupportedFormats());
315     }
316   }
317
318   /**
319    * boilerplate method to handle data from an AlignFile and construct a new
320    * alignment or import to an existing alignment
321    * 
322    * @return AlignmentI instance ready to pass to a UI constructor
323    */
324   private AlignmentI buildAlignmentFromFile()
325   {
326     // Standard boilerplate for creating alignment from parser
327     // alignFile.configureForView(viewpanel);
328
329     AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
330
331     alignFile.addAnnotations(al);
332
333     alignFile.addGroups(al);
334
335     return al;
336   }
337
338   /**
339    * create an alignment flatfile from a Jalview alignment view
340    * 
341    * @param format
342    * @param jvsuffix
343    * @param av
344    * @param selectedOnly
345    * @return flatfile in a string
346    */
347   public String formatSequences(FileFormatI format, boolean jvsuffix,
348           AlignmentViewPanel ap, boolean selectedOnly)
349   {
350
351     AlignmentView selvew = ap.getAlignViewport()
352             .getAlignmentView(selectedOnly, false);
353     AlignmentI aselview = selvew
354             .getVisibleAlignment(ap.getAlignViewport().getGapCharacter());
355     List<AlignmentAnnotation> ala = (ap.getAlignViewport()
356             .getVisibleAlignmentAnnotation(selectedOnly));
357     if (ala != null)
358     {
359       for (AlignmentAnnotation aa : ala)
360       {
361         aselview.addAnnotation(aa);
362       }
363     }
364     viewpanel = ap;
365     return formatSequences(format, aselview, jvsuffix);
366   }
367
368   /**
369    * Construct an output class for an alignment in a particular filetype TODO:
370    * allow caller to detect errors and warnings encountered when generating
371    * output
372    *
373    * @param format
374    *          string name of alignment format
375    * @param alignment
376    *          the alignment to be written out
377    * @param jvsuffix
378    *          passed to AlnFile class controls whether /START-END is added to
379    *          sequence names
380    *
381    * @return alignment flat file contents
382    */
383   public String formatSequences(FileFormatI format, AlignmentI alignment,
384           boolean jvsuffix)
385   {
386     try
387     {
388       AlignmentFileWriterI afile = format.getWriter(alignment);
389
390       afile.setNewlineString(newline);
391       afile.setExportSettings(exportSettings);
392       afile.configureForView(viewpanel);
393
394       // check whether we were given a specific alignment to export, rather than
395       // the one in the viewpanel
396       SequenceI[] seqs = null;
397       if (viewpanel == null || viewpanel.getAlignment() == null
398               || viewpanel.getAlignment() != alignment)
399       {
400         seqs = alignment.getSequencesArray();
401       }
402       else
403       {
404         seqs = viewpanel.getAlignment().getSequencesArray();
405       }
406
407       String afileresp = afile.print(seqs, jvsuffix);
408       if (afile.hasWarningMessage())
409       {
410         System.err.println("Warning raised when writing as " + format
411                 + " : " + afile.getWarningMessage());
412       }
413       return afileresp;
414     } catch (Exception e)
415     {
416       System.err.println("Failed to write alignment as a '"
417               + format.getName() + "' file\n");
418       e.printStackTrace();
419     }
420
421     return null;
422   }
423
424   /**
425    * Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
426    * data
427    *
428    * @param data
429    * @return the protocol for the input data
430    */
431   public static DataSourceType checkProtocol(String data)
432   {
433     DataSourceType protocol = DataSourceType.PASTE;
434     String ft = data.toLowerCase().trim();
435     if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
436             || ft.indexOf("file:") == 0)
437     {
438       protocol = DataSourceType.URL;
439     }
440     else if (jalview.bin.Jalview.isJS)
441     {
442       protocol = DataSourceType.RELATIVE_URL;
443     }
444     else if (new File(data).exists())
445     {
446       protocol = DataSourceType.FILE;
447     }
448     return protocol;
449   }
450
451   public static void main(String[] args)
452   {
453     int i = 0;
454     while (i < args.length)
455     {
456       File f = new File(args[i]);
457       if (f.exists())
458       {
459         try
460         {
461           System.out.println("Reading file: " + f);
462           AppletFormatAdapter afa = new AppletFormatAdapter();
463           Runtime r = Runtime.getRuntime();
464           System.gc();
465           long memf = -r.totalMemory() + r.freeMemory();
466           long t1 = -System.currentTimeMillis();
467           AlignmentI al = afa.readFile(args[i], DataSourceType.FILE,
468                   new IdentifyFile().identify(args[i],
469                           DataSourceType.FILE));
470           t1 += System.currentTimeMillis();
471           System.gc();
472           memf += r.totalMemory() - r.freeMemory();
473           if (al != null)
474           {
475             System.out.println("Alignment contains " + al.getHeight()
476                     + " sequences and " + al.getWidth() + " columns.");
477             try
478             {
479               System.out.println(new AppletFormatAdapter()
480                       .formatSequences(FileFormat.Fasta, al, true));
481             } catch (Exception e)
482             {
483               System.err.println(
484                       "Couln't format the alignment for output as a FASTA file.");
485               e.printStackTrace(System.err);
486             }
487           }
488           else
489           {
490             System.out.println("Couldn't read alignment");
491           }
492           System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
493           System.out.println(
494                   "Difference between free memory now and before is "
495                           + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
496         } catch (Exception e)
497         {
498           System.err.println("Exception when dealing with " + i
499                   + "'th argument: " + args[i] + "\n" + e);
500         }
501       }
502       else
503       {
504         System.err.println("Ignoring argument '" + args[i] + "' (" + i
505                 + "'th)- not a readable file.");
506       }
507       i++;
508     }
509   }
510
511   /**
512    * try to discover how to access the given file as a valid datasource that
513    * will be identified as the given type.
514    *
515    * @param file
516    * @param format
517    * @return protocol that yields the data parsable as the given type
518    */
519   public static DataSourceType resolveProtocol(String file,
520           FileFormatI format)
521   {
522     return resolveProtocol(file, format, false);
523   }
524
525   public static DataSourceType resolveProtocol(String file,
526           FileFormatI format, boolean debug)
527   {
528     // TODO: test thoroughly!
529     DataSourceType protocol = null;
530     if (debug)
531     {
532       System.out.println("resolving datasource started with:\n>>file\n"
533               + file + ">>endfile");
534     }
535
536     // This might throw a security exception in certain browsers
537     // Netscape Communicator for instance.
538     try
539     {
540       boolean rtn = false;
541       InputStream is = System.getSecurityManager().getClass()
542               .getResourceAsStream("/" + file);
543       if (is != null)
544       {
545         rtn = true;
546         is.close();
547       }
548       if (debug)
549       {
550         System.err.println("Resource '" + file + "' was "
551                 + (rtn ? "" : "not") + " located by classloader.");
552       }
553       if (rtn)
554       {
555         protocol = DataSourceType.CLASSLOADER;
556       }
557
558     } catch (Exception ex)
559     {
560       System.err
561               .println("Exception checking resources: " + file + " " + ex);
562     }
563
564     if (file.indexOf("://") > -1)
565     {
566       protocol = DataSourceType.URL;
567     }
568     else
569     {
570       // skipping codebase prepend check.
571       protocol = DataSourceType.FILE;
572     }
573     FileParse fp = null;
574     try
575     {
576       if (debug)
577       {
578         System.out.println(
579                 "Trying to get contents of resource as " + protocol + ":");
580       }
581       fp = new FileParse(file, protocol);
582       if (!fp.isValid())
583       {
584         fp = null;
585       }
586       else
587       {
588         if (debug)
589         {
590           System.out.println("Successful.");
591         }
592       }
593     } catch (Exception e)
594     {
595       if (debug)
596       {
597         System.err.println("Exception when accessing content: " + e);
598       }
599       fp = null;
600     }
601     if (fp == null)
602     {
603       if (debug)
604       {
605         System.out.println("Accessing as paste.");
606       }
607       protocol = DataSourceType.PASTE;
608       fp = null;
609       try
610       {
611         fp = new FileParse(file, protocol);
612         if (!fp.isValid())
613         {
614           fp = null;
615         }
616       } catch (Exception e)
617       {
618         System.err.println("Failed to access content as paste!");
619         e.printStackTrace();
620         fp = null;
621       }
622     }
623     if (fp == null)
624     {
625       return null;
626     }
627     if (format == null)
628     {
629       return protocol;
630     }
631     else
632     {
633       try
634       {
635         FileFormatI idformat = new IdentifyFile().identify(file, protocol);
636         if (idformat == null)
637         {
638           if (debug)
639           {
640             System.out.println("Format not identified. Inaccessible file.");
641           }
642           return null;
643         }
644         if (debug)
645         {
646           System.out.println("Format identified as " + idformat
647                   + "and expected as " + format);
648         }
649         if (idformat.equals(format))
650         {
651           if (debug)
652           {
653             System.out.println("Protocol identified as " + protocol);
654           }
655           return protocol;
656         }
657         else
658         {
659           if (debug)
660           {
661             System.out
662                     .println("File deemed not accessible via " + protocol);
663           }
664           fp.close();
665           return null;
666         }
667       } catch (Exception e)
668       {
669         if (debug)
670         {
671           System.err.println("File deemed not accessible via " + protocol);
672           e.printStackTrace();
673         }
674       }
675     }
676     return null;
677   }
678
679   public AlignmentFileReaderI getAlignFile()
680   {
681     return alignFile;
682   }
683 }