2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import java.io.BufferedInputStream;
24 import java.io.BufferedReader;
25 import java.io.ByteArrayInputStream;
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.HttpURLConnection;
35 import java.net.MalformedURLException;
37 import java.net.URLConnection;
38 import java.util.zip.GZIPInputStream;
40 import jalview.api.AlignExportSettingsI;
41 import jalview.api.AlignViewportI;
42 import jalview.api.AlignmentViewPanel;
43 import jalview.api.FeatureSettingsModelI;
44 import jalview.bin.Cache;
45 import jalview.util.MessageManager;
46 import jalview.util.Platform;
49 * implements a random access wrapper around a particular datasource, for
50 * passing to identifyFile and AlignFile objects.
52 public class FileParse
54 protected static final String SPACE = " ";
56 protected static final String TAB = "\t";
59 * text specifying source of data. usually filename or url.
61 private String dataName = "unknown source";
63 public File inFile = null;
65 private byte[] bytes; // from JavaScript
67 public byte[] getBytes()
73 * a viewport associated with the current file operation. May be null. May
74 * move to different object.
76 private AlignViewportI viewport;
79 * specific settings for exporting data from the current context
81 private AlignExportSettingsI exportSettings;
84 * sequence counter for FileParse object created from same data source
89 * separator for extracting specific 'frame' of a datasource for formats that
90 * support multiple records (e.g. BLC, Stockholm, etc)
92 protected char suffixSeparator = '#';
95 * character used to write newlines
97 protected String newline = System.getProperty("line.separator");
99 public void setNewlineString(String nl)
104 public String getNewlineString()
110 * '#' separated string tagged on to end of filename or url that was clipped
111 * off to resolve to valid filename
113 protected String suffix = null;
115 protected DataSourceType dataSourceType = null;
117 protected BufferedReader dataIn = null;
119 protected String errormessage = "UNINITIALISED SOURCE";
121 protected boolean error = true;
123 protected String warningMessage = null;
126 * size of readahead buffer used for when initial stream position is marked.
128 final int READAHEAD_LIMIT = 2048;
135 * Create a new FileParse instance reading from the same datasource starting
136 * at the current position. WARNING! Subsequent reads from either object will
137 * affect the read position of the other, but not the error state.
141 public FileParse(FileParse from) throws IOException
145 throw new Error(MessageManager
146 .getString("error.implementation_error_null_fileparse"));
152 index = ++from.index;
153 inFile = from.inFile;
154 suffixSeparator = from.suffixSeparator;
155 suffix = from.suffix;
156 errormessage = from.errormessage; // inherit potential error messages
157 error = false; // reset any error condition.
158 dataSourceType = from.dataSourceType;
159 dataIn = from.dataIn;
164 dataName = from.dataName;
168 * Attempt to open a file as a datasource. Sets error and errormessage if
169 * fileStr was invalid.
172 * @return this.error (true if the source was invalid)
174 private boolean checkFileSource(String fileStr) throws IOException
177 this.inFile = new File(fileStr);
178 // check to see if it's a Jar file in disguise.
179 if (!inFile.exists())
181 errormessage = "FILE NOT FOUND";
184 if (!inFile.canRead())
186 errormessage = "FILE CANNOT BE OPENED FOR READING";
189 if (inFile.isDirectory())
191 // this is really a 'complex' filetype - but we don't handle directory
193 errormessage = "FILE IS A DIRECTORY";
200 dataIn = checkForGzipStream(new FileInputStream(fileStr));
202 } catch (Exception x)
204 warningMessage = "Failed to resolve " + fileStr
205 + " as a data source. (" + x.getMessage() + ")";
206 // x.printStackTrace();
215 * Recognise the 2-byte magic header for gzip streams
217 * https://recalll.co/ask/v/topic/java-How-to-check-if-InputStream-is-Gzipped/555aadd62bd27354438b90f6
220 * - at least two bytes
222 * @throws IOException
224 public static boolean isGzipStream(InputStream input) throws IOException
226 if (!input.markSupported())
229 "FileParse.izGzipStream: input stream must support mark/reset");
233 byte[] bytes = new byte[2]; // input.readNBytes(2);
234 int read = input.read(bytes);
236 if (read != bytes.length)
240 if (bytes.length == 2)
242 int header = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
243 return (GZIPInputStream.GZIP_MAGIC == header);
249 * Returns a Reader for the given input after wrapping it in a buffered input
250 * stream, and then checking if it needs to be wrapped by a GZipInputStream
255 private BufferedReader checkForGzipStream(InputStream input)
259 // https://stackoverflow.com/questions/4818468/how-to-check-if-inputstream-is-gzipped
260 // could use a PushBackInputStream rather than a BufferedInputStream
261 if (!input.markSupported())
263 input = new BufferedInputStream(input, 16);
265 if (isGzipStream(input))
267 return getGzipReader(input);
269 // return a buffered reader for the stream.
270 InputStreamReader isReader = new InputStreamReader(input);
271 BufferedReader toReadFrom = new BufferedReader(isReader);
276 * Returns a {@code BufferedReader} which wraps the input stream with a
277 * GZIPInputStream. Throws a {@code ZipException} if a GZIP format error
278 * occurs or the compression method used is unsupported.
284 private BufferedReader getGzipReader(InputStream inputStream)
287 BufferedReader inData = new BufferedReader(
288 new InputStreamReader(new GZIPInputStream(inputStream)));
296 * Tries to read from the given URL. If successful, saves a reader to the
297 * response in field {@code dataIn}, otherwise (on exception, or HTTP response
298 * status not 200), throws an exception.
300 * If the response status includes
303 * Content-Type : application/x-gzip
306 * then tries to read as gzipped content.
309 * @throws IOException
310 * @throws MalformedURLException
312 private void checkURLSource(String urlStr)
313 throws IOException, MalformedURLException
315 errormessage = "URL NOT FOUND";
316 URL url = new URL(urlStr);
317 URLConnection _conn = url.openConnection();
318 if (_conn instanceof HttpURLConnection)
320 HttpURLConnection conn = (HttpURLConnection) _conn;
321 int rc = conn.getResponseCode();
322 if (rc != HttpURLConnection.HTTP_OK)
324 throw new IOException(
325 "Response status from " + urlStr + " was " + rc);
332 dataIn = checkForGzipStream(_conn.getInputStream());
334 } catch (IOException ex)
336 throw new IOException("Failed to handle non-HTTP URI stream", ex);
337 } catch (Exception ex)
339 throw new IOException(
340 "Failed to determine type of input stream for given URI",
345 String encoding = _conn.getContentEncoding();
346 String contentType = _conn.getContentType();
347 boolean isgzipped = "application/x-gzip".equalsIgnoreCase(contentType)
348 || "gzip".equals(encoding);
350 InputStream inputStream = _conn.getInputStream();
355 dataIn = getGzipReader(inputStream);
357 } catch (Exception e1)
359 throw new IOException(MessageManager
360 .getString("exception.failed_to_resolve_gzip_stream"), e);
365 dataIn = new BufferedReader(new InputStreamReader(inputStream));
371 * sets the suffix string (if any) and returns remainder (if suffix was
375 * @return truncated fileStr or null
377 private String extractSuffix(String fileStr)
379 // first check that there wasn't a suffix string tagged on.
380 int sfpos = fileStr.lastIndexOf(suffixSeparator);
381 if (sfpos > -1 && sfpos < fileStr.length() - 1)
383 suffix = fileStr.substring(sfpos + 1);
384 // System.err.println("DEBUG: Found Suffix:"+suffix);
385 return fileStr.substring(0, sfpos);
391 * not for general use, creates a fileParse object for an existing reader with
392 * configurable values for the origin and the type of the source
394 public FileParse(BufferedReader source, String originString,
395 DataSourceType sourceType)
397 dataSourceType = sourceType;
400 dataName = originString;
404 if (dataIn.markSupported())
406 dataIn.mark(READAHEAD_LIMIT);
408 } catch (IOException q)
415 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
416 * types of sources that are handled.
419 * - datasource locator/content as File or String
421 * - protocol of source
422 * @throws MalformedURLException
423 * @throws IOException
425 public FileParse(Object file, DataSourceType sourceType)
426 throws MalformedURLException, IOException
428 if (file instanceof File)
430 parse((File) file, ((File) file).getPath(), sourceType, true);
434 parse(null, file.toString(), sourceType, false);
438 private void parse(File file, String fileStr, DataSourceType sourceType,
439 boolean isFileObject) throws IOException
441 bytes = Platform.getFileBytes(file);
442 dataSourceType = sourceType;
445 if (sourceType == DataSourceType.FILE)
450 // this will be from JavaScript
452 dataIn = new BufferedReader(
453 new InputStreamReader(new ByteArrayInputStream(bytes)));
456 else if (checkFileSource(fileStr))
458 String suffixLess = extractSuffix(fileStr);
459 if (suffixLess != null)
461 if (checkFileSource(suffixLess))
463 throw new IOException(MessageManager.formatMessage(
464 "exception.problem_opening_file_also_tried",
466 { inFile.getName(), suffixLess, errormessage }));
471 throw new IOException(MessageManager.formatMessage(
472 "exception.problem_opening_file", new String[]
473 { inFile.getName(), errormessage }));
477 else if (sourceType == DataSourceType.RELATIVE_URL)
479 // BH 2018 hack for no support for access-origin
480 bytes = Platform.getFileAsBytes(fileStr);
481 dataIn = new BufferedReader(
482 new InputStreamReader(new ByteArrayInputStream(bytes)));
486 else if (sourceType == DataSourceType.URL)
492 checkURLSource(fileStr);
493 if (suffixSeparator == '#')
495 extractSuffix(fileStr); // URL lref is stored for later reference.
497 } catch (IOException e)
499 String suffixLess = extractSuffix(fileStr);
500 if (suffixLess == null)
508 checkURLSource(suffixLess);
509 } catch (IOException e2)
511 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
512 throw (e); // just pass back original - everything was wrong.
516 } catch (Exception e)
518 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
519 + e.getMessage() + ")";
523 else if (sourceType == DataSourceType.PASTE)
525 errormessage = "PASTE INACCESSIBLE!";
526 dataIn = new BufferedReader(new StringReader(fileStr));
529 else if (sourceType == DataSourceType.CLASSLOADER)
531 errormessage = "RESOURCE CANNOT BE LOCATED";
532 InputStream is = getClass().getResourceAsStream("/" + fileStr);
535 String suffixLess = extractSuffix(fileStr);
536 if (suffixLess != null)
538 is = getClass().getResourceAsStream("/" + suffixLess);
543 dataIn = new BufferedReader(new InputStreamReader(is));
553 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
554 + (sourceType != null ? sourceType : "null") + "'";
557 if (dataIn == null || error)
559 // pass up the reason why we have no source to read from
560 throw new IOException(MessageManager.formatMessage(
561 "exception.failed_to_read_data_from_source", new String[]
565 dataIn.mark(READAHEAD_LIMIT);
569 * mark the current position in the source as start for the purposes of it
570 * being analysed by IdentifyFile().identify
572 * @throws IOException
574 public void mark() throws IOException
578 dataIn.mark(READAHEAD_LIMIT);
582 throw new IOException(
583 MessageManager.getString("exception.no_init_source_stream"));
587 public String nextLine() throws IOException
591 return dataIn.readLine();
593 throw new IOException(MessageManager
594 .formatMessage("exception.invalid_source_stream", new String[]
600 * @return true if this FileParse is configured for Export only
602 public boolean isExporting()
604 return !error && dataIn == null;
609 * @return true if the data source is valid
611 public boolean isValid()
617 * closes the datasource and tidies up. source will be left in an error state
619 public void close() throws IOException
621 errormessage = "EXCEPTION ON CLOSE";
625 errormessage = "SOURCE IS CLOSED";
629 * Rewinds the datasource to the marked point if possible
634 public void reset(int bytesRead) throws IOException
636 if (bytesRead >= READAHEAD_LIMIT)
638 System.err.println(String.format(
639 "File reset error: read %d bytes but reset limit is %d",
640 bytesRead, READAHEAD_LIMIT));
642 if (dataIn != null && !error)
648 throw new IOException(MessageManager.getString(
649 "error.implementation_error_reset_called_for_invalid_source"));
655 * @return true if there is a warning for the user
657 public boolean hasWarningMessage()
659 return (warningMessage != null && warningMessage.length() > 0);
664 * @return empty string or warning message about file that was just parsed.
666 public String getWarningMessage()
668 return warningMessage;
671 public String getInFile()
675 return inFile.getAbsolutePath() + " (" + index + ")";
679 return "From Paste + (" + index + ")";
684 * @return the dataName
686 public String getDataName()
692 * set the (human readable) name or URI for this datasource
696 protected void setDataName(String dataname)
702 * get the underlying bufferedReader for this data source.
704 * @return null if no reader available
705 * @throws IOException
707 public Reader getReader()
709 if (dataIn != null) // Probably don't need to test for readiness &&
717 public AlignViewportI getViewport()
722 public void setViewport(AlignViewportI viewport)
724 this.viewport = viewport;
728 * @return the currently configured exportSettings for writing data.
730 public AlignExportSettingsI getExportSettings()
732 return exportSettings;
736 * Set configuration for export of data.
738 * @param exportSettings
739 * the exportSettings to set
741 public void setExportSettings(AlignExportSettingsI exportSettings)
743 this.exportSettings = exportSettings;
747 * method overridden by complex file exporter/importers which support
748 * exporting visualisation and layout settings for a view
752 public void configureForView(AlignmentViewPanel avpanel)
756 setViewport(avpanel.getAlignViewport());
758 // could also set export/import settings
762 * Returns the preferred feature colour configuration if there is one, else
767 public FeatureSettingsModelI getFeatureColourScheme()
772 public DataSourceType getDataSourceType()
774 return dataSourceType;
778 * Returns a buffered reader for the input object. Returns null, or throws
779 * IOException, on failure.
782 * a File, or a String which is a name of a file
785 * @throws IOException
787 public BufferedReader getBufferedReader(Object file,
788 DataSourceType sourceType) throws IOException
790 BufferedReader in = null;
796 if (file instanceof String)
798 return new BufferedReader(new FileReader((String) file));
800 bytes = Platform.getFileBytes((File) file);
803 return new BufferedReader(
804 new InputStreamReader(new ByteArrayInputStream(bytes)));
806 return new BufferedReader(new FileReader((File) file));
808 URL url = new URL(file.toString());
809 in = new BufferedReader(new InputStreamReader(url.openStream()));
811 case RELATIVE_URL: // JalviewJS only
812 bytes = Platform.getFileAsBytes(file.toString());
815 in = new BufferedReader(
816 new InputStreamReader(new ByteArrayInputStream(bytes)));
820 in = new BufferedReader(new StringReader(file.toString()));
823 InputStream is = getClass().getResourceAsStream("/" + file);
826 in = new BufferedReader(new InputStreamReader(is));