f1d79fe62375b4c2950b6e8e093cfc673e1bb515
[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     URLConnection _conn = url.openConnection();
289     if (_conn instanceof HttpURLConnection)
290     {
291       HttpURLConnection conn = (HttpURLConnection) _conn;
292       int rc = conn.getResponseCode();
293       if (rc != HttpURLConnection.HTTP_OK)
294       {
295         throw new IOException(
296                 "Response status from " + urlStr + " was " + rc);
297       }
298     } else {
299       try {
300       dataIn = checkForGzipStream(_conn.getInputStream());
301       dataName=urlStr;
302       } catch (IOException ex)
303       {
304         throw new IOException("Failed to handle non-HTTP URI stream",ex);
305       } catch (Exception ex)
306       {
307         throw new IOException("Failed to determine type of input stream for given URI",ex);
308       }
309       return;
310     }
311     String encoding = _conn.getContentEncoding();
312     String contentType = _conn.getContentType();
313     boolean isgzipped = "application/x-gzip".equalsIgnoreCase(contentType)
314             || "gzip".equals(encoding);
315     Exception e = null;
316     InputStream inputStream = _conn.getInputStream();
317     if (isgzipped)
318     {
319       try
320       {
321         dataIn = getGzipReader(inputStream);
322         dataName = urlStr;
323       } catch (Exception e1)
324       {
325         throw new IOException(MessageManager
326                 .getString("exception.failed_to_resolve_gzip_stream"), e);
327       }
328       return;
329     }
330
331     dataIn = new BufferedReader(new InputStreamReader(inputStream));
332     dataName = urlStr;
333     return;
334   }
335
336   /**
337    * sets the suffix string (if any) and returns remainder (if suffix was
338    * detected)
339    * 
340    * @param fileStr
341    * @return truncated fileStr or null
342    */
343   private String extractSuffix(String fileStr)
344   {
345     // first check that there wasn't a suffix string tagged on.
346     int sfpos = fileStr.lastIndexOf(suffixSeparator);
347     if (sfpos > -1 && sfpos < fileStr.length() - 1)
348     {
349       suffix = fileStr.substring(sfpos + 1);
350       // System.err.println("DEBUG: Found Suffix:"+suffix);
351       return fileStr.substring(0, sfpos);
352     }
353     return null;
354   }
355
356   /**
357    * not for general use, creates a fileParse object for an existing reader with
358    * configurable values for the origin and the type of the source
359    */
360   public FileParse(BufferedReader source, String originString,
361           DataSourceType sourceType)
362   {
363     dataSourceType = sourceType;
364     error = false;
365     inFile = null;
366     dataName = originString;
367     dataIn = source;
368     try
369     {
370       if (dataIn.markSupported())
371       {
372         dataIn.mark(READAHEAD_LIMIT);
373       }
374     } catch (IOException q)
375     {
376
377     }
378   }
379
380   /**
381    * Create a datasource for input to Jalview. See AppletFormatAdapter for the
382    * types of sources that are handled.
383    * 
384    * @param fileStr
385    *          - datasource locator/content
386    * @param sourceType
387    *          - protocol of source
388    * @throws MalformedURLException
389    * @throws IOException
390    */
391   public FileParse(String fileStr, DataSourceType sourceType)
392           throws MalformedURLException, IOException
393   {
394     this.dataSourceType = sourceType;
395     error = false;
396
397     if (sourceType == DataSourceType.FILE)
398     {
399       if (checkFileSource(fileStr))
400       {
401         String suffixLess = extractSuffix(fileStr);
402         if (suffixLess != null)
403         {
404           if (checkFileSource(suffixLess))
405           {
406             throw new IOException(MessageManager.formatMessage(
407                     "exception.problem_opening_file_also_tried",
408                     new String[]
409                     { inFile.getName(), suffixLess, errormessage }));
410           }
411         }
412         else
413         {
414           throw new IOException(MessageManager.formatMessage(
415                   "exception.problem_opening_file", new String[]
416                   { inFile.getName(), errormessage }));
417         }
418       }
419     }
420     else if (sourceType == DataSourceType.URL)
421     {
422       try
423       {
424         try
425         {
426           checkURLSource(fileStr);
427           if (suffixSeparator == '#')
428           {
429             extractSuffix(fileStr); // URL lref is stored for later reference.
430           }
431         } catch (IOException e)
432         {
433           String suffixLess = extractSuffix(fileStr);
434           if (suffixLess == null)
435           {
436             throw (e);
437           }
438           else
439           {
440             try
441             {
442               checkURLSource(suffixLess);
443             } catch (IOException e2)
444             {
445               errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
446               throw (e); // just pass back original - everything was wrong.
447             }
448           }
449         }
450       } catch (Exception e)
451       {
452         errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
453                 + e.getMessage() + ")";
454         error = true;
455       }
456     }
457     else if (sourceType == DataSourceType.PASTE)
458     {
459       errormessage = "PASTE INACCESSIBLE!";
460       dataIn = new BufferedReader(new StringReader(fileStr));
461       dataName = "Paste";
462     }
463     else if (sourceType == DataSourceType.CLASSLOADER)
464     {
465       errormessage = "RESOURCE CANNOT BE LOCATED";
466       java.io.InputStream is = getClass()
467               .getResourceAsStream("/" + fileStr);
468       if (is == null)
469       {
470         String suffixLess = extractSuffix(fileStr);
471         if (suffixLess != null)
472         {
473           is = getClass().getResourceAsStream("/" + suffixLess);
474         }
475       }
476       if (is != null)
477       {
478         dataIn = new BufferedReader(new java.io.InputStreamReader(is));
479         dataName = fileStr;
480       }
481       else
482       {
483         error = true;
484       }
485     }
486     else
487     {
488       errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
489               + (sourceType != null ? sourceType : "null") + "'";
490       error = true;
491     }
492     if (dataIn == null || error)
493     {
494       // pass up the reason why we have no source to read from
495       throw new IOException(MessageManager.formatMessage(
496               "exception.failed_to_read_data_from_source", new String[]
497               { errormessage }));
498     }
499     error = false;
500     dataIn.mark(READAHEAD_LIMIT);
501   }
502
503   /**
504    * mark the current position in the source as start for the purposes of it
505    * being analysed by IdentifyFile().identify
506    * 
507    * @throws IOException
508    */
509   public void mark() throws IOException
510   {
511     if (dataIn != null)
512     {
513       dataIn.mark(READAHEAD_LIMIT);
514     }
515     else
516     {
517       throw new IOException(
518               MessageManager.getString("exception.no_init_source_stream"));
519     }
520   }
521
522   public String nextLine() throws IOException
523   {
524     if (!error)
525     {
526       return dataIn.readLine();
527     }
528     throw new IOException(MessageManager
529             .formatMessage("exception.invalid_source_stream", new String[]
530             { errormessage }));
531   }
532
533   /**
534    * 
535    * @return true if this FileParse is configured for Export only
536    */
537   public boolean isExporting()
538   {
539     return !error && dataIn == null;
540   }
541
542   /**
543    * 
544    * @return true if the data source is valid
545    */
546   public boolean isValid()
547   {
548     return !error;
549   }
550
551   /**
552    * closes the datasource and tidies up. source will be left in an error state
553    */
554   public void close() throws IOException
555   {
556     errormessage = "EXCEPTION ON CLOSE";
557     error = true;
558     dataIn.close();
559     dataIn = null;
560     errormessage = "SOURCE IS CLOSED";
561   }
562
563   /**
564    * Rewinds the datasource to the marked point if possible
565    * 
566    * @param bytesRead
567    * 
568    */
569   public void reset(int bytesRead) throws IOException
570   {
571     if (bytesRead >= READAHEAD_LIMIT)
572     {
573       System.err.println(String.format(
574               "File reset error: read %d bytes but reset limit is %d",
575               bytesRead, READAHEAD_LIMIT));
576     }
577     if (dataIn != null && !error)
578     {
579       dataIn.reset();
580     }
581     else
582     {
583       throw new IOException(MessageManager.getString(
584               "error.implementation_error_reset_called_for_invalid_source"));
585     }
586   }
587
588   /**
589    * 
590    * @return true if there is a warning for the user
591    */
592   public boolean hasWarningMessage()
593   {
594     return (warningMessage != null && warningMessage.length() > 0);
595   }
596
597   /**
598    * 
599    * @return empty string or warning message about file that was just parsed.
600    */
601   public String getWarningMessage()
602   {
603     return warningMessage;
604   }
605
606   public String getInFile()
607   {
608     if (inFile != null)
609     {
610       return inFile.getAbsolutePath() + " (" + index + ")";
611     }
612     else
613     {
614       return "From Paste + (" + index + ")";
615     }
616   }
617
618   /**
619    * @return the dataName
620    */
621   public String getDataName()
622   {
623     return dataName;
624   }
625
626   /**
627    * set the (human readable) name or URI for this datasource
628    * 
629    * @param dataname
630    */
631   protected void setDataName(String dataname)
632   {
633     dataName = dataname;
634   }
635
636   /**
637    * get the underlying bufferedReader for this data source.
638    * 
639    * @return null if no reader available
640    * @throws IOException
641    */
642   public Reader getReader()
643   {
644     if (dataIn != null) // Probably don't need to test for readiness &&
645                         // dataIn.ready())
646     {
647       return dataIn;
648     }
649     return null;
650   }
651
652   public AlignViewportI getViewport()
653   {
654     return viewport;
655   }
656
657   public void setViewport(AlignViewportI viewport)
658   {
659     this.viewport = viewport;
660   }
661
662   /**
663    * @return the currently configured exportSettings for writing data.
664    */
665   public AlignExportSettingI getExportSettings()
666   {
667     return exportSettings;
668   }
669
670   /**
671    * Set configuration for export of data.
672    * 
673    * @param exportSettings
674    *          the exportSettings to set
675    */
676   public void setExportSettings(AlignExportSettingI exportSettings)
677   {
678     this.exportSettings = exportSettings;
679   }
680
681   /**
682    * method overridden by complex file exporter/importers which support
683    * exporting visualisation and layout settings for a view
684    * 
685    * @param avpanel
686    */
687   public void configureForView(AlignmentViewPanel avpanel)
688   {
689     if (avpanel != null)
690     {
691       setViewport(avpanel.getAlignViewport());
692     }
693     // could also set export/import settings
694   }
695
696   /**
697    * Returns the preferred feature colour configuration if there is one, else
698    * null
699    * 
700    * @return
701    */
702   public FeatureSettingsModelI getFeatureColourScheme()
703   {
704     return null;
705   }
706
707   public DataSourceType getDataSourceType()
708   {
709     return dataSourceType;
710   }
711 }