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.AlignExportSettingI;
24 import jalview.api.AlignViewportI;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.api.FeatureSettingsModelI;
27 import jalview.util.MessageManager;
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.MalformedURLException;
41 import java.util.zip.GZIPInputStream;
44 * implements a random access wrapper around a particular datasource, for
45 * passing to identifyFile and AlignFile objects.
47 public class FileParse
49 protected static final String SPACE = " ";
51 protected static final String TAB = "\t";
54 * text specifying source of data. usually filename or url.
56 private String dataName = "unknown source";
58 public File inFile = null;
60 private byte[] bytes; // from JavaScript
62 public byte[] getBytes()
67 * a viewport associated with the current file operation. May be null. May
68 * move to different object.
70 private AlignViewportI viewport;
73 * specific settings for exporting data from the current context
75 private AlignExportSettingI exportSettings;
78 * sequence counter for FileParse object created from same data source
83 * separator for extracting specific 'frame' of a datasource for formats that
84 * support multiple records (e.g. BLC, Stockholm, etc)
86 protected char suffixSeparator = '#';
89 * character used to write newlines
91 protected String newline = System.getProperty("line.separator");
93 public void setNewlineString(String nl)
98 public String getNewlineString()
104 * '#' separated string tagged on to end of filename or url that was clipped
105 * off to resolve to valid filename
107 protected String suffix = null;
109 protected DataSourceType dataSourceType = null;
111 protected BufferedReader dataIn = null;
113 protected String errormessage = "UNINITIALISED SOURCE";
115 protected boolean error = true;
117 protected String warningMessage = null;
120 * size of readahead buffer used for when initial stream position is marked.
122 final int READAHEAD_LIMIT = 2048;
129 * Create a new FileParse instance reading from the same datasource starting
130 * at the current position. WARNING! Subsequent reads from either object will
131 * affect the read position of the other, but not the error state.
135 public FileParse(FileParse from) throws IOException
139 throw new Error(MessageManager
140 .getString("error.implementation_error_null_fileparse"));
146 index = ++from.index;
147 inFile = from.inFile;
148 suffixSeparator = from.suffixSeparator;
149 suffix = from.suffix;
150 errormessage = from.errormessage; // inherit potential error messages
151 error = false; // reset any error condition.
152 dataSourceType = from.dataSourceType;
153 dataIn = from.dataIn;
158 dataName = from.dataName;
162 * Attempt to open a file as a datasource. Sets error and errormessage if
163 * fileStr was invalid.
166 * @return this.error (true if the source was invalid)
168 private boolean checkFileSource(String fileStr) throws IOException
171 this.inFile = new File(fileStr);
172 // check to see if it's a Jar file in disguise.
173 if (!inFile.exists())
175 errormessage = "FILE NOT FOUND";
178 if (!inFile.canRead())
180 errormessage = "FILE CANNOT BE OPENED FOR READING";
183 if (inFile.isDirectory())
185 // this is really a 'complex' filetype - but we don't handle directory
187 errormessage = "FILE IS A DIRECTORY";
192 if (fileStr.toLowerCase().endsWith(".gz"))
196 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
199 } catch (Exception x)
201 warningMessage = "Failed to resolve as a GZ stream ("
202 + x.getMessage() + ")";
203 // x.printStackTrace();
208 dataIn = new BufferedReader(new FileReader(fileStr));
214 private BufferedReader tryAsGzipSource(InputStream inputStream)
217 BufferedReader inData = new BufferedReader(
218 new InputStreamReader(new GZIPInputStream(inputStream)));
225 private boolean checkURLSource(String fileStr)
226 throws IOException, MalformedURLException
228 errormessage = "URL NOT FOUND";
229 URL url = new URL(fileStr);
231 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
234 if (fileStr.toLowerCase().endsWith(".gz"))
238 InputStream inputStream = url.openStream();
239 dataIn = tryAsGzipSource(inputStream);
242 } catch (Exception ex)
250 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
251 } catch (IOException q)
255 throw new IOException(MessageManager
256 .getString("exception.failed_to_resolve_gzip_stream"), e);
260 // record URL as name of datasource.
266 * sets the suffix string (if any) and returns remainder (if suffix was
270 * @return truncated fileStr or null
272 private String extractSuffix(String fileStr)
274 // first check that there wasn't a suffix string tagged on.
275 int sfpos = fileStr.lastIndexOf(suffixSeparator);
276 if (sfpos > -1 && sfpos < fileStr.length() - 1)
278 suffix = fileStr.substring(sfpos + 1);
279 // System.err.println("DEBUG: Found Suffix:"+suffix);
280 return fileStr.substring(0, sfpos);
286 * not for general use, creates a fileParse object for an existing reader with
287 * configurable values for the origin and the type of the source
289 public FileParse(BufferedReader source, String originString,
290 DataSourceType sourceType)
292 dataSourceType = sourceType;
295 dataName = originString;
299 if (dataIn.markSupported())
301 dataIn.mark(READAHEAD_LIMIT);
303 } catch (IOException q)
310 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
311 * types of sources that are handled.
314 * - datasource locator/content as File or String
316 * - protocol of source
317 * @throws MalformedURLException
318 * @throws IOException
320 public FileParse(Object file, DataSourceType sourceType)
321 throws MalformedURLException, IOException
323 if (file instanceof File)
325 parse((File) file, ((File) file).getPath(), sourceType, true);
329 parse(null, file.toString(), sourceType, false);
333 private void parse(File file, String fileStr, DataSourceType sourceType,
334 boolean isFileObject) throws MalformedURLException, IOException
339 * this.bytes = file && file._bytes;
342 this.dataSourceType = sourceType;
345 if (sourceType == DataSourceType.FILE)
350 // this will be from JavaScript
352 dataIn = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
355 else if (checkFileSource(fileStr))
357 String suffixLess = extractSuffix(fileStr);
358 if (suffixLess != null)
360 if (checkFileSource(suffixLess))
362 throw new IOException(MessageManager.formatMessage(
363 "exception.problem_opening_file_also_tried",
365 { inFile.getName(), suffixLess, errormessage }));
370 throw new IOException(MessageManager.formatMessage(
371 "exception.problem_opening_file", new String[]
372 { inFile.getName(), errormessage }));
376 else if (sourceType == DataSourceType.RELATIVE_URL)
379 * BH 2018 hack for no support for access-origin
383 * this.bytes = swingjs.JSUtil.getFileAsBytes$O(fileStr);
387 dataIn = new BufferedReader(new java.io.InputStreamReader(new ByteArrayInputStream(bytes)));
391 else if (sourceType == DataSourceType.URL)
397 checkURLSource(fileStr);
398 if (suffixSeparator == '#')
400 extractSuffix(fileStr); // URL lref is stored for later reference.
402 } catch (IOException e)
404 String suffixLess = extractSuffix(fileStr);
405 if (suffixLess == null)
413 checkURLSource(suffixLess);
414 } catch (IOException e2)
416 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
417 throw (e); // just pass back original - everything was wrong.
421 } catch (Exception e)
423 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
424 + e.getMessage() + ")";
428 else if (sourceType == DataSourceType.PASTE)
430 errormessage = "PASTE INACCESSIBLE!";
431 dataIn = new BufferedReader(new StringReader(fileStr));
434 else if (sourceType == DataSourceType.CLASSLOADER)
436 errormessage = "RESOURCE CANNOT BE LOCATED";
437 java.io.InputStream is = getClass()
438 .getResourceAsStream("/" + fileStr);
441 String suffixLess = extractSuffix(fileStr);
442 if (suffixLess != null)
444 is = getClass().getResourceAsStream("/" + suffixLess);
449 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
459 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
460 + (sourceType != null ? sourceType : "null") + "'";
463 if (dataIn == null || error)
465 // pass up the reason why we have no source to read from
466 throw new IOException(MessageManager.formatMessage(
467 "exception.failed_to_read_data_from_source",
472 dataIn.mark(READAHEAD_LIMIT);
476 * mark the current position in the source as start for the purposes of it
477 * being analysed by IdentifyFile().identify
479 * @throws IOException
481 public void mark() throws IOException
485 dataIn.mark(READAHEAD_LIMIT);
489 throw new IOException(
490 MessageManager.getString("exception.no_init_source_stream"));
494 public String nextLine() throws IOException
498 return dataIn.readLine();
500 throw new IOException(MessageManager
501 .formatMessage("exception.invalid_source_stream", new String[]
507 * @return true if this FileParse is configured for Export only
509 public boolean isExporting()
511 return !error && dataIn == null;
516 * @return true if the data source is valid
518 public boolean isValid()
524 * closes the datasource and tidies up. source will be left in an error state
526 public void close() throws IOException
528 errormessage = "EXCEPTION ON CLOSE";
532 errormessage = "SOURCE IS CLOSED";
536 * Rewinds the datasource to the marked point if possible
541 public void reset(int bytesRead) throws IOException
543 if (bytesRead >= READAHEAD_LIMIT)
545 System.err.println(String.format(
546 "File reset error: read %d bytes but reset limit is %d",
547 bytesRead, READAHEAD_LIMIT));
549 if (dataIn != null && !error)
555 throw new IOException(MessageManager.getString(
556 "error.implementation_error_reset_called_for_invalid_source"));
562 * @return true if there is a warning for the user
564 public boolean hasWarningMessage()
566 return (warningMessage != null && warningMessage.length() > 0);
571 * @return empty string or warning message about file that was just parsed.
573 public String getWarningMessage()
575 return warningMessage;
578 public String getInFile()
582 return inFile.getAbsolutePath() + " (" + index + ")";
586 return "From Paste + (" + index + ")";
591 * @return the dataName
593 public String getDataName()
599 * set the (human readable) name or URI for this datasource
603 protected void setDataName(String dataname)
609 * get the underlying bufferedReader for this data source.
611 * @return null if no reader available
612 * @throws IOException
614 public Reader getReader()
616 if (dataIn != null) // Probably don't need to test for readiness &&
624 public AlignViewportI getViewport()
629 public void setViewport(AlignViewportI viewport)
631 this.viewport = viewport;
635 * @return the currently configured exportSettings for writing data.
637 public AlignExportSettingI getExportSettings()
639 return exportSettings;
643 * Set configuration for export of data.
645 * @param exportSettings
646 * the exportSettings to set
648 public void setExportSettings(AlignExportSettingI exportSettings)
650 this.exportSettings = exportSettings;
654 * method overridden by complex file exporter/importers which support
655 * exporting visualisation and layout settings for a view
659 public void configureForView(AlignmentViewPanel avpanel)
663 setViewport(avpanel.getAlignViewport());
665 // could also set export/import settings
669 * Returns the preferred feature colour configuration if there is one, else
674 public FeatureSettingsModelI getFeatureColourScheme()
679 public DataSourceType getDataSourceType()
681 return dataSourceType;