690e22ace03ea44a5e5feb45ad67c0f3d7acf09c
[jalview.git] / src / jalview / io / FileParse.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.AlignViewportI;
25 import jalview.util.MessageManager;
26
27 import java.io.BufferedReader;
28 import java.io.File;
29 import java.io.FileInputStream;
30 import java.io.FileReader;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.InputStreamReader;
34 import java.io.Reader;
35 import java.io.StringReader;
36 import java.net.MalformedURLException;
37 import java.net.URL;
38 import java.util.zip.GZIPInputStream;
39
40 /**
41  * implements a random access wrapper around a particular datasource, for
42  * passing to identifyFile and AlignFile objects.
43  */
44 public class FileParse
45 {
46   /**
47    * text specifying source of data. usually filename or url.
48    */
49   private String dataName = "unknown source";
50
51   public File inFile = null;
52
53   private AlignViewportI viewport;
54
55   public int index = 1; // sequence counter for FileParse object created from
56   /**
57    * specific settings for exporting data from the current context
58    */
59   private AlignExportSettingI exportSettings;
60
61   // same data source
62
63   protected char suffixSeparator = '#';
64
65   /**
66    * character used to write newlines
67    */
68   protected String newline = System.getProperty("line.separator");
69
70   public void setNewlineString(String nl)
71   {
72       newline = nl;
73   }
74
75   public String getNewlineString()
76   {
77     return newline;
78   }
79
80   /**
81    * '#' separated string tagged on to end of filename or url that was clipped
82    * off to resolve to valid filename
83    */
84   protected String suffix = null;
85
86   protected String type = null;
87
88   protected BufferedReader dataIn = null;
89
90   protected String errormessage = "UNITIALISED SOURCE";
91
92   protected boolean error = true;
93
94   protected String warningMessage = null;
95
96   /**
97    * size of readahead buffer used for when initial stream position is marked.
98    */
99   final int READAHEAD_LIMIT = 2048;
100
101   public FileParse()
102   {
103   }
104
105   /**
106    * Create a new FileParse instance reading from the same datasource starting
107    * at the current position. WARNING! Subsequent reads from either object will
108    * affect the read position of the other, but not the error state.
109    * 
110    * @param from
111    */
112   public FileParse(FileParse from) throws IOException
113   {
114     if (from == null)
115     {
116       throw new Error(MessageManager.getString("error.implementation_error_null_fileparse"));
117     }
118     if (from == this)
119     {
120       return;
121     }
122     index = ++from.index;
123     inFile = from.inFile;
124     suffixSeparator = from.suffixSeparator;
125     suffix = from.suffix;
126     errormessage = from.errormessage; // inherit potential error messages
127     error = false; // reset any error condition.
128     type = from.type;
129     dataIn = from.dataIn;
130     if (dataIn != null)
131     {
132       mark();
133     }
134     dataName = from.dataName;
135   }
136
137   /**
138    * Attempt to open a file as a datasource. Sets error and errormessage if
139    * fileStr was invalid.
140    * 
141    * @param fileStr
142    * @return this.error (true if the source was invalid)
143    */
144   private boolean checkFileSource(String fileStr) throws IOException
145   {
146     error = false;
147     this.inFile = new File(fileStr);
148     // check to see if it's a Jar file in disguise.
149     if (!inFile.exists())
150     {
151       errormessage = "FILE NOT FOUND";
152       error = true;
153     }
154     if (!inFile.canRead())
155     {
156       errormessage = "FILE CANNOT BE OPENED FOR READING";
157       error = true;
158     }
159     if (inFile.isDirectory())
160     {
161       // this is really a 'complex' filetype - but we don't handle directory
162       // reads yet.
163       errormessage = "FILE IS A DIRECTORY";
164       error = true;
165     }
166     if (!error)
167     {
168       if (fileStr.toLowerCase().endsWith(".gz"))
169       {
170         try
171         {
172           dataIn = tryAsGzipSource(new FileInputStream(fileStr));
173           dataName = fileStr;
174           return error;
175         } catch (Exception x)
176         {
177           warningMessage = "Failed  to resolve as a GZ stream ("
178                   + x.getMessage() + ")";
179           // x.printStackTrace();
180         }
181         ;
182       }
183
184       dataIn = new BufferedReader(new FileReader(fileStr));
185       dataName = fileStr;
186     }
187     return error;
188   }
189
190   private BufferedReader tryAsGzipSource(InputStream inputStream)
191           throws Exception
192   {
193     BufferedReader inData = new BufferedReader(new InputStreamReader(
194             new GZIPInputStream(inputStream)));
195     inData.mark(2048);
196     inData.read();
197     inData.reset();
198     return inData;
199   }
200
201   private boolean checkURLSource(String fileStr) throws IOException,
202           MalformedURLException
203   {
204     errormessage = "URL NOT FOUND";
205     URL url = new URL(fileStr);
206     //
207     // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
208     // Kenny Sabir
209     Exception e = null;
210     if (fileStr.toLowerCase().endsWith(".gz"))
211     {
212       try
213       {
214         InputStream inputStream = url.openStream();
215         dataIn = tryAsGzipSource(inputStream);
216         dataName = fileStr;
217         return false;
218       } catch (Exception ex)
219       {
220         e = ex;
221       }
222     }
223
224     try
225     {
226       dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
227     } catch (IOException q)
228     {
229       if (e != null)
230       {
231         throw new IOException(MessageManager.getString("exception.failed_to_resolve_gzip_stream"), e);
232       }
233       throw q;
234     }
235     // record URL as name of datasource.
236     dataName = fileStr;
237     return false;
238   }
239
240   /**
241    * sets the suffix string (if any) and returns remainder (if suffix was
242    * detected)
243    * 
244    * @param fileStr
245    * @return truncated fileStr or null
246    */
247   private String extractSuffix(String fileStr)
248   {
249     // first check that there wasn't a suffix string tagged on.
250     int sfpos = fileStr.lastIndexOf(suffixSeparator);
251     if (sfpos > -1 && sfpos < fileStr.length() - 1)
252     {
253       suffix = fileStr.substring(sfpos + 1);
254       // System.err.println("DEBUG: Found Suffix:"+suffix);
255       return fileStr.substring(0, sfpos);
256     }
257     return null;
258   }
259
260   /**
261    * Create a datasource for input to Jalview. See AppletFormatAdapter for the
262    * types of sources that are handled.
263    * 
264    * @param fileStr
265    *          - datasource locator/content
266    * @param type
267    *          - protocol of source
268    * @throws MalformedURLException
269    * @throws IOException
270    */
271   public FileParse(String fileStr, String type)
272           throws MalformedURLException, IOException
273   {
274     this.type = type;
275     error = false;
276
277     if (type.equals(AppletFormatAdapter.FILE))
278     {
279       if (checkFileSource(fileStr))
280       {
281         String suffixLess = extractSuffix(fileStr);
282         if (suffixLess != null)
283         {
284           if (checkFileSource(suffixLess))
285           {
286             throw new IOException(MessageManager.formatMessage("exception.problem_opening_file_also_tried", new String[]{inFile.getName(),suffixLess,errormessage}));
287           }
288         }
289         else
290         {
291           throw new IOException(MessageManager.formatMessage("exception.problem_opening_file", new String[]{inFile.getName(),errormessage}));
292         }
293       }
294     }
295     else if (type.equals(AppletFormatAdapter.URL))
296     {
297       try
298       {
299         try
300         {
301           checkURLSource(fileStr);
302           if (suffixSeparator == '#')
303            {
304             extractSuffix(fileStr); // URL lref is stored for later reference.
305           }
306         } catch (IOException e)
307         {
308           String suffixLess = extractSuffix(fileStr);
309           if (suffixLess == null)
310           {
311             throw (e);
312           }
313           else
314           {
315             try
316             {
317               checkURLSource(suffixLess);
318             } catch (IOException e2)
319             {
320               errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
321               throw (e); // just pass back original - everything was wrong.
322             }
323           }
324         }
325       } catch (Exception e)
326       {
327         errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
328                 + e.getMessage() + ")";
329         error = true;
330       }
331     }
332     else if (type.equals(AppletFormatAdapter.PASTE))
333     {
334       errormessage = "PASTE INACCESSIBLE!";
335       dataIn = new BufferedReader(new StringReader(fileStr));
336       dataName = "Paste";
337     }
338     else if (type.equals(AppletFormatAdapter.CLASSLOADER))
339     {
340       errormessage = "RESOURCE CANNOT BE LOCATED";
341       java.io.InputStream is = getClass()
342               .getResourceAsStream("/" + fileStr);
343       if (is == null)
344       {
345         String suffixLess = extractSuffix(fileStr);
346         if (suffixLess != null)
347         {
348           is = getClass().getResourceAsStream("/" + suffixLess);
349         }
350       }
351       if (is != null)
352       {
353         dataIn = new BufferedReader(new java.io.InputStreamReader(is));
354         dataName = fileStr;
355       }
356       else
357       {
358         error = true;
359       }
360     }
361     else
362     {
363       errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
364               + (type != null ? type : "null") + "'";
365       error = true;
366     }
367     if (dataIn == null || error)
368     {
369       // pass up the reason why we have no source to read from
370       throw new IOException(MessageManager.formatMessage("exception.failed_to_read_data_from_source", new String[]{errormessage}));
371     }
372     error = false;
373     dataIn.mark(READAHEAD_LIMIT);
374   }
375
376   /**
377    * mark the current position in the source as start for the purposes of it
378    * being analysed by IdentifyFile().identify
379    * 
380    * @throws IOException
381    */
382   public void mark() throws IOException
383   {
384     if (dataIn != null)
385     {
386       dataIn.mark(READAHEAD_LIMIT);
387     }
388     else
389     {
390       throw new IOException(MessageManager.getString("exception.no_init_source_stream"));
391     }
392   }
393
394   public String nextLine() throws IOException
395   {
396     if (!error)
397     {
398       return dataIn.readLine();
399     }
400     throw new IOException(MessageManager.formatMessage("exception.invalid_source_stream", new String[]{errormessage}));
401   }
402
403   public boolean isValid()
404   {
405     return !error;
406   }
407
408   /**
409    * closes the datasource and tidies up. source will be left in an error state
410    */
411   public void close() throws IOException
412   {
413     errormessage = "EXCEPTION ON CLOSE";
414     error = true;
415     dataIn.close();
416     dataIn = null;
417     errormessage = "SOURCE IS CLOSED";
418   }
419
420   /**
421    * rewinds the datasource the beginning.
422    * 
423    */
424   public void reset() throws IOException
425   {
426     if (dataIn != null && !error)
427     {
428       dataIn.reset();
429     }
430     else
431     {
432       throw new IOException(MessageManager.getString("error.implementation_error_reset_called_for_invalid_source"));
433     }
434   }
435
436   /**
437    * 
438    * @return true if there is a warning for the user
439    */
440   public boolean hasWarningMessage()
441   {
442     return (warningMessage != null && warningMessage.length() > 0);
443   }
444
445   /**
446    * 
447    * @return empty string or warning message about file that was just parsed.
448    */
449   public String getWarningMessage()
450   {
451     return warningMessage;
452   }
453
454   public String getInFile()
455   {
456     if (inFile != null)
457     {
458       return inFile.getAbsolutePath() + " (" + index + ")";
459     }
460     else
461     {
462       return "From Paste + (" + index + ")";
463     }
464   }
465
466   /**
467    * @return the dataName
468    */
469   public String getDataName()
470   {
471     return dataName;
472   }
473
474   /**
475    * set the (human readable) name or URI for this datasource
476    * 
477    * @param dataname
478    */
479   protected void setDataName(String dataname)
480   {
481     dataName = dataname;
482   }
483
484   /**
485    * get the underlying bufferedReader for this data source.
486    * 
487    * @return null if no reader available
488    * @throws IOException
489    */
490   public Reader getReader()
491   {
492     if (dataIn != null) // Probably don't need to test for readiness &&
493                         // dataIn.ready())
494     {
495       return dataIn;
496     }
497     return null;
498   }
499
500   public AlignViewportI getViewport()
501   {
502     return viewport;
503   }
504
505   public void setViewport(AlignViewportI viewport)
506   {
507     this.viewport = viewport;
508   }
509
510   /**
511    * @return the currently configured exportSettings for writing data.
512    */
513   public AlignExportSettingI getExportSettings()
514   {
515     return exportSettings;
516   }
517
518   /**
519    * Set configuration for export of data.
520    * 
521    * @param exportSettings
522    *          the exportSettings to set
523    */
524   public void setExportSettings(AlignExportSettingI exportSettings)
525   {
526     this.exportSettings = exportSettings;
527   }
528 }