167314eee2dae90118035a57b15feb649e5729e0
[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.api.AlignmentViewPanel;
26 import jalview.api.FeatureSettingsModelI;
27 import jalview.util.MessageManager;
28
29 import java.io.BufferedReader;
30 import java.io.File;
31 import java.io.FileInputStream;
32 import java.io.FileReader;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.InputStreamReader;
36 import java.io.Reader;
37 import java.io.StringReader;
38 import java.net.HttpURLConnection;
39 import java.net.MalformedURLException;
40 import java.net.URL;
41 import java.util.zip.GZIPInputStream;
42
43
44 /**
45  * implements a random access wrapper around a particular datasource, for
46  * passing to identifyFile and AlignFile objects.
47  */
48 public class FileParse
49 {
50   protected static final String SPACE = " ";
51
52   protected static final String TAB = "\t";
53
54   /**
55    * text specifying source of data. usually filename or url.
56    */
57   private String dataName = "unknown source";
58
59   public File inFile = null;
60
61
62   /**
63    * a viewport associated with the current file operation. May be null. May
64    * move to different object.
65    */
66   private AlignViewportI viewport;
67
68   /**
69    * specific settings for exporting data from the current context
70    */
71   private AlignExportSettingI exportSettings;
72
73   /**
74    * sequence counter for FileParse object created from same data source
75    */
76   public int index = 1;
77
78   /**
79    * separator for extracting specific 'frame' of a datasource for formats that
80    * support multiple records (e.g. BLC, Stockholm, etc)
81    */
82   protected char suffixSeparator = '#';
83
84   /**
85    * character used to write newlines
86    */
87   protected String newline = System.getProperty("line.separator");
88
89   public void setNewlineString(String nl)
90   {
91     newline = nl;
92   }
93
94   public String getNewlineString()
95   {
96     return newline;
97   }
98
99   /**
100    * '#' separated string tagged on to end of filename or url that was clipped
101    * off to resolve to valid filename
102    */
103   protected String suffix = null;
104
105   protected DataSourceType dataSourceType = null;
106
107   protected BufferedReader dataIn = null;
108
109   protected String errormessage = "UNINITIALISED SOURCE";
110
111   protected boolean error = true;
112
113   protected String warningMessage = null;
114
115   /**
116    * size of readahead buffer used for when initial stream position is marked.
117    */
118   final int READAHEAD_LIMIT = 2048;
119
120   public FileParse()
121   {
122   }
123
124   /**
125    * Create a new FileParse instance reading from the same datasource starting
126    * at the current position. WARNING! Subsequent reads from either object will
127    * affect the read position of the other, but not the error state.
128    * 
129    * @param from
130    */
131   public FileParse(FileParse from) throws IOException
132   {
133     if (from == null)
134     {
135       throw new Error(MessageManager
136               .getString("error.implementation_error_null_fileparse"));
137     }
138     if (from == this)
139     {
140       return;
141     }
142     index = ++from.index;
143     inFile = from.inFile;
144     suffixSeparator = from.suffixSeparator;
145     suffix = from.suffix;
146     errormessage = from.errormessage; // inherit potential error messages
147     error = false; // reset any error condition.
148     dataSourceType = from.dataSourceType;
149     dataIn = from.dataIn;
150     if (dataIn != null)
151     {
152       mark();
153     }
154     dataName = from.dataName;
155   }
156
157   /**
158    * Attempt to open a file as a datasource. Sets error and errormessage if
159    * fileStr was invalid.
160    * 
161    * @param fileStr
162    * @return this.error (true if the source was invalid)
163    */
164   private boolean checkFileSource(String fileStr) throws IOException
165   {
166     error = false;
167     this.inFile = new File(fileStr);
168     // check to see if it's a Jar file in disguise.
169     if (!inFile.exists())
170     {
171       errormessage = "FILE NOT FOUND";
172       error = true;
173     }
174     if (!inFile.canRead())
175     {
176       errormessage = "FILE CANNOT BE OPENED FOR READING";
177       error = true;
178     }
179     if (inFile.isDirectory())
180     {
181       // this is really a 'complex' filetype - but we don't handle directory
182       // reads yet.
183       errormessage = "FILE IS A DIRECTORY";
184       error = true;
185     }
186     if (!error)
187     {
188       if (fileStr.toLowerCase().endsWith(".gz"))
189       {
190         try
191         {
192           dataIn = getGzipReader(new FileInputStream(fileStr));
193           dataName = fileStr;
194           return error;
195         } catch (Exception x)
196         {
197           warningMessage = "Failed  to resolve as a GZ stream ("
198                   + x.getMessage() + ")";
199           // x.printStackTrace();
200         }
201         ;
202       }
203
204       dataIn = new BufferedReader(new FileReader(fileStr));
205       dataName = fileStr;
206     }
207     return error;
208   }
209
210   /**
211    * Returns a {@code BufferedReader} which wraps the input stream with a
212    * GZIPInputStream. Throws a {@code ZipException} if a GZIP format error
213    * occurs or the compression method used is unsupported.
214    * 
215    * @param inputStream
216    * @return
217    * @throws Exception
218    */
219   private BufferedReader getGzipReader(InputStream inputStream)
220           throws Exception
221   {
222     BufferedReader inData = new BufferedReader(
223             new InputStreamReader(new GZIPInputStream(inputStream)));
224     inData.mark(2048);
225     inData.read();
226     inData.reset();
227     return inData;
228   }
229
230   /**
231    * Tries to read from the given URL. If successful, saves a reader to the
232    * response in field {@code dataIn}, otherwise (on exception, or HTTP response
233    * status not 200), throws an exception.
234    * <p>
235    * If the response status includes
236    * 
237    * <pre>
238    * Content-Type : application/x-gzip
239    * </pre>
240    * 
241    * then tries to read as gzipped content.
242    * 
243    * @param urlStr
244    * @throws IOException
245    * @throws MalformedURLException
246    */
247   private void checkURLSource(String urlStr)
248           throws IOException, MalformedURLException
249   {
250     errormessage = "URL NOT FOUND";
251     URL url = new URL(urlStr);
252     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
253     int rc = conn.getResponseCode();
254     if (rc != HttpURLConnection.HTTP_OK)
255     {
256       throw new IOException(
257               "Response status from " + urlStr + " was " + rc);
258     }
259     String encoding = conn.getContentEncoding();
260     String contentType = conn.getContentType();
261     boolean isgzipped = "application/x-gzip".equalsIgnoreCase(contentType)
262             || "gzip".equals(encoding);
263     Exception e = null;
264     InputStream inputStream = conn.getInputStream();
265     if (isgzipped)
266     {
267       try
268       {
269         dataIn = getGzipReader(inputStream);
270         dataName = urlStr;
271       } catch (Exception e1)
272       {
273         throw new IOException(MessageManager
274                 .getString("exception.failed_to_resolve_gzip_stream"), e);
275       }
276       return;
277     }
278
279     dataIn = new BufferedReader(new InputStreamReader(inputStream));
280     dataName = urlStr;
281     return;
282   }
283
284   /**
285    * sets the suffix string (if any) and returns remainder (if suffix was
286    * detected)
287    * 
288    * @param fileStr
289    * @return truncated fileStr or null
290    */
291   private String extractSuffix(String fileStr)
292   {
293     // first check that there wasn't a suffix string tagged on.
294     int sfpos = fileStr.lastIndexOf(suffixSeparator);
295     if (sfpos > -1 && sfpos < fileStr.length() - 1)
296     {
297       suffix = fileStr.substring(sfpos + 1);
298       // System.err.println("DEBUG: Found Suffix:"+suffix);
299       return fileStr.substring(0, sfpos);
300     }
301     return null;
302   }
303
304   /**
305    * not for general use, creates a fileParse object for an existing reader with
306    * configurable values for the origin and the type of the source
307    */
308   public FileParse(BufferedReader source, String originString,
309           DataSourceType sourceType)
310   {
311     dataSourceType = sourceType;
312     error = false;
313     inFile = null;
314     dataName = originString;
315     dataIn = source;
316     try
317     {
318       if (dataIn.markSupported())
319       {
320         dataIn.mark(READAHEAD_LIMIT);
321       }
322     } catch (IOException q)
323     {
324
325     }
326   }
327
328   /**
329    * Create a datasource for input to Jalview. See AppletFormatAdapter for the
330    * types of sources that are handled.
331    * 
332    * @param fileStr
333    *          - datasource locator/content
334    * @param sourceType
335    *          - protocol of source
336    * @throws MalformedURLException
337    * @throws IOException
338    */
339   public FileParse(String fileStr, DataSourceType sourceType)
340           throws MalformedURLException, IOException
341   {
342     this.dataSourceType = sourceType;
343     error = false;
344
345     if (sourceType == DataSourceType.FILE)
346     {
347       if (checkFileSource(fileStr))
348       {
349         String suffixLess = extractSuffix(fileStr);
350         if (suffixLess != null)
351         {
352           if (checkFileSource(suffixLess))
353           {
354             throw new IOException(MessageManager.formatMessage(
355                     "exception.problem_opening_file_also_tried",
356                     new String[]
357                     { inFile.getName(), suffixLess, errormessage }));
358           }
359         }
360         else
361         {
362           throw new IOException(MessageManager.formatMessage(
363                   "exception.problem_opening_file", new String[]
364                   { inFile.getName(), errormessage }));
365         }
366       }
367     }
368     else if (sourceType == DataSourceType.URL)
369     {
370       try
371       {
372         try
373         {
374           checkURLSource(fileStr);
375           if (suffixSeparator == '#')
376           {
377             extractSuffix(fileStr); // URL lref is stored for later reference.
378           }
379         } catch (IOException e)
380         {
381           String suffixLess = extractSuffix(fileStr);
382           if (suffixLess == null)
383           {
384             throw (e);
385           }
386           else
387           {
388             try
389             {
390               checkURLSource(suffixLess);
391             } catch (IOException e2)
392             {
393               errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
394               throw (e); // just pass back original - everything was wrong.
395             }
396           }
397         }
398       } catch (Exception e)
399       {
400         errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
401                 + e.getMessage() + ")";
402         error = true;
403       }
404     }
405     else if (sourceType == DataSourceType.PASTE)
406     {
407       errormessage = "PASTE INACCESSIBLE!";
408       dataIn = new BufferedReader(new StringReader(fileStr));
409       dataName = "Paste";
410     }
411     else if (sourceType == DataSourceType.CLASSLOADER)
412     {
413       errormessage = "RESOURCE CANNOT BE LOCATED";
414       java.io.InputStream is = getClass()
415               .getResourceAsStream("/" + fileStr);
416       if (is == null)
417       {
418         String suffixLess = extractSuffix(fileStr);
419         if (suffixLess != null)
420         {
421           is = getClass().getResourceAsStream("/" + suffixLess);
422         }
423       }
424       if (is != null)
425       {
426         dataIn = new BufferedReader(new java.io.InputStreamReader(is));
427         dataName = fileStr;
428       }
429       else
430       {
431         error = true;
432       }
433     }
434     else
435     {
436       errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
437               + (sourceType != null ? sourceType : "null") + "'";
438       error = true;
439     }
440     if (dataIn == null || error)
441     {
442       // pass up the reason why we have no source to read from
443       throw new IOException(MessageManager.formatMessage(
444               "exception.failed_to_read_data_from_source", new String[]
445               { errormessage }));
446     }
447     error = false;
448     dataIn.mark(READAHEAD_LIMIT);
449   }
450
451   /**
452    * mark the current position in the source as start for the purposes of it
453    * being analysed by IdentifyFile().identify
454    * 
455    * @throws IOException
456    */
457   public void mark() throws IOException
458   {
459     if (dataIn != null)
460     {
461       dataIn.mark(READAHEAD_LIMIT);
462     }
463     else
464     {
465       throw new IOException(
466               MessageManager.getString("exception.no_init_source_stream"));
467     }
468   }
469
470   public String nextLine() throws IOException
471   {
472     if (!error)
473     {
474       return dataIn.readLine();
475     }
476     throw new IOException(MessageManager
477             .formatMessage("exception.invalid_source_stream", new String[]
478             { errormessage }));
479   }
480
481   /**
482    * 
483    * @return true if this FileParse is configured for Export only
484    */
485   public boolean isExporting()
486   {
487     return !error && dataIn == null;
488   }
489
490   /**
491    * 
492    * @return true if the data source is valid
493    */
494   public boolean isValid()
495   {
496     return !error;
497   }
498
499   /**
500    * closes the datasource and tidies up. source will be left in an error state
501    */
502   public void close() throws IOException
503   {
504     errormessage = "EXCEPTION ON CLOSE";
505     error = true;
506     dataIn.close();
507     dataIn = null;
508     errormessage = "SOURCE IS CLOSED";
509   }
510
511   /**
512    * Rewinds the datasource to the marked point if possible
513    * 
514    * @param bytesRead
515    * 
516    */
517   public void reset(int bytesRead) throws IOException
518   {
519     if (bytesRead >= READAHEAD_LIMIT)
520     {
521       System.err.println(String.format(
522               "File reset error: read %d bytes but reset limit is %d",
523               bytesRead, READAHEAD_LIMIT));
524     }
525     if (dataIn != null && !error)
526     {
527       dataIn.reset();
528     }
529     else
530     {
531       throw new IOException(MessageManager.getString(
532               "error.implementation_error_reset_called_for_invalid_source"));
533     }
534   }
535
536   /**
537    * 
538    * @return true if there is a warning for the user
539    */
540   public boolean hasWarningMessage()
541   {
542     return (warningMessage != null && warningMessage.length() > 0);
543   }
544
545   /**
546    * 
547    * @return empty string or warning message about file that was just parsed.
548    */
549   public String getWarningMessage()
550   {
551     return warningMessage;
552   }
553
554   public String getInFile()
555   {
556     if (inFile != null)
557     {
558       return inFile.getAbsolutePath() + " (" + index + ")";
559     }
560     else
561     {
562       return "From Paste + (" + index + ")";
563     }
564   }
565
566   /**
567    * @return the dataName
568    */
569   public String getDataName()
570   {
571     return dataName;
572   }
573
574   /**
575    * set the (human readable) name or URI for this datasource
576    * 
577    * @param dataname
578    */
579   protected void setDataName(String dataname)
580   {
581     dataName = dataname;
582   }
583
584   /**
585    * get the underlying bufferedReader for this data source.
586    * 
587    * @return null if no reader available
588    * @throws IOException
589    */
590   public Reader getReader()
591   {
592     if (dataIn != null) // Probably don't need to test for readiness &&
593                         // dataIn.ready())
594     {
595       return dataIn;
596     }
597     return null;
598   }
599
600   public AlignViewportI getViewport()
601   {
602     return viewport;
603   }
604
605   public void setViewport(AlignViewportI viewport)
606   {
607     this.viewport = viewport;
608   }
609
610   /**
611    * @return the currently configured exportSettings for writing data.
612    */
613   public AlignExportSettingI getExportSettings()
614   {
615     return exportSettings;
616   }
617
618   /**
619    * Set configuration for export of data.
620    * 
621    * @param exportSettings
622    *          the exportSettings to set
623    */
624   public void setExportSettings(AlignExportSettingI exportSettings)
625   {
626     this.exportSettings = exportSettings;
627   }
628
629   /**
630    * method overridden by complex file exporter/importers which support
631    * exporting visualisation and layout settings for a view
632    * 
633    * @param avpanel
634    */
635   public void configureForView(AlignmentViewPanel avpanel)
636   {
637     if (avpanel != null)
638     {
639       setViewport(avpanel.getAlignViewport());
640     }
641     // could also set export/import settings
642   }
643
644   /**
645    * Returns the preferred feature colour configuration if there is one, else
646    * null
647    * 
648    * @return
649    */
650   public FeatureSettingsModelI getFeatureColourScheme()
651   {
652     return null;
653   }
654
655   public DataSourceType getDataSourceType()
656   {
657     return dataSourceType;
658   }
659 }