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