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;
43 * implements a random access wrapper around a particular datasource, for
44 * passing to identifyFile and AlignFile objects.
46 public class FileParse
49 * text specifying source of data. usually filename or url.
51 private String dataName = "unknown source";
53 public File inFile = null;
56 * a viewport associated with the current file operation. May be null. May
57 * move to different object.
59 private AlignViewportI viewport;
62 * specific settings for exporting data from the current context
64 private AlignExportSettingI exportSettings;
67 * sequence counter for FileParse object created from same data source
72 * separator for extracting specific 'frame' of a datasource for formats that
73 * support multiple records (e.g. BLC, Stockholm, etc)
75 protected char suffixSeparator = '#';
78 * character used to write newlines
80 protected String newline = System.getProperty("line.separator");
82 public void setNewlineString(String nl)
87 public String getNewlineString()
93 * '#' separated string tagged on to end of filename or url that was clipped
94 * off to resolve to valid filename
96 protected String suffix = null;
98 protected DataSourceType dataSourceType = null;
100 protected BufferedReader dataIn = null;
102 protected String errormessage = "UNINITIALISED SOURCE";
104 protected boolean error = true;
106 protected String warningMessage = null;
109 * size of readahead buffer used for when initial stream position is marked.
111 final int READAHEAD_LIMIT = 2048;
118 * Create a new FileParse instance reading from the same datasource starting
119 * at the current position. WARNING! Subsequent reads from either object will
120 * affect the read position of the other, but not the error state.
124 public FileParse(FileParse from) throws IOException
130 .getString("error.implementation_error_null_fileparse"));
136 index = ++from.index;
137 inFile = from.inFile;
138 suffixSeparator = from.suffixSeparator;
139 suffix = from.suffix;
140 errormessage = from.errormessage; // inherit potential error messages
141 error = false; // reset any error condition.
142 dataSourceType = from.dataSourceType;
143 dataIn = from.dataIn;
148 dataName = from.dataName;
152 * Attempt to open a file as a datasource. Sets error and errormessage if
153 * fileStr was invalid.
156 * @return this.error (true if the source was invalid)
158 private boolean checkFileSource(String fileStr) throws IOException
161 this.inFile = new File(fileStr);
162 // check to see if it's a Jar file in disguise.
163 if (!inFile.exists())
165 errormessage = "FILE NOT FOUND";
168 if (!inFile.canRead())
170 errormessage = "FILE CANNOT BE OPENED FOR READING";
173 if (inFile.isDirectory())
175 // this is really a 'complex' filetype - but we don't handle directory
177 errormessage = "FILE IS A DIRECTORY";
182 if (fileStr.toLowerCase().endsWith(".gz"))
186 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
189 } catch (Exception x)
191 warningMessage = "Failed to resolve as a GZ stream ("
192 + x.getMessage() + ")";
193 // x.printStackTrace();
198 dataIn = new BufferedReader(new FileReader(fileStr));
204 private BufferedReader tryAsGzipSource(InputStream inputStream)
207 BufferedReader inData = new BufferedReader(new InputStreamReader(
208 new GZIPInputStream(inputStream)));
215 private boolean checkURLSource(String fileStr) throws IOException,
216 MalformedURLException
218 errormessage = "URL NOT FOUND";
219 URL url = new URL(fileStr);
221 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
224 if (fileStr.toLowerCase().endsWith(".gz"))
228 InputStream inputStream = url.openStream();
229 dataIn = tryAsGzipSource(inputStream);
232 } catch (Exception ex)
240 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
241 } catch (IOException q)
245 throw new IOException(
247 .getString("exception.failed_to_resolve_gzip_stream"),
252 // record URL as name of datasource.
258 * sets the suffix string (if any) and returns remainder (if suffix was
262 * @return truncated fileStr or null
264 private String extractSuffix(String fileStr)
266 // first check that there wasn't a suffix string tagged on.
267 int sfpos = fileStr.lastIndexOf(suffixSeparator);
268 if (sfpos > -1 && sfpos < fileStr.length() - 1)
270 suffix = fileStr.substring(sfpos + 1);
271 // System.err.println("DEBUG: Found Suffix:"+suffix);
272 return fileStr.substring(0, sfpos);
278 * not for general use, creates a fileParse object for an existing reader with
279 * configurable values for the origin and the type of the source
281 public FileParse(BufferedReader source, String originString,
282 DataSourceType sourceType)
284 dataSourceType = sourceType;
287 dataName = originString;
291 if (dataIn.markSupported())
293 dataIn.mark(READAHEAD_LIMIT);
295 } catch (IOException q)
302 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
303 * types of sources that are handled.
306 * - datasource locator/content
308 * - protocol of source
309 * @throws MalformedURLException
310 * @throws IOException
312 public FileParse(String fileStr, DataSourceType sourceType)
313 throws MalformedURLException, IOException
315 this.dataSourceType = sourceType;
318 if (sourceType == DataSourceType.FILE)
320 if (checkFileSource(fileStr))
322 String suffixLess = extractSuffix(fileStr);
323 if (suffixLess != null)
325 if (checkFileSource(suffixLess))
327 throw new IOException(MessageManager.formatMessage(
328 "exception.problem_opening_file_also_tried",
329 new String[] { inFile.getName(), suffixLess,
335 throw new IOException(MessageManager.formatMessage(
336 "exception.problem_opening_file",
337 new String[] { inFile.getName(), errormessage }));
341 else if (sourceType == DataSourceType.URL)
347 checkURLSource(fileStr);
348 if (suffixSeparator == '#')
350 extractSuffix(fileStr); // URL lref is stored for later reference.
352 } catch (IOException e)
354 String suffixLess = extractSuffix(fileStr);
355 if (suffixLess == null)
363 checkURLSource(suffixLess);
364 } catch (IOException e2)
366 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
367 throw (e); // just pass back original - everything was wrong.
371 } catch (Exception e)
373 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
374 + e.getMessage() + ")";
378 else if (sourceType == DataSourceType.PASTE)
380 errormessage = "PASTE INACCESSIBLE!";
381 dataIn = new BufferedReader(new StringReader(fileStr));
384 else if (sourceType == DataSourceType.CLASSLOADER)
386 errormessage = "RESOURCE CANNOT BE LOCATED";
387 java.io.InputStream is = getClass()
388 .getResourceAsStream("/" + fileStr);
391 String suffixLess = extractSuffix(fileStr);
392 if (suffixLess != null)
394 is = getClass().getResourceAsStream("/" + suffixLess);
399 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
409 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
410 + (sourceType != null ? sourceType : "null") + "'";
413 if (dataIn == null || error)
415 // pass up the reason why we have no source to read from
416 throw new IOException(MessageManager.formatMessage(
417 "exception.failed_to_read_data_from_source",
418 new String[] { errormessage }));
421 dataIn.mark(READAHEAD_LIMIT);
425 * mark the current position in the source as start for the purposes of it
426 * being analysed by IdentifyFile().identify
428 * @throws IOException
430 public void mark() throws IOException
434 dataIn.mark(READAHEAD_LIMIT);
438 throw new IOException(
439 MessageManager.getString("exception.no_init_source_stream"));
443 public String nextLine() throws IOException
447 return dataIn.readLine();
449 throw new IOException(MessageManager.formatMessage(
450 "exception.invalid_source_stream",
451 new String[] { errormessage }));
456 * @return true if this FileParse is configured for Export only
458 public boolean isExporting()
460 return !error && dataIn == null;
465 * @return true if the data source is valid
467 public boolean isValid()
473 * closes the datasource and tidies up. source will be left in an error state
475 public void close() throws IOException
477 errormessage = "EXCEPTION ON CLOSE";
481 errormessage = "SOURCE IS CLOSED";
485 * Rewinds the datasource to the marked point if possible
490 public void reset(int bytesRead) throws IOException
492 if (bytesRead >= READAHEAD_LIMIT)
494 System.err.println(String.format(
495 "File reset error: read %d bytes but reset limit is %d",
496 bytesRead, READAHEAD_LIMIT));
498 if (dataIn != null && !error)
504 throw new IOException(
506 .getString("error.implementation_error_reset_called_for_invalid_source"));
512 * @return true if there is a warning for the user
514 public boolean hasWarningMessage()
516 return (warningMessage != null && warningMessage.length() > 0);
521 * @return empty string or warning message about file that was just parsed.
523 public String getWarningMessage()
525 return warningMessage;
528 public String getInFile()
532 return inFile.getAbsolutePath() + " (" + index + ")";
536 return "From Paste + (" + index + ")";
541 * @return the dataName
543 public String getDataName()
549 * set the (human readable) name or URI for this datasource
553 protected void setDataName(String dataname)
559 * get the underlying bufferedReader for this data source.
561 * @return null if no reader available
562 * @throws IOException
564 public Reader getReader()
566 if (dataIn != null) // Probably don't need to test for readiness &&
574 public AlignViewportI getViewport()
579 public void setViewport(AlignViewportI viewport)
581 this.viewport = viewport;
585 * @return the currently configured exportSettings for writing data.
587 public AlignExportSettingI getExportSettings()
589 return exportSettings;
593 * Set configuration for export of data.
595 * @param exportSettings
596 * the exportSettings to set
598 public void setExportSettings(AlignExportSettingI exportSettings)
600 this.exportSettings = exportSettings;
604 * method overridden by complex file exporter/importers which support
605 * exporting visualisation and layout settings for a view
609 public void configureForView(AlignmentViewPanel avpanel)
613 setViewport(avpanel.getAlignViewport());
615 // could also set export/import settings
619 * Returns the preferred feature colour configuration if there is one, else
624 public FeatureSettingsModelI getFeatureColourScheme()
629 public DataSourceType getDataSourceType()
631 return dataSourceType;