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 jalview.api.AlignExportSettingsI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.api.FeatureSettingsModelI;
26 import jalview.util.MessageManager;
28 import java.io.BufferedInputStream;
29 import java.io.BufferedReader;
30 import java.io.ByteArrayInputStream;
32 import java.io.FileInputStream;
33 import java.io.FileReader;
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;
42 import java.net.URLConnection;
43 import java.util.zip.GZIPInputStream;
45 import jalview.util.Platform;
48 * implements a random access wrapper around a particular datasource, for
49 * passing to identifyFile and AlignFile objects.
51 public class FileParse
53 protected static final String SPACE = " ";
55 protected static final String TAB = "\t";
58 * text specifying source of data. usually filename or url.
60 private String dataName = "unknown source";
62 public File inFile = null;
64 private byte[] bytes; // from JavaScript
66 public byte[] getBytes()
72 * a viewport associated with the current file operation. May be null. May
73 * move to different object.
75 private AlignViewportI viewport;
78 * specific settings for exporting data from the current context
80 private AlignExportSettingsI exportSettings;
83 * sequence counter for FileParse object created from same data source
88 * separator for extracting specific 'frame' of a datasource for formats that
89 * support multiple records (e.g. BLC, Stockholm, etc)
91 protected char suffixSeparator = '#';
94 * character used to write newlines
96 protected String newline = System.getProperty("line.separator");
98 public void setNewlineString(String nl)
103 public String getNewlineString()
109 * '#' separated string tagged on to end of filename or url that was clipped
110 * off to resolve to valid filename
112 protected String suffix = null;
114 protected DataSourceType dataSourceType = null;
116 protected BufferedReader dataIn = null;
118 protected String errormessage = "UNINITIALISED SOURCE";
120 protected boolean error = true;
122 protected String warningMessage = null;
125 * size of readahead buffer used for when initial stream position is marked.
127 final int READAHEAD_LIMIT = 2048;
134 * Create a new FileParse instance reading from the same datasource starting
135 * at the current position. WARNING! Subsequent reads from either object will
136 * affect the read position of the other, but not the error state.
140 public FileParse(FileParse from) throws IOException
144 throw new Error(MessageManager
145 .getString("error.implementation_error_null_fileparse"));
151 index = ++from.index;
152 inFile = from.inFile;
153 suffixSeparator = from.suffixSeparator;
154 suffix = from.suffix;
155 errormessage = from.errormessage; // inherit potential error messages
156 error = false; // reset any error condition.
157 dataSourceType = from.dataSourceType;
158 dataIn = from.dataIn;
163 dataName = from.dataName;
167 * Attempt to open a file as a datasource. Sets error and errormessage if
168 * fileStr was invalid.
171 * @return this.error (true if the source was invalid)
173 private boolean checkFileSource(String fileStr) throws IOException
176 this.inFile = new File(fileStr);
177 // check to see if it's a Jar file in disguise.
178 if (!inFile.exists())
180 errormessage = "FILE NOT FOUND";
183 if (!inFile.canRead())
185 errormessage = "FILE CANNOT BE OPENED FOR READING";
188 if (inFile.isDirectory())
190 // this is really a 'complex' filetype - but we don't handle directory
192 errormessage = "FILE IS A DIRECTORY";
199 dataIn = checkForGzipStream(new FileInputStream(fileStr));
201 } catch (Exception x)
203 warningMessage = "Failed to resolve " + fileStr
204 + " as a data source. (" + x.getMessage() + ")";
205 // x.printStackTrace();
214 * Recognise the 2-byte magic header for gzip streams
216 * https://recalll.co/ask/v/topic/java-How-to-check-if-InputStream-is-Gzipped/555aadd62bd27354438b90f6
218 * @param bytes - at least two bytes
221 private static boolean isGzipStream(byte[] bytes) {
222 int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
223 return (GZIPInputStream.GZIP_MAGIC == head);
227 * Returns a Reader for the given input after wrapping it in a buffered input
228 * stream, and then checking if it needs to be wrapped by a GZipInputStream
233 private BufferedReader checkForGzipStream(InputStream input) throws Exception {
235 // NB: stackoverflow https://stackoverflow.com/questions/4818468/how-to-check-if-inputstream-is-gzipped
236 // could use a PushBackInputStream rather than a BufferedInputStream
238 BufferedInputStream bufinput;
239 if (!input.markSupported()) {
240 bufinput= new BufferedInputStream(input,16);
244 byte[] bytes=input.readNBytes(2);
246 if (bytes.length==2 && isGzipStream(bytes)) {
247 return getGzipReader(input);
249 // return a buffered reader for the stream.
250 InputStreamReader isReader= new InputStreamReader(input);
251 BufferedReader toReadFrom=new BufferedReader(isReader);
255 * Returns a {@code BufferedReader} which wraps the input stream with a
256 * GZIPInputStream. Throws a {@code ZipException} if a GZIP format error
257 * occurs or the compression method used is unsupported.
263 private BufferedReader getGzipReader(InputStream inputStream)
266 BufferedReader inData = new BufferedReader(
267 new InputStreamReader(new GZIPInputStream(inputStream)));
275 * Tries to read from the given URL. If successful, saves a reader to the
276 * response in field {@code dataIn}, otherwise (on exception, or HTTP response
277 * status not 200), throws an exception.
279 * If the response status includes
282 * Content-Type : application/x-gzip
285 * then tries to read as gzipped content.
288 * @throws IOException
289 * @throws MalformedURLException
291 private void checkURLSource(String urlStr)
292 throws IOException, MalformedURLException
294 errormessage = "URL NOT FOUND";
295 URL url = new URL(urlStr);
296 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
297 int rc = conn.getResponseCode();
298 if (rc != HttpURLConnection.HTTP_OK)
300 throw new IOException(
301 "Response status from " + urlStr + " was " + rc);
303 String encoding = conn.getContentEncoding();
304 String contentType = conn.getContentType();
305 boolean isgzipped = "application/x-gzip".equalsIgnoreCase(contentType)
306 || "gzip".equals(encoding);
308 InputStream inputStream = conn.getInputStream();
313 dataIn = getGzipReader(inputStream);
315 } catch (Exception e1)
317 throw new IOException(MessageManager
318 .getString("exception.failed_to_resolve_gzip_stream"), e);
323 dataIn = new BufferedReader(new InputStreamReader(inputStream));
329 * sets the suffix string (if any) and returns remainder (if suffix was
333 * @return truncated fileStr or null
335 private String extractSuffix(String fileStr)
337 // first check that there wasn't a suffix string tagged on.
338 int sfpos = fileStr.lastIndexOf(suffixSeparator);
339 if (sfpos > -1 && sfpos < fileStr.length() - 1)
341 suffix = fileStr.substring(sfpos + 1);
342 // System.err.println("DEBUG: Found Suffix:"+suffix);
343 return fileStr.substring(0, sfpos);
349 * not for general use, creates a fileParse object for an existing reader with
350 * configurable values for the origin and the type of the source
352 public FileParse(BufferedReader source, String originString,
353 DataSourceType sourceType)
355 dataSourceType = sourceType;
358 dataName = originString;
362 if (dataIn.markSupported())
364 dataIn.mark(READAHEAD_LIMIT);
366 } catch (IOException q)
373 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
374 * types of sources that are handled.
377 * - datasource locator/content as File or String
379 * - protocol of source
380 * @throws MalformedURLException
381 * @throws IOException
383 public FileParse(Object file, DataSourceType sourceType)
384 throws MalformedURLException, IOException
386 if (file instanceof File)
388 parse((File) file, ((File) file).getPath(), sourceType, true);
392 parse(null, file.toString(), sourceType, false);
396 private void parse(File file, String fileStr, DataSourceType sourceType,
397 boolean isFileObject) throws IOException
399 bytes = Platform.getFileBytes(file);
400 dataSourceType = sourceType;
403 if (sourceType == DataSourceType.FILE)
408 // this will be from JavaScript
410 dataIn = new BufferedReader(
411 new InputStreamReader(new ByteArrayInputStream(bytes)));
414 else if (checkFileSource(fileStr))
416 String suffixLess = extractSuffix(fileStr);
417 if (suffixLess != null)
419 if (checkFileSource(suffixLess))
421 throw new IOException(MessageManager.formatMessage(
422 "exception.problem_opening_file_also_tried",
424 { inFile.getName(), suffixLess, errormessage }));
429 throw new IOException(MessageManager.formatMessage(
430 "exception.problem_opening_file", new String[]
431 { inFile.getName(), errormessage }));
435 else if (sourceType == DataSourceType.RELATIVE_URL)
437 // BH 2018 hack for no support for access-origin
438 bytes = Platform.getFileAsBytes(fileStr);
439 dataIn = new BufferedReader(
440 new InputStreamReader(new ByteArrayInputStream(bytes)));
444 else if (sourceType == DataSourceType.URL)
450 checkURLSource(fileStr);
451 if (suffixSeparator == '#')
453 extractSuffix(fileStr); // URL lref is stored for later reference.
455 } catch (IOException e)
457 String suffixLess = extractSuffix(fileStr);
458 if (suffixLess == null)
466 checkURLSource(suffixLess);
467 } catch (IOException e2)
469 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
470 throw (e); // just pass back original - everything was wrong.
474 } catch (Exception e)
476 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
477 + e.getMessage() + ")";
481 else if (sourceType == DataSourceType.PASTE)
483 errormessage = "PASTE INACCESSIBLE!";
484 dataIn = new BufferedReader(new StringReader(fileStr));
487 else if (sourceType == DataSourceType.CLASSLOADER)
489 errormessage = "RESOURCE CANNOT BE LOCATED";
490 InputStream is = getClass().getResourceAsStream("/" + fileStr);
493 String suffixLess = extractSuffix(fileStr);
494 if (suffixLess != null)
496 is = getClass().getResourceAsStream("/" + suffixLess);
501 dataIn = new BufferedReader(new InputStreamReader(is));
511 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
512 + (sourceType != null ? sourceType : "null") + "'";
515 if (dataIn == null || error)
517 // pass up the reason why we have no source to read from
518 throw new IOException(MessageManager.formatMessage(
519 "exception.failed_to_read_data_from_source", new String[]
523 dataIn.mark(READAHEAD_LIMIT);
527 * mark the current position in the source as start for the purposes of it
528 * being analysed by IdentifyFile().identify
530 * @throws IOException
532 public void mark() throws IOException
536 dataIn.mark(READAHEAD_LIMIT);
540 throw new IOException(
541 MessageManager.getString("exception.no_init_source_stream"));
545 public String nextLine() throws IOException
549 return dataIn.readLine();
551 throw new IOException(MessageManager
552 .formatMessage("exception.invalid_source_stream", new String[]
558 * @return true if this FileParse is configured for Export only
560 public boolean isExporting()
562 return !error && dataIn == null;
567 * @return true if the data source is valid
569 public boolean isValid()
575 * closes the datasource and tidies up. source will be left in an error state
577 public void close() throws IOException
579 errormessage = "EXCEPTION ON CLOSE";
583 errormessage = "SOURCE IS CLOSED";
587 * Rewinds the datasource to the marked point if possible
592 public void reset(int bytesRead) throws IOException
594 if (bytesRead >= READAHEAD_LIMIT)
596 System.err.println(String.format(
597 "File reset error: read %d bytes but reset limit is %d",
598 bytesRead, READAHEAD_LIMIT));
600 if (dataIn != null && !error)
606 throw new IOException(MessageManager.getString(
607 "error.implementation_error_reset_called_for_invalid_source"));
613 * @return true if there is a warning for the user
615 public boolean hasWarningMessage()
617 return (warningMessage != null && warningMessage.length() > 0);
622 * @return empty string or warning message about file that was just parsed.
624 public String getWarningMessage()
626 return warningMessage;
629 public String getInFile()
633 return inFile.getAbsolutePath() + " (" + index + ")";
637 return "From Paste + (" + index + ")";
642 * @return the dataName
644 public String getDataName()
650 * set the (human readable) name or URI for this datasource
654 protected void setDataName(String dataname)
660 * get the underlying bufferedReader for this data source.
662 * @return null if no reader available
663 * @throws IOException
665 public Reader getReader()
667 if (dataIn != null) // Probably don't need to test for readiness &&
675 public AlignViewportI getViewport()
680 public void setViewport(AlignViewportI viewport)
682 this.viewport = viewport;
686 * @return the currently configured exportSettings for writing data.
688 public AlignExportSettingsI getExportSettings()
690 return exportSettings;
694 * Set configuration for export of data.
696 * @param exportSettings
697 * the exportSettings to set
699 public void setExportSettings(AlignExportSettingsI exportSettings)
701 this.exportSettings = exportSettings;
705 * method overridden by complex file exporter/importers which support
706 * exporting visualisation and layout settings for a view
710 public void configureForView(AlignmentViewPanel avpanel)
714 setViewport(avpanel.getAlignViewport());
716 // could also set export/import settings
720 * Returns the preferred feature colour configuration if there is one, else
725 public FeatureSettingsModelI getFeatureColourScheme()
730 public DataSourceType getDataSourceType()
732 return dataSourceType;
736 * Returns a buffered reader for the input object. Returns null, or throws
737 * IOException, on failure.
740 * a File, or a String which is a name of a file
743 * @throws IOException
745 public BufferedReader getBufferedReader(Object file,
746 DataSourceType sourceType) throws IOException
748 BufferedReader in = null;
754 if (file instanceof String)
756 return new BufferedReader(new FileReader((String) file));
758 bytes = Platform.getFileBytes((File) file);
761 return new BufferedReader(
762 new InputStreamReader(new ByteArrayInputStream(bytes)));
764 return new BufferedReader(new FileReader((File) file));
766 URL url = new URL(file.toString());
767 in = new BufferedReader(new InputStreamReader(url.openStream()));
769 case RELATIVE_URL: // JalviewJS only
770 bytes = Platform.getFileAsBytes(file.toString());
773 in = new BufferedReader(
774 new InputStreamReader(new ByteArrayInputStream(bytes)));
778 in = new BufferedReader(new StringReader(file.toString()));
781 InputStream is = getClass().getResourceAsStream("/" + file);
784 in = new BufferedReader(new InputStreamReader(is));