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
128 throw new Error(MessageManager
129 .getString("error.implementation_error_null_fileparse"));
135 index = ++from.index;
136 inFile = from.inFile;
137 suffixSeparator = from.suffixSeparator;
138 suffix = from.suffix;
139 errormessage = from.errormessage; // inherit potential error messages
140 error = false; // reset any error condition.
141 dataSourceType = from.dataSourceType;
142 dataIn = from.dataIn;
147 dataName = from.dataName;
151 * Attempt to open a file as a datasource. Sets error and errormessage if
152 * fileStr was invalid.
155 * @return this.error (true if the source was invalid)
157 private boolean checkFileSource(String fileStr) throws IOException
160 this.inFile = new File(fileStr);
161 // check to see if it's a Jar file in disguise.
162 if (!inFile.exists())
164 errormessage = "FILE NOT FOUND";
167 if (!inFile.canRead())
169 errormessage = "FILE CANNOT BE OPENED FOR READING";
172 if (inFile.isDirectory())
174 // this is really a 'complex' filetype - but we don't handle directory
176 errormessage = "FILE IS A DIRECTORY";
181 if (fileStr.toLowerCase().endsWith(".gz"))
185 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
188 } catch (Exception x)
190 warningMessage = "Failed to resolve as a GZ stream ("
191 + x.getMessage() + ")";
192 // x.printStackTrace();
197 dataIn = new BufferedReader(new FileReader(fileStr));
203 private BufferedReader tryAsGzipSource(InputStream inputStream)
206 BufferedReader inData = new BufferedReader(
207 new InputStreamReader(new GZIPInputStream(inputStream)));
214 private boolean checkURLSource(String fileStr)
215 throws IOException, MalformedURLException
217 errormessage = "URL NOT FOUND";
218 URL url = new URL(fileStr);
220 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
223 if (fileStr.toLowerCase().endsWith(".gz"))
227 InputStream inputStream = url.openStream();
228 dataIn = tryAsGzipSource(inputStream);
231 } catch (Exception ex)
239 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
240 } catch (IOException q)
244 throw new IOException(MessageManager
245 .getString("exception.failed_to_resolve_gzip_stream"), e);
249 // record URL as name of datasource.
255 * sets the suffix string (if any) and returns remainder (if suffix was
259 * @return truncated fileStr or null
261 private String extractSuffix(String fileStr)
263 // first check that there wasn't a suffix string tagged on.
264 int sfpos = fileStr.lastIndexOf(suffixSeparator);
265 if (sfpos > -1 && sfpos < fileStr.length() - 1)
267 suffix = fileStr.substring(sfpos + 1);
268 // System.err.println("DEBUG: Found Suffix:"+suffix);
269 return fileStr.substring(0, sfpos);
275 * not for general use, creates a fileParse object for an existing reader with
276 * configurable values for the origin and the type of the source
278 public FileParse(BufferedReader source, String originString,
279 DataSourceType sourceType)
281 dataSourceType = sourceType;
284 dataName = originString;
288 if (dataIn.markSupported())
290 dataIn.mark(READAHEAD_LIMIT);
292 } catch (IOException q)
299 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
300 * types of sources that are handled.
303 * - datasource locator/content
305 * - protocol of source
306 * @throws MalformedURLException
307 * @throws IOException
309 public FileParse(String fileStr, DataSourceType sourceType)
310 throws MalformedURLException, IOException
312 this.dataSourceType = sourceType;
315 if (sourceType == DataSourceType.FILE)
317 if (checkFileSource(fileStr))
319 String suffixLess = extractSuffix(fileStr);
320 if (suffixLess != null)
322 if (checkFileSource(suffixLess))
324 throw new IOException(MessageManager.formatMessage(
325 "exception.problem_opening_file_also_tried",
327 { inFile.getName(), suffixLess, errormessage }));
332 throw new IOException(MessageManager.formatMessage(
333 "exception.problem_opening_file", new String[]
334 { inFile.getName(), errormessage }));
338 else if (sourceType == DataSourceType.URL)
344 checkURLSource(fileStr);
345 if (suffixSeparator == '#')
347 extractSuffix(fileStr); // URL lref is stored for later reference.
349 } catch (IOException e)
351 String suffixLess = extractSuffix(fileStr);
352 if (suffixLess == null)
360 checkURLSource(suffixLess);
361 } catch (IOException e2)
363 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
364 throw (e); // just pass back original - everything was wrong.
368 } catch (Exception e)
370 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
371 + e.getMessage() + ")";
375 else if (sourceType == DataSourceType.PASTE)
377 errormessage = "PASTE INACCESSIBLE!";
378 dataIn = new BufferedReader(new StringReader(fileStr));
381 else if (sourceType == DataSourceType.CLASSLOADER)
383 errormessage = "RESOURCE CANNOT BE LOCATED";
384 java.io.InputStream is = getClass()
385 .getResourceAsStream("/" + fileStr);
388 String suffixLess = extractSuffix(fileStr);
389 if (suffixLess != null)
391 is = getClass().getResourceAsStream("/" + suffixLess);
396 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
406 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
407 + (sourceType != null ? sourceType : "null") + "'";
410 if (dataIn == null || error)
412 // pass up the reason why we have no source to read from
413 throw new IOException(MessageManager.formatMessage(
414 "exception.failed_to_read_data_from_source", new String[]
418 dataIn.mark(READAHEAD_LIMIT);
422 * mark the current position in the source as start for the purposes of it
423 * being analysed by IdentifyFile().identify
425 * @throws IOException
427 public void mark() throws IOException
431 dataIn.mark(READAHEAD_LIMIT);
435 throw new IOException(
436 MessageManager.getString("exception.no_init_source_stream"));
440 public String nextLine() throws IOException
444 return dataIn.readLine();
446 throw new IOException(MessageManager
447 .formatMessage("exception.invalid_source_stream", new String[]
453 * @return true if this FileParse is configured for Export only
455 public boolean isExporting()
457 return !error && dataIn == null;
462 * @return true if the data source is valid
464 public boolean isValid()
470 * closes the datasource and tidies up. source will be left in an error state
472 public void close() throws IOException
474 errormessage = "EXCEPTION ON CLOSE";
478 errormessage = "SOURCE IS CLOSED";
482 * Rewinds the datasource to the marked point if possible
487 public void reset(int bytesRead) throws IOException
489 if (bytesRead >= READAHEAD_LIMIT)
491 System.err.println(String.format(
492 "File reset error: read %d bytes but reset limit is %d",
493 bytesRead, READAHEAD_LIMIT));
495 if (dataIn != null && !error)
501 throw new IOException(MessageManager.getString(
502 "error.implementation_error_reset_called_for_invalid_source"));
508 * @return true if there is a warning for the user
510 public boolean hasWarningMessage()
512 return (warningMessage != null && warningMessage.length() > 0);
517 * @return empty string or warning message about file that was just parsed.
519 public String getWarningMessage()
521 return warningMessage;
524 public String getInFile()
528 return inFile.getAbsolutePath() + " (" + index + ")";
532 return "From Paste + (" + index + ")";
537 * @return the dataName
539 public String getDataName()
545 * set the (human readable) name or URI for this datasource
549 protected void setDataName(String dataname)
555 * get the underlying bufferedReader for this data source.
557 * @return null if no reader available
558 * @throws IOException
560 public Reader getReader()
562 if (dataIn != null) // Probably don't need to test for readiness &&
570 public AlignViewportI getViewport()
575 public void setViewport(AlignViewportI viewport)
577 this.viewport = viewport;
581 * @return the currently configured exportSettings for writing data.
583 public AlignExportSettingI getExportSettings()
585 return exportSettings;
589 * Set configuration for export of data.
591 * @param exportSettings
592 * the exportSettings to set
594 public void setExportSettings(AlignExportSettingI exportSettings)
596 this.exportSettings = exportSettings;
600 * method overridden by complex file exporter/importers which support
601 * exporting visualisation and layout settings for a view
605 public void configureForView(AlignmentViewPanel avpanel)
609 setViewport(avpanel.getAlignViewport());
611 // could also set export/import settings
615 * Returns the preferred feature colour configuration if there is one, else
620 public FeatureSettingsModelI getFeatureColourScheme()
625 public DataSourceType getDataSourceType()
627 return dataSourceType;