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