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