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.BufferedReader;
24 import java.io.ByteArrayInputStream;
26 import java.io.FileInputStream;
27 import java.io.FileReader;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
31 import java.io.Reader;
32 import java.io.StringReader;
33 import java.net.MalformedURLException;
35 import java.util.zip.GZIPInputStream;
37 import jalview.api.AlignExportSettingsI;
38 import jalview.api.AlignViewportI;
39 import jalview.api.AlignmentViewPanel;
40 import jalview.api.FeatureSettingsModelI;
41 import jalview.util.MessageManager;
42 import jalview.util.Platform;
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 private byte[] bytes; // from JavaScript
63 public byte[] getBytes()
68 * a viewport associated with the current file operation. May be null. May
69 * move to different object.
71 private AlignViewportI viewport;
74 * specific settings for exporting data from the current context
76 private AlignExportSettingsI exportSettings;
79 * sequence counter for FileParse object created from same data source
84 * separator for extracting specific 'frame' of a datasource for formats that
85 * support multiple records (e.g. BLC, Stockholm, etc)
87 protected char suffixSeparator = '#';
90 * character used to write newlines
92 protected String newline = System.getProperty("line.separator");
94 public void setNewlineString(String nl)
99 public String getNewlineString()
105 * '#' separated string tagged on to end of filename or url that was clipped
106 * off to resolve to valid filename
108 protected String suffix = null;
110 protected DataSourceType dataSourceType = null;
112 protected BufferedReader dataIn = null;
114 protected String errormessage = "UNINITIALISED SOURCE";
116 protected boolean error = true;
118 protected String warningMessage = null;
121 * size of readahead buffer used for when initial stream position is marked.
123 final int READAHEAD_LIMIT = 2048;
130 * Create a new FileParse instance reading from the same datasource starting
131 * at the current position. WARNING! Subsequent reads from either object will
132 * affect the read position of the other, but not the error state.
136 public FileParse(FileParse from) throws IOException
140 throw new Error(MessageManager
141 .getString("error.implementation_error_null_fileparse"));
147 index = ++from.index;
148 inFile = from.inFile;
149 suffixSeparator = from.suffixSeparator;
150 suffix = from.suffix;
151 errormessage = from.errormessage; // inherit potential error messages
152 error = false; // reset any error condition.
153 dataSourceType = from.dataSourceType;
154 dataIn = from.dataIn;
159 dataName = from.dataName;
163 * Attempt to open a file as a datasource. Sets error and errormessage if
164 * fileStr was invalid.
167 * @return this.error (true if the source was invalid)
169 private boolean checkFileSource(String fileStr) throws IOException
172 this.inFile = new File(fileStr);
173 // check to see if it's a Jar file in disguise.
174 if (!inFile.exists())
176 errormessage = "FILE NOT FOUND";
179 if (!inFile.canRead())
181 errormessage = "FILE CANNOT BE OPENED FOR READING";
184 if (inFile.isDirectory())
186 // this is really a 'complex' filetype - but we don't handle directory
188 errormessage = "FILE IS A DIRECTORY";
193 if (fileStr.toLowerCase().endsWith(".gz"))
197 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
200 } catch (Exception x)
202 warningMessage = "Failed to resolve as a GZ stream ("
203 + x.getMessage() + ")";
204 // x.printStackTrace();
209 dataIn = new BufferedReader(new FileReader(fileStr));
215 private BufferedReader tryAsGzipSource(InputStream inputStream)
218 BufferedReader inData = new BufferedReader(
219 new InputStreamReader(new GZIPInputStream(inputStream)));
226 private boolean checkURLSource(String fileStr)
227 throws IOException, MalformedURLException
229 errormessage = "URL NOT FOUND";
230 URL url = new URL(fileStr);
232 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
235 if (fileStr.toLowerCase().endsWith(".gz"))
239 InputStream inputStream = url.openStream();
240 dataIn = tryAsGzipSource(inputStream);
243 } catch (Exception ex)
251 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
252 } catch (IOException q)
256 throw new IOException(MessageManager
257 .getString("exception.failed_to_resolve_gzip_stream"), e);
261 // record URL as name of datasource.
267 * sets the suffix string (if any) and returns remainder (if suffix was
271 * @return truncated fileStr or null
273 private String extractSuffix(String fileStr)
275 // first check that there wasn't a suffix string tagged on.
276 int sfpos = fileStr.lastIndexOf(suffixSeparator);
277 if (sfpos > -1 && sfpos < fileStr.length() - 1)
279 suffix = fileStr.substring(sfpos + 1);
280 // System.err.println("DEBUG: Found Suffix:"+suffix);
281 return fileStr.substring(0, sfpos);
287 * not for general use, creates a fileParse object for an existing reader with
288 * configurable values for the origin and the type of the source
290 public FileParse(BufferedReader source, String originString,
291 DataSourceType sourceType)
293 dataSourceType = sourceType;
296 dataName = originString;
300 if (dataIn.markSupported())
302 dataIn.mark(READAHEAD_LIMIT);
304 } catch (IOException q)
311 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
312 * types of sources that are handled.
315 * - datasource locator/content as File or String
317 * - protocol of source
318 * @throws MalformedURLException
319 * @throws IOException
321 public FileParse(Object file, DataSourceType sourceType)
322 throws MalformedURLException, IOException
324 if (file instanceof File)
326 parse((File) file, ((File) file).getPath(), sourceType, true);
330 parse(null, file.toString(), sourceType, false);
334 private void parse(File file, String fileStr, DataSourceType sourceType,
335 boolean isFileObject) throws IOException
337 bytes = Platform.getFileBytes(file);
338 dataSourceType = sourceType;
341 if (sourceType == DataSourceType.FILE)
346 // this will be from JavaScript
348 dataIn = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
351 else if (checkFileSource(fileStr))
353 String suffixLess = extractSuffix(fileStr);
354 if (suffixLess != null)
356 if (checkFileSource(suffixLess))
358 throw new IOException(MessageManager.formatMessage(
359 "exception.problem_opening_file_also_tried",
361 { inFile.getName(), suffixLess, errormessage }));
366 throw new IOException(MessageManager.formatMessage(
367 "exception.problem_opening_file", new String[]
368 { inFile.getName(), errormessage }));
372 else if (sourceType == DataSourceType.RELATIVE_URL)
374 // BH 2018 hack for no support for access-origin
375 bytes = Platform.getFileAsBytes(fileStr);
376 dataIn = new BufferedReader(
377 new InputStreamReader(new ByteArrayInputStream(bytes)));
381 else if (sourceType == DataSourceType.URL)
387 checkURLSource(fileStr);
388 if (suffixSeparator == '#')
390 extractSuffix(fileStr); // URL lref is stored for later reference.
392 } catch (IOException e)
394 String suffixLess = extractSuffix(fileStr);
395 if (suffixLess == null)
403 checkURLSource(suffixLess);
404 } catch (IOException e2)
406 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
407 throw (e); // just pass back original - everything was wrong.
411 } catch (Exception e)
413 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
414 + e.getMessage() + ")";
418 else if (sourceType == DataSourceType.PASTE)
420 errormessage = "PASTE INACCESSIBLE!";
421 dataIn = new BufferedReader(new StringReader(fileStr));
424 else if (sourceType == DataSourceType.CLASSLOADER)
426 errormessage = "RESOURCE CANNOT BE LOCATED";
427 InputStream is = getClass().getResourceAsStream("/" + fileStr);
430 String suffixLess = extractSuffix(fileStr);
431 if (suffixLess != null)
433 is = getClass().getResourceAsStream("/" + suffixLess);
438 dataIn = new BufferedReader(new InputStreamReader(is));
448 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
449 + (sourceType != null ? sourceType : "null") + "'";
452 if (dataIn == null || error)
454 // pass up the reason why we have no source to read from
455 throw new IOException(MessageManager.formatMessage(
456 "exception.failed_to_read_data_from_source",
461 dataIn.mark(READAHEAD_LIMIT);
465 * mark the current position in the source as start for the purposes of it
466 * being analysed by IdentifyFile().identify
468 * @throws IOException
470 public void mark() throws IOException
474 dataIn.mark(READAHEAD_LIMIT);
478 throw new IOException(
479 MessageManager.getString("exception.no_init_source_stream"));
483 public String nextLine() throws IOException
487 return dataIn.readLine();
489 throw new IOException(MessageManager
490 .formatMessage("exception.invalid_source_stream", new String[]
496 * @return true if this FileParse is configured for Export only
498 public boolean isExporting()
500 return !error && dataIn == null;
505 * @return true if the data source is valid
507 public boolean isValid()
513 * closes the datasource and tidies up. source will be left in an error state
515 public void close() throws IOException
517 errormessage = "EXCEPTION ON CLOSE";
521 errormessage = "SOURCE IS CLOSED";
525 * Rewinds the datasource to the marked point if possible
530 public void reset(int bytesRead) throws IOException
532 if (bytesRead >= READAHEAD_LIMIT)
534 System.err.println(String.format(
535 "File reset error: read %d bytes but reset limit is %d",
536 bytesRead, READAHEAD_LIMIT));
538 if (dataIn != null && !error)
544 throw new IOException(MessageManager.getString(
545 "error.implementation_error_reset_called_for_invalid_source"));
551 * @return true if there is a warning for the user
553 public boolean hasWarningMessage()
555 return (warningMessage != null && warningMessage.length() > 0);
560 * @return empty string or warning message about file that was just parsed.
562 public String getWarningMessage()
564 return warningMessage;
567 public String getInFile()
571 return inFile.getAbsolutePath() + " (" + index + ")";
575 return "From Paste + (" + index + ")";
580 * @return the dataName
582 public String getDataName()
588 * set the (human readable) name or URI for this datasource
592 protected void setDataName(String dataname)
598 * get the underlying bufferedReader for this data source.
600 * @return null if no reader available
601 * @throws IOException
603 public Reader getReader()
605 if (dataIn != null) // Probably don't need to test for readiness &&
613 public AlignViewportI getViewport()
618 public void setViewport(AlignViewportI viewport)
620 this.viewport = viewport;
624 * @return the currently configured exportSettings for writing data.
626 public AlignExportSettingsI getExportSettings()
628 return exportSettings;
632 * Set configuration for export of data.
634 * @param exportSettings
635 * the exportSettings to set
637 public void setExportSettings(AlignExportSettingsI exportSettings)
639 this.exportSettings = exportSettings;
643 * method overridden by complex file exporter/importers which support
644 * exporting visualisation and layout settings for a view
648 public void configureForView(AlignmentViewPanel avpanel)
652 setViewport(avpanel.getAlignViewport());
654 // could also set export/import settings
658 * Returns the preferred feature colour configuration if there is one, else
663 public FeatureSettingsModelI getFeatureColourScheme()
668 public DataSourceType getDataSourceType()
670 return dataSourceType;
674 * Returns a buffered reader for the input object. Returns null, or throws
675 * IOException, on failure.
678 * a File, or a String which is a name of a file
681 * @throws IOException
683 public BufferedReader getBufferedReader(Object file,
684 DataSourceType sourceType) throws IOException
686 BufferedReader in = null;
692 if (file instanceof String)
694 return new BufferedReader(new FileReader((String) file));
696 bytes = Platform.getFileBytes((File) file);
699 return new BufferedReader(
700 new InputStreamReader(new ByteArrayInputStream(bytes)));
702 return new BufferedReader(new FileReader((File) file));
704 URL url = new URL(file.toString());
705 in = new BufferedReader(new InputStreamReader(url.openStream()));
707 case RELATIVE_URL: // JalviewJS only
708 bytes = Platform.getFileAsBytes(file.toString());
711 in = new BufferedReader(
712 new InputStreamReader(new ByteArrayInputStream(bytes)));
716 in = new BufferedReader(new StringReader(file.toString()));
719 InputStream is = getClass().getResourceAsStream("/" + file);
722 in = new BufferedReader(new InputStreamReader(is));