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
48 protected static final String SPACE = " ";
50 protected static final String TAB = "\t";
53 * text specifying source of data. usually filename or url.
55 private String dataName = "unknown source";
57 public File inFile = null;
60 * a viewport associated with the current file operation. May be null. May
61 * move to different object.
63 private AlignViewportI viewport;
66 * specific settings for exporting data from the current context
68 private AlignExportSettingI exportSettings;
71 * sequence counter for FileParse object created from same data source
76 * separator for extracting specific 'frame' of a datasource for formats that
77 * support multiple records (e.g. BLC, Stockholm, etc)
79 protected char suffixSeparator = '#';
82 * character used to write newlines
84 protected String newline = System.getProperty("line.separator");
86 public void setNewlineString(String nl)
91 public String getNewlineString()
97 * '#' separated string tagged on to end of filename or url that was clipped
98 * off to resolve to valid filename
100 protected String suffix = null;
102 protected DataSourceType dataSourceType = null;
104 protected BufferedReader dataIn = null;
106 protected String errormessage = "UNINITIALISED SOURCE";
108 protected boolean error = true;
110 protected String warningMessage = null;
113 * size of readahead buffer used for when initial stream position is marked.
115 final int READAHEAD_LIMIT = 2048;
122 * Create a new FileParse instance reading from the same datasource starting
123 * at the current position. WARNING! Subsequent reads from either object will
124 * affect the read position of the other, but not the error state.
128 public FileParse(FileParse from) throws IOException
132 throw new Error(MessageManager
133 .getString("error.implementation_error_null_fileparse"));
139 index = ++from.index;
140 inFile = from.inFile;
141 suffixSeparator = from.suffixSeparator;
142 suffix = from.suffix;
143 errormessage = from.errormessage; // inherit potential error messages
144 error = false; // reset any error condition.
145 dataSourceType = from.dataSourceType;
146 dataIn = from.dataIn;
151 dataName = from.dataName;
155 * Attempt to open a file as a datasource. Sets error and errormessage if
156 * fileStr was invalid.
159 * @return this.error (true if the source was invalid)
161 private boolean checkFileSource(String fileStr) throws IOException
164 this.inFile = new File(fileStr);
165 // check to see if it's a Jar file in disguise.
166 if (!inFile.exists())
168 errormessage = "FILE NOT FOUND";
171 if (!inFile.canRead())
173 errormessage = "FILE CANNOT BE OPENED FOR READING";
176 if (inFile.isDirectory())
178 // this is really a 'complex' filetype - but we don't handle directory
180 errormessage = "FILE IS A DIRECTORY";
185 if (fileStr.toLowerCase().endsWith(".gz"))
189 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
192 } catch (Exception x)
194 warningMessage = "Failed to resolve as a GZ stream ("
195 + x.getMessage() + ")";
196 // x.printStackTrace();
201 dataIn = new BufferedReader(new FileReader(fileStr));
207 private BufferedReader tryAsGzipSource(InputStream inputStream)
210 BufferedReader inData = new BufferedReader(
211 new InputStreamReader(new GZIPInputStream(inputStream)));
218 private boolean checkURLSource(String fileStr)
219 throws IOException, MalformedURLException
221 errormessage = "URL NOT FOUND";
222 URL url = new URL(fileStr);
224 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
227 if (fileStr.toLowerCase().endsWith(".gz"))
231 InputStream inputStream = url.openStream();
232 dataIn = tryAsGzipSource(inputStream);
235 } catch (Exception ex)
243 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
244 } catch (IOException q)
248 throw new IOException(MessageManager
249 .getString("exception.failed_to_resolve_gzip_stream"), e);
253 // record URL as name of datasource.
259 * sets the suffix string (if any) and returns remainder (if suffix was
263 * @return truncated fileStr or null
265 private String extractSuffix(String fileStr)
267 // first check that there wasn't a suffix string tagged on.
268 int sfpos = fileStr.lastIndexOf(suffixSeparator);
269 if (sfpos > -1 && sfpos < fileStr.length() - 1)
271 suffix = fileStr.substring(sfpos + 1);
272 // System.err.println("DEBUG: Found Suffix:"+suffix);
273 return fileStr.substring(0, sfpos);
279 * not for general use, creates a fileParse object for an existing reader with
280 * configurable values for the origin and the type of the source
282 public FileParse(BufferedReader source, String originString,
283 DataSourceType sourceType)
285 dataSourceType = sourceType;
288 dataName = originString;
292 if (dataIn.markSupported())
294 dataIn.mark(READAHEAD_LIMIT);
296 } catch (IOException q)
303 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
304 * types of sources that are handled.
307 * - datasource locator/content
309 * - protocol of source
310 * @throws MalformedURLException
311 * @throws IOException
313 public FileParse(String fileStr, DataSourceType sourceType)
314 throws MalformedURLException, IOException
316 this.dataSourceType = sourceType;
319 if (sourceType == DataSourceType.FILE)
321 if (checkFileSource(fileStr))
323 String suffixLess = extractSuffix(fileStr);
324 if (suffixLess != null)
326 if (checkFileSource(suffixLess))
328 throw new IOException(MessageManager.formatMessage(
329 "exception.problem_opening_file_also_tried",
331 { inFile.getName(), suffixLess, errormessage }));
336 throw new IOException(MessageManager.formatMessage(
337 "exception.problem_opening_file", new String[]
338 { inFile.getName(), errormessage }));
342 else if (sourceType == DataSourceType.URL)
348 checkURLSource(fileStr);
349 if (suffixSeparator == '#')
351 extractSuffix(fileStr); // URL lref is stored for later reference.
353 } catch (IOException e)
355 String suffixLess = extractSuffix(fileStr);
356 if (suffixLess == null)
364 checkURLSource(suffixLess);
365 } catch (IOException e2)
367 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
368 throw (e); // just pass back original - everything was wrong.
372 } catch (Exception e)
374 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
375 + e.getMessage() + ")";
379 else if (sourceType == DataSourceType.PASTE)
381 errormessage = "PASTE INACCESSIBLE!";
382 dataIn = new BufferedReader(new StringReader(fileStr));
385 else if (sourceType == DataSourceType.CLASSLOADER)
387 errormessage = "RESOURCE CANNOT BE LOCATED";
388 java.io.InputStream is = getClass()
389 .getResourceAsStream("/" + fileStr);
392 String suffixLess = extractSuffix(fileStr);
393 if (suffixLess != null)
395 is = getClass().getResourceAsStream("/" + suffixLess);
400 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
410 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
411 + (sourceType != null ? sourceType : "null") + "'";
414 if (dataIn == null || error)
416 // pass up the reason why we have no source to read from
417 throw new IOException(MessageManager.formatMessage(
418 "exception.failed_to_read_data_from_source", new String[]
422 dataIn.mark(READAHEAD_LIMIT);
426 * mark the current position in the source as start for the purposes of it
427 * being analysed by IdentifyFile().identify
429 * @throws IOException
431 public void mark() throws IOException
435 dataIn.mark(READAHEAD_LIMIT);
439 throw new IOException(
440 MessageManager.getString("exception.no_init_source_stream"));
444 public String nextLine() throws IOException
448 return dataIn.readLine();
450 throw new IOException(MessageManager
451 .formatMessage("exception.invalid_source_stream", new String[]
457 * @return true if this FileParse is configured for Export only
459 public boolean isExporting()
461 return !error && dataIn == null;
466 * @return true if the data source is valid
468 public boolean isValid()
474 * closes the datasource and tidies up. source will be left in an error state
476 public void close() throws IOException
478 errormessage = "EXCEPTION ON CLOSE";
482 errormessage = "SOURCE IS CLOSED";
486 * Rewinds the datasource to the marked point if possible
491 public void reset(int bytesRead) throws IOException
493 if (bytesRead >= READAHEAD_LIMIT)
495 System.err.println(String.format(
496 "File reset error: read %d bytes but reset limit is %d",
497 bytesRead, READAHEAD_LIMIT));
499 if (dataIn != null && !error)
505 throw new IOException(MessageManager.getString(
506 "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;