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;
31 import java.io.FileInputStream;
32 import java.io.FileReader;
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.MalformedURLException;
40 import java.util.zip.GZIPInputStream;
42 import javajs.util.Rdr;
45 * implements a random access wrapper around a particular datasource, for
46 * passing to identifyFile and AlignFile objects.
48 public class FileParse
50 protected static final String SPACE = " ";
52 protected static final String TAB = "\t";
55 * text specifying source of data. usually filename or url.
57 private String dataName = "unknown source";
59 public File inFile = null;
61 public byte[] bytes; // from JavaScript
64 * a viewport associated with the current file operation. May be null. May
65 * move to different object.
67 private AlignViewportI viewport;
70 * specific settings for exporting data from the current context
72 private AlignExportSettingI exportSettings;
75 * sequence counter for FileParse object created from same data source
80 * separator for extracting specific 'frame' of a datasource for formats that
81 * support multiple records (e.g. BLC, Stockholm, etc)
83 protected char suffixSeparator = '#';
86 * character used to write newlines
88 protected String newline = System.getProperty("line.separator");
90 public void setNewlineString(String nl)
95 public String getNewlineString()
101 * '#' separated string tagged on to end of filename or url that was clipped
102 * off to resolve to valid filename
104 protected String suffix = null;
106 protected DataSourceType dataSourceType = null;
108 protected BufferedReader dataIn = null;
110 protected String errormessage = "UNINITIALISED SOURCE";
112 protected boolean error = true;
114 protected String warningMessage = null;
117 * size of readahead buffer used for when initial stream position is marked.
119 final int READAHEAD_LIMIT = 2048;
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.
132 public FileParse(FileParse from) throws IOException
136 throw new Error(MessageManager
137 .getString("error.implementation_error_null_fileparse"));
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;
155 dataName = from.dataName;
159 * Attempt to open a file as a datasource. Sets error and errormessage if
160 * fileStr was invalid.
163 * @return this.error (true if the source was invalid)
165 private boolean checkFileSource(String fileStr) throws IOException
168 this.inFile = new File(fileStr);
169 // check to see if it's a Jar file in disguise.
170 if (!inFile.exists())
172 errormessage = "FILE NOT FOUND";
175 if (!inFile.canRead())
177 errormessage = "FILE CANNOT BE OPENED FOR READING";
180 if (inFile.isDirectory())
182 // this is really a 'complex' filetype - but we don't handle directory
184 errormessage = "FILE IS A DIRECTORY";
189 if (fileStr.toLowerCase().endsWith(".gz"))
193 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
196 } catch (Exception x)
198 warningMessage = "Failed to resolve as a GZ stream ("
199 + x.getMessage() + ")";
200 // x.printStackTrace();
205 dataIn = new BufferedReader(new FileReader(fileStr));
211 private BufferedReader tryAsGzipSource(InputStream inputStream)
214 BufferedReader inData = new BufferedReader(
215 new InputStreamReader(new GZIPInputStream(inputStream)));
222 private boolean checkURLSource(String fileStr)
223 throws IOException, MalformedURLException
225 errormessage = "URL NOT FOUND";
226 URL url = new URL(fileStr);
228 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
231 if (fileStr.toLowerCase().endsWith(".gz"))
235 InputStream inputStream = url.openStream();
236 dataIn = tryAsGzipSource(inputStream);
239 } catch (Exception ex)
247 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
248 } catch (IOException q)
252 throw new IOException(MessageManager
253 .getString("exception.failed_to_resolve_gzip_stream"), e);
257 // record URL as name of datasource.
263 * sets the suffix string (if any) and returns remainder (if suffix was
267 * @return truncated fileStr or null
269 private String extractSuffix(String fileStr)
271 // first check that there wasn't a suffix string tagged on.
272 int sfpos = fileStr.lastIndexOf(suffixSeparator);
273 if (sfpos > -1 && sfpos < fileStr.length() - 1)
275 suffix = fileStr.substring(sfpos + 1);
276 // System.err.println("DEBUG: Found Suffix:"+suffix);
277 return fileStr.substring(0, sfpos);
283 * not for general use, creates a fileParse object for an existing reader with
284 * configurable values for the origin and the type of the source
286 public FileParse(BufferedReader source, String originString,
287 DataSourceType sourceType)
289 dataSourceType = sourceType;
292 dataName = originString;
296 if (dataIn.markSupported())
298 dataIn.mark(READAHEAD_LIMIT);
300 } catch (IOException q)
307 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
308 * types of sources that are handled.
311 * - datasource locator/content
313 * - protocol of source
314 * @throws MalformedURLException
315 * @throws IOException
317 public FileParse(String fileStr, DataSourceType sourceType)
318 throws MalformedURLException, IOException
321 this(null, fileStr, sourceType, false);
324 public FileParse(File file, DataSourceType sourceType)
325 throws MalformedURLException, IOException
328 this(file, file.getPath(), sourceType, true);
331 private FileParse(File file, String fileStr, DataSourceType sourceType,
332 boolean isFileObject) throws MalformedURLException, IOException
338 * this.bytes = file && file._bytes;
341 this.dataSourceType = sourceType;
344 if (sourceType == DataSourceType.FILE)
349 // this will be from JavaScript
351 dataIn = new BufferedReader(new StringReader(new String(bytes)));
354 else if (checkFileSource(fileStr))
356 String suffixLess = extractSuffix(fileStr);
357 if (suffixLess != null)
359 if (checkFileSource(suffixLess))
361 throw new IOException(MessageManager.formatMessage(
362 "exception.problem_opening_file_also_tried",
364 { inFile.getName(), suffixLess, errormessage }));
369 throw new IOException(MessageManager.formatMessage(
370 "exception.problem_opening_file", new String[]
371 { inFile.getName(), errormessage }));
375 else if (sourceType == DataSourceType.RELATIVE_URL)
379 * BH 2018 hack for no support for access-origin
383 * data = $.ajax({url:fileStr, async:false}).responseText;
387 System.out.println(data);
388 dataIn = Rdr.getBR(data);
392 else if (sourceType == DataSourceType.URL)
398 checkURLSource(fileStr);
399 if (suffixSeparator == '#')
401 extractSuffix(fileStr); // URL lref is stored for later reference.
403 } catch (IOException e)
405 String suffixLess = extractSuffix(fileStr);
406 if (suffixLess == null)
414 checkURLSource(suffixLess);
415 } catch (IOException e2)
417 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
418 throw (e); // just pass back original - everything was wrong.
422 } catch (Exception e)
424 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
425 + e.getMessage() + ")";
429 else if (sourceType == DataSourceType.PASTE)
431 errormessage = "PASTE INACCESSIBLE!";
432 dataIn = new BufferedReader(new StringReader(fileStr));
435 else if (sourceType == DataSourceType.CLASSLOADER)
437 errormessage = "RESOURCE CANNOT BE LOCATED";
438 java.io.InputStream is = getClass()
439 .getResourceAsStream("/" + fileStr);
442 String suffixLess = extractSuffix(fileStr);
443 if (suffixLess != null)
445 is = getClass().getResourceAsStream("/" + suffixLess);
450 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
460 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
461 + (sourceType != null ? sourceType : "null") + "'";
464 if (dataIn == null || error)
466 // pass up the reason why we have no source to read from
467 throw new IOException(MessageManager.formatMessage(
468 "exception.failed_to_read_data_from_source",
473 dataIn.mark(READAHEAD_LIMIT);
477 * mark the current position in the source as start for the purposes of it
478 * being analysed by IdentifyFile().identify
480 * @throws IOException
482 public void mark() throws IOException
486 dataIn.mark(READAHEAD_LIMIT);
490 throw new IOException(
491 MessageManager.getString("exception.no_init_source_stream"));
495 public String nextLine() throws IOException
499 return dataIn.readLine();
501 throw new IOException(MessageManager
502 .formatMessage("exception.invalid_source_stream", new String[]
508 * @return true if this FileParse is configured for Export only
510 public boolean isExporting()
512 return !error && dataIn == null;
517 * @return true if the data source is valid
519 public boolean isValid()
525 * closes the datasource and tidies up. source will be left in an error state
527 public void close() throws IOException
529 errormessage = "EXCEPTION ON CLOSE";
533 errormessage = "SOURCE IS CLOSED";
537 * Rewinds the datasource to the marked point if possible
542 public void reset(int bytesRead) throws IOException
544 if (bytesRead >= READAHEAD_LIMIT)
546 System.err.println(String.format(
547 "File reset error: read %d bytes but reset limit is %d",
548 bytesRead, READAHEAD_LIMIT));
550 if (dataIn != null && !error)
556 throw new IOException(MessageManager.getString(
557 "error.implementation_error_reset_called_for_invalid_source"));
563 * @return true if there is a warning for the user
565 public boolean hasWarningMessage()
567 return (warningMessage != null && warningMessage.length() > 0);
572 * @return empty string or warning message about file that was just parsed.
574 public String getWarningMessage()
576 return warningMessage;
579 public String getInFile()
583 return inFile.getAbsolutePath() + " (" + index + ")";
587 return "From Paste + (" + index + ")";
592 * @return the dataName
594 public String getDataName()
600 * set the (human readable) name or URI for this datasource
604 protected void setDataName(String dataname)
610 * get the underlying bufferedReader for this data source.
612 * @return null if no reader available
613 * @throws IOException
615 public Reader getReader()
617 if (dataIn != null) // Probably don't need to test for readiness &&
625 public AlignViewportI getViewport()
630 public void setViewport(AlignViewportI viewport)
632 this.viewport = viewport;
636 * @return the currently configured exportSettings for writing data.
638 public AlignExportSettingI getExportSettings()
640 return exportSettings;
644 * Set configuration for export of data.
646 * @param exportSettings
647 * the exportSettings to set
649 public void setExportSettings(AlignExportSettingI exportSettings)
651 this.exportSettings = exportSettings;
655 * method overridden by complex file exporter/importers which support
656 * exporting visualisation and layout settings for a view
660 public void configureForView(AlignmentViewPanel avpanel)
664 setViewport(avpanel.getAlignViewport());
666 // could also set export/import settings
670 * Returns the preferred feature colour configuration if there is one, else
675 public FeatureSettingsModelI getFeatureColourScheme()
680 public DataSourceType getDataSourceType()
682 return dataSourceType;