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.util.MessageManager;
27 import java.io.BufferedReader;
29 import java.io.FileInputStream;
30 import java.io.FileReader;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.InputStreamReader;
34 import java.io.Reader;
35 import java.io.StringReader;
36 import java.net.MalformedURLException;
38 import java.util.zip.GZIPInputStream;
41 * implements a random access wrapper around a particular datasource, for
42 * passing to identifyFile and AlignFile objects.
44 public class FileParse
47 * text specifying source of data. usually filename or url.
49 private String dataName = "unknown source";
51 public File inFile = null;
53 private AlignViewportI viewport;
55 public int index = 1; // sequence counter for FileParse object created from
57 * specific settings for exporting data from the current context
59 private AlignExportSettingI exportSettings;
63 protected char suffixSeparator = '#';
66 * character used to write newlines
68 protected String newline = System.getProperty("line.separator");
70 public void setNewlineString(String nl)
75 public String getNewlineString()
81 * '#' separated string tagged on to end of filename or url that was clipped
82 * off to resolve to valid filename
84 protected String suffix = null;
86 protected String type = null;
88 protected BufferedReader dataIn = null;
90 protected String errormessage = "UNITIALISED SOURCE";
92 protected boolean error = true;
94 protected String warningMessage = null;
97 * size of readahead buffer used for when initial stream position is marked.
99 final int READAHEAD_LIMIT = 2048;
106 * Create a new FileParse instance reading from the same datasource starting
107 * at the current position. WARNING! Subsequent reads from either object will
108 * affect the read position of the other, but not the error state.
112 public FileParse(FileParse from) throws IOException
116 throw new Error(MessageManager.getString("error.implementation_error_null_fileparse"));
122 index = ++from.index;
123 inFile = from.inFile;
124 suffixSeparator = from.suffixSeparator;
125 suffix = from.suffix;
126 errormessage = from.errormessage; // inherit potential error messages
127 error = false; // reset any error condition.
129 dataIn = from.dataIn;
134 dataName = from.dataName;
138 * Attempt to open a file as a datasource. Sets error and errormessage if
139 * fileStr was invalid.
142 * @return this.error (true if the source was invalid)
144 private boolean checkFileSource(String fileStr) throws IOException
147 this.inFile = new File(fileStr);
148 // check to see if it's a Jar file in disguise.
149 if (!inFile.exists())
151 errormessage = "FILE NOT FOUND";
154 if (!inFile.canRead())
156 errormessage = "FILE CANNOT BE OPENED FOR READING";
159 if (inFile.isDirectory())
161 // this is really a 'complex' filetype - but we don't handle directory
163 errormessage = "FILE IS A DIRECTORY";
168 if (fileStr.toLowerCase().endsWith(".gz"))
172 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
175 } catch (Exception x)
177 warningMessage = "Failed to resolve as a GZ stream ("
178 + x.getMessage() + ")";
179 // x.printStackTrace();
184 dataIn = new BufferedReader(new FileReader(fileStr));
190 private BufferedReader tryAsGzipSource(InputStream inputStream)
193 BufferedReader inData = new BufferedReader(new InputStreamReader(
194 new GZIPInputStream(inputStream)));
201 private boolean checkURLSource(String fileStr) throws IOException,
202 MalformedURLException
204 errormessage = "URL NOT FOUND";
205 URL url = new URL(fileStr);
207 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
210 if (fileStr.toLowerCase().endsWith(".gz"))
214 InputStream inputStream = url.openStream();
215 dataIn = tryAsGzipSource(inputStream);
218 } catch (Exception ex)
226 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
227 } catch (IOException q)
231 throw new IOException(MessageManager.getString("exception.failed_to_resolve_gzip_stream"), e);
235 // record URL as name of datasource.
241 * sets the suffix string (if any) and returns remainder (if suffix was
245 * @return truncated fileStr or null
247 private String extractSuffix(String fileStr)
249 // first check that there wasn't a suffix string tagged on.
250 int sfpos = fileStr.lastIndexOf(suffixSeparator);
251 if (sfpos > -1 && sfpos < fileStr.length() - 1)
253 suffix = fileStr.substring(sfpos + 1);
254 // System.err.println("DEBUG: Found Suffix:"+suffix);
255 return fileStr.substring(0, sfpos);
261 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
262 * types of sources that are handled.
265 * - datasource locator/content
267 * - protocol of source
268 * @throws MalformedURLException
269 * @throws IOException
271 public FileParse(String fileStr, String type)
272 throws MalformedURLException, IOException
277 if (type.equals(AppletFormatAdapter.FILE))
279 if (checkFileSource(fileStr))
281 String suffixLess = extractSuffix(fileStr);
282 if (suffixLess != null)
284 if (checkFileSource(suffixLess))
286 throw new IOException(MessageManager.formatMessage("exception.problem_opening_file_also_tried", new String[]{inFile.getName(),suffixLess,errormessage}));
291 throw new IOException(MessageManager.formatMessage("exception.problem_opening_file", new String[]{inFile.getName(),errormessage}));
295 else if (type.equals(AppletFormatAdapter.URL))
301 checkURLSource(fileStr);
302 if (suffixSeparator == '#')
304 extractSuffix(fileStr); // URL lref is stored for later reference.
306 } catch (IOException e)
308 String suffixLess = extractSuffix(fileStr);
309 if (suffixLess == null)
317 checkURLSource(suffixLess);
318 } catch (IOException e2)
320 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
321 throw (e); // just pass back original - everything was wrong.
325 } catch (Exception e)
327 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
328 + e.getMessage() + ")";
332 else if (type.equals(AppletFormatAdapter.PASTE))
334 errormessage = "PASTE INACCESSIBLE!";
335 dataIn = new BufferedReader(new StringReader(fileStr));
338 else if (type.equals(AppletFormatAdapter.CLASSLOADER))
340 errormessage = "RESOURCE CANNOT BE LOCATED";
341 java.io.InputStream is = getClass()
342 .getResourceAsStream("/" + fileStr);
345 String suffixLess = extractSuffix(fileStr);
346 if (suffixLess != null)
348 is = getClass().getResourceAsStream("/" + suffixLess);
353 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
363 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
364 + (type != null ? type : "null") + "'";
367 if (dataIn == null || error)
369 // pass up the reason why we have no source to read from
370 throw new IOException(MessageManager.formatMessage("exception.failed_to_read_data_from_source", new String[]{errormessage}));
373 dataIn.mark(READAHEAD_LIMIT);
377 * mark the current position in the source as start for the purposes of it
378 * being analysed by IdentifyFile().identify
380 * @throws IOException
382 public void mark() throws IOException
386 dataIn.mark(READAHEAD_LIMIT);
390 throw new IOException(MessageManager.getString("exception.no_init_source_stream"));
394 public String nextLine() throws IOException
398 return dataIn.readLine();
400 throw new IOException(MessageManager.formatMessage("exception.invalid_source_stream", new String[]{errormessage}));
403 public boolean isValid()
409 * closes the datasource and tidies up. source will be left in an error state
411 public void close() throws IOException
413 errormessage = "EXCEPTION ON CLOSE";
417 errormessage = "SOURCE IS CLOSED";
421 * rewinds the datasource the beginning.
424 public void reset() throws IOException
426 if (dataIn != null && !error)
432 throw new IOException(MessageManager.getString("error.implementation_error_reset_called_for_invalid_source"));
438 * @return true if there is a warning for the user
440 public boolean hasWarningMessage()
442 return (warningMessage != null && warningMessage.length() > 0);
447 * @return empty string or warning message about file that was just parsed.
449 public String getWarningMessage()
451 return warningMessage;
454 public String getInFile()
458 return inFile.getAbsolutePath() + " (" + index + ")";
462 return "From Paste + (" + index + ")";
467 * @return the dataName
469 public String getDataName()
475 * set the (human readable) name or URI for this datasource
479 protected void setDataName(String dataname)
485 * get the underlying bufferedReader for this data source.
487 * @return null if no reader available
488 * @throws IOException
490 public Reader getReader()
492 if (dataIn != null) // Probably don't need to test for readiness &&
500 public AlignViewportI getViewport()
505 public void setViewport(AlignViewportI viewport)
507 this.viewport = viewport;
511 * @return the currently configured exportSettings for writing data.
513 public AlignExportSettingI getExportSettings()
515 return exportSettings;
519 * Set configuration for export of data.
521 * @param exportSettings
522 * the exportSettings to set
524 public void setExportSettings(AlignExportSettingI exportSettings)
526 this.exportSettings = exportSettings;