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.FileNotFoundException;
29 import java.io.FileReader;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.InputStreamReader;
33 import java.io.Reader;
34 import java.io.StringReader;
35 import java.net.HttpURLConnection;
36 import java.net.MalformedURLException;
38 import java.net.URLConnection;
39 import java.net.UnknownHostException;
40 import java.util.zip.GZIPInputStream;
42 import jalview.api.AlignExportSettingsI;
43 import jalview.api.AlignViewportI;
44 import jalview.api.AlignmentViewPanel;
45 import jalview.api.FeatureSettingsModelI;
46 import jalview.bin.Console;
47 import jalview.util.HttpUtils;
48 import jalview.util.MessageManager;
49 import jalview.util.Platform;
52 * implements a random access wrapper around a particular datasource, for
53 * passing to identifyFile and AlignFile objects.
55 public class FileParse
57 protected static final String SPACE = " ";
59 protected static final String TAB = "\t";
62 * text specifying source of data. usually filename or url.
64 private String dataName = "unknown source";
66 public File inFile = null;
68 private byte[] bytes; // from JavaScript
70 public byte[] getBytes()
76 * a viewport associated with the current file operation. May be null. May
77 * move to different object.
79 private AlignViewportI viewport;
82 * specific settings for exporting data from the current context
84 private AlignExportSettingsI exportSettings;
87 * sequence counter for FileParse object created from same data source
92 * separator for extracting specific 'frame' of a datasource for formats that
93 * support multiple records (e.g. BLC, Stockholm, etc)
95 protected char suffixSeparator = '#';
98 * character used to write newlines
100 protected String newline = System.getProperty("line.separator");
102 public void setNewlineString(String nl)
107 public String getNewlineString()
113 * '#' separated string tagged on to end of filename or url that was clipped
114 * off to resolve to valid filename
116 protected String suffix = null;
118 protected DataSourceType dataSourceType = null;
120 protected BufferedReader dataIn = null;
122 protected String errormessage = "UNINITIALISED SOURCE";
124 protected boolean error = true;
126 protected String warningMessage = null;
129 * size of readahead buffer used for when initial stream position is marked.
131 final int READAHEAD_LIMIT = 2048;
138 * Create a new FileParse instance reading from the same datasource starting
139 * at the current position. WARNING! Subsequent reads from either object will
140 * affect the read position of the other, but not the error state.
144 public FileParse(FileParse from) throws IOException
148 throw new Error(MessageManager
149 .getString("error.implementation_error_null_fileparse"));
155 index = ++from.index;
156 inFile = from.inFile;
157 suffixSeparator = from.suffixSeparator;
158 suffix = from.suffix;
159 errormessage = from.errormessage; // inherit potential error messages
160 error = false; // reset any error condition.
161 dataSourceType = from.dataSourceType;
162 dataIn = from.dataIn;
167 dataName = from.dataName;
171 * Attempt to open a file as a datasource. Sets error and errormessage if
172 * fileStr was invalid.
175 * @return this.error (true if the source was invalid)
177 private boolean checkFileSource(String fileStr) throws IOException
180 this.inFile = new File(fileStr);
181 // check to see if it's a Jar file in disguise.
182 if (!inFile.exists())
184 errormessage = "FILE NOT FOUND";
187 if (!inFile.canRead())
189 errormessage = "FILE CANNOT BE OPENED FOR READING";
192 if (inFile.isDirectory())
194 // this is really a 'complex' filetype - but we don't handle directory
196 errormessage = "FILE IS A DIRECTORY";
203 dataIn = checkForGzipStream(new FileInputStream(fileStr));
205 } catch (Exception x)
207 warningMessage = "Failed to resolve " + fileStr
208 + " as a data source. (" + x.getMessage() + ")";
209 // x.printStackTrace();
218 * Recognise the 2-byte magic header for gzip streams
220 * https://recalll.co/ask/v/topic/java-How-to-check-if-InputStream-is-Gzipped/555aadd62bd27354438b90f6
223 * - at least two bytes
225 * @throws IOException
227 public static boolean isGzipStream(InputStream input) throws IOException
229 if (!input.markSupported())
232 "FileParse.izGzipStream: input stream must support mark/reset");
237 // get first 2 bytes or return false
238 byte[] bytes = new byte[2];
239 int read = input.read(bytes);
241 if (read != bytes.length)
246 int header = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
247 return (GZIPInputStream.GZIP_MAGIC == header);
251 * Returns a Reader for the given input after wrapping it in a buffered input
252 * stream, and then checking if it needs to be wrapped by a GZipInputStream
257 private BufferedReader checkForGzipStream(InputStream input)
261 // https://stackoverflow.com/questions/4818468/how-to-check-if-inputstream-is-gzipped
262 // could use a PushBackInputStream rather than a BufferedInputStream
263 if (!input.markSupported())
265 input = new BufferedInputStream(input, 16);
267 if (isGzipStream(input))
269 return getGzipReader(input);
271 // return a buffered reader for the stream.
272 InputStreamReader isReader = new InputStreamReader(input);
273 BufferedReader toReadFrom = new BufferedReader(isReader);
278 * Returns a {@code BufferedReader} which wraps the input stream with a
279 * GZIPInputStream. Throws a {@code ZipException} if a GZIP format error
280 * occurs or the compression method used is unsupported.
286 private BufferedReader getGzipReader(InputStream inputStream)
289 BufferedReader inData = new BufferedReader(
290 new InputStreamReader(new GZIPInputStream(inputStream)));
298 * Tries to read from the given URL. If successful, saves a reader to the
299 * response in field {@code dataIn}, otherwise (on exception, or HTTP response
300 * status not 200), throws an exception.
302 * If the response status includes
305 * Content-Type : application/x-gzip
308 * then tries to read as gzipped content.
311 * @throws IOException
312 * @throws MalformedURLException
314 private void checkURLSource(String urlStr)
315 throws IOException, MalformedURLException
317 errormessage = "URL NOT FOUND";
318 URL url = new URL(urlStr);
319 URLConnection _conn = HttpUtils.openConnection(url);
320 if (_conn instanceof HttpURLConnection)
322 HttpURLConnection conn = HttpUtils
323 .followConnection((HttpURLConnection) _conn);
324 int rc = conn.getResponseCode();
325 if (rc != HttpURLConnection.HTTP_OK)
327 throw new FileNotFoundException("Response status from " + urlStr
328 + " was " + conn.getResponseCode());
336 dataIn = checkForGzipStream(_conn.getInputStream());
338 } catch (IOException ex)
340 throw new IOException("Failed to handle non-HTTP URI stream", ex);
341 } catch (Exception ex)
343 throw new IOException(
344 "Failed to determine type of input stream for given URI",
349 String encoding = _conn.getContentEncoding();
350 String contentType = _conn.getContentType();
351 boolean isgzipped = "application/x-gzip".equalsIgnoreCase(contentType)
352 || contentType.endsWith("gzip") || "gzip".equals(encoding);
354 InputStream inputStream = _conn.getInputStream();
359 dataIn = getGzipReader(inputStream);
361 } catch (Exception e1)
363 throw new IOException(MessageManager
364 .getString("exception.failed_to_resolve_gzip_stream"), e);
369 dataIn = new BufferedReader(new InputStreamReader(inputStream));
375 * sets the suffix string (if any) and returns remainder (if suffix was
379 * @return truncated fileStr or null
381 private String extractSuffix(String fileStr)
383 // first check that there wasn't a suffix string tagged on.
384 int sfpos = fileStr.lastIndexOf(suffixSeparator);
385 if (sfpos > -1 && sfpos < fileStr.length() - 1)
387 suffix = fileStr.substring(sfpos + 1);
388 // jalview.bin.Console.errPrintln("DEBUG: Found Suffix:"+suffix);
389 return fileStr.substring(0, sfpos);
395 * not for general use, creates a fileParse object for an existing reader with
396 * configurable values for the origin and the type of the source
398 public FileParse(BufferedReader source, String originString,
399 DataSourceType sourceType)
401 dataSourceType = sourceType;
404 dataName = originString;
408 if (dataIn.markSupported())
410 dataIn.mark(READAHEAD_LIMIT);
412 } catch (IOException q)
419 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
420 * types of sources that are handled.
423 * - datasource locator/content as File or String
425 * - protocol of source
426 * @throws MalformedURLException
427 * @throws IOException
429 public FileParse(Object file, DataSourceType sourceType)
430 throws MalformedURLException, FileNotFoundException, IOException
432 if (file instanceof File)
434 parse((File) file, ((File) file).getPath(), sourceType, true);
438 parse(null, file.toString(), sourceType, false);
442 private void parse(File file, String fileStr, DataSourceType sourceType,
443 boolean isFileObject) throws FileNotFoundException, IOException
445 bytes = Platform.getFileBytes(file);
446 dataSourceType = sourceType;
448 boolean filenotfound = false;
450 if (sourceType == DataSourceType.FILE)
455 // this will be from JavaScript
457 dataIn = new BufferedReader(
458 new InputStreamReader(new ByteArrayInputStream(bytes)));
461 else if (checkFileSource(fileStr))
463 String suffixLess = extractSuffix(fileStr);
464 if (suffixLess != null)
466 if (checkFileSource(suffixLess))
468 throw new IOException(MessageManager.formatMessage(
469 "exception.problem_opening_file_also_tried",
471 { inFile.getName(), suffixLess, errormessage }));
476 throw new IOException(MessageManager.formatMessage(
477 "exception.problem_opening_file", new String[]
478 { inFile.getName(), errormessage }));
482 else if (sourceType == DataSourceType.RELATIVE_URL)
484 // BH 2018 hack for no support for access-origin
485 bytes = Platform.getFileAsBytes(fileStr);
486 dataIn = new BufferedReader(
487 new InputStreamReader(new ByteArrayInputStream(bytes)));
491 else if (sourceType == DataSourceType.URL)
497 checkURLSource(fileStr);
498 if (suffixSeparator == '#')
500 extractSuffix(fileStr); // URL lref is stored for later reference.
502 } catch (IOException e)
504 String suffixLess = extractSuffix(fileStr);
505 if (suffixLess == null)
507 if (e instanceof FileNotFoundException
508 || e instanceof UnknownHostException)
510 errormessage = "File at URL '" + fileStr + "' not found";
519 checkURLSource(suffixLess);
520 } catch (IOException e2)
522 errormessage = "BAD URL WITH OR WITHOUT SUFFIX '" + fileStr
524 if (e instanceof FileNotFoundException)
528 throw (e); // just pass back original - everything was wrong.
532 } catch (Exception e)
534 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
535 + e.getMessage() + ")";
539 else if (sourceType == DataSourceType.PASTE)
541 errormessage = "PASTE INACCESSIBLE!";
542 dataIn = new BufferedReader(new StringReader(fileStr));
545 else if (sourceType == DataSourceType.CLASSLOADER)
547 errormessage = "RESOURCE CANNOT BE LOCATED";
548 InputStream is = getClass().getResourceAsStream("/" + fileStr);
551 String suffixLess = extractSuffix(fileStr);
552 if (suffixLess != null)
554 is = getClass().getResourceAsStream("/" + suffixLess);
559 dataIn = new BufferedReader(new InputStreamReader(is));
569 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
570 + (sourceType != null ? sourceType : "null") + "'";
573 if (dataIn == null || error)
575 // pass up the reason why we have no source to read from
578 throw new FileNotFoundException(MessageManager
579 .formatMessage("label.url_not_found", new String[]
582 throw new IOException(MessageManager.formatMessage(
583 "exception.failed_to_read_data_from_source", new String[]
587 dataIn.mark(READAHEAD_LIMIT);
591 * mark the current position in the source as start for the purposes of it
592 * being analysed by IdentifyFile().identify
594 * @throws IOException
596 public void mark() throws IOException
600 dataIn.mark(READAHEAD_LIMIT);
604 throw new IOException(
605 MessageManager.getString("exception.no_init_source_stream"));
609 public String nextLine() throws IOException
613 return dataIn.readLine();
615 throw new IOException(MessageManager
616 .formatMessage("exception.invalid_source_stream", new String[]
622 * @return true if this FileParse is configured for Export only
624 public boolean isExporting()
626 return !error && dataIn == null;
631 * @return true if the data source is valid
633 public boolean isValid()
639 * closes the datasource and tidies up. source will be left in an error state
641 public void close() throws IOException
643 errormessage = "EXCEPTION ON CLOSE";
647 errormessage = "SOURCE IS CLOSED";
651 * Rewinds the datasource to the marked point if possible
656 public void reset(int bytesRead) throws IOException
658 if (bytesRead >= READAHEAD_LIMIT)
660 jalview.bin.Console.errPrintln(String.format(
661 "File reset error: read %d bytes but reset limit is %d",
662 bytesRead, READAHEAD_LIMIT));
664 if (dataIn != null && !error)
670 throw new IOException(MessageManager.getString(
671 "error.implementation_error_reset_called_for_invalid_source"));
677 * @return true if there is a warning for the user
679 public boolean hasWarningMessage()
681 return (warningMessage != null && warningMessage.length() > 0);
686 * @return empty string or warning message about file that was just parsed.
688 public String getWarningMessage()
690 return warningMessage;
693 public String getInFile()
697 return inFile.getAbsolutePath() + " (" + index + ")";
701 return "From Paste + (" + index + ")";
706 * @return the dataName
708 public String getDataName()
714 * set the (human readable) name or URI for this datasource
718 protected void setDataName(String dataname)
724 * get the underlying bufferedReader for this data source.
726 * @return null if no reader available
727 * @throws IOException
729 public Reader getReader()
731 if (dataIn != null) // Probably don't need to test for readiness &&
739 public AlignViewportI getViewport()
744 public void setViewport(AlignViewportI viewport)
746 this.viewport = viewport;
750 * @return the currently configured exportSettings for writing data.
752 public AlignExportSettingsI getExportSettings()
754 return exportSettings;
758 * Set configuration for export of data.
760 * @param exportSettings
761 * the exportSettings to set
763 public void setExportSettings(AlignExportSettingsI exportSettings)
765 this.exportSettings = exportSettings;
769 * method overridden by complex file exporter/importers which support
770 * exporting visualisation and layout settings for a view
774 public void configureForView(AlignmentViewPanel avpanel)
778 setViewport(avpanel.getAlignViewport());
780 // could also set export/import settings
784 * Returns the preferred feature colour configuration if there is one, else
789 public FeatureSettingsModelI getFeatureColourScheme()
794 public DataSourceType getDataSourceType()
796 return dataSourceType;
800 * Returns a buffered reader for the input object. Returns null, or throws
801 * IOException, on failure.
804 * a File, or a String which is a name of a file
807 * @throws IOException
809 public BufferedReader getBufferedReader(Object file,
810 DataSourceType sourceType) throws IOException
812 BufferedReader in = null;
818 if (file instanceof String)
820 return new BufferedReader(new FileReader((String) file));
822 bytes = Platform.getFileBytes((File) file);
825 return new BufferedReader(
826 new InputStreamReader(new ByteArrayInputStream(bytes)));
828 return new BufferedReader(new FileReader((File) file));
830 URL url = new URL(file.toString());
831 in = new BufferedReader(
832 new InputStreamReader(HttpUtils.openStream(url)));
834 case RELATIVE_URL: // JalviewJS only
835 bytes = Platform.getFileAsBytes(file.toString());
838 in = new BufferedReader(
839 new InputStreamReader(new ByteArrayInputStream(bytes)));
843 in = new BufferedReader(new StringReader(file.toString()));
846 InputStream is = getClass().getResourceAsStream("/" + file);
849 in = new BufferedReader(new InputStreamReader(is));