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.util.MessageManager;
25 import java.io.BufferedReader;
27 import java.io.FileInputStream;
28 import java.io.FileReader;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.io.Reader;
33 import java.io.StringReader;
34 import java.net.MalformedURLException;
36 import java.util.zip.GZIPInputStream;
39 * implements a random access wrapper around a particular datasource, for
40 * passing to identifyFile and AlignFile objects.
42 public class FileParse
45 * text specifying source of data. usually filename or url.
47 private String dataName = "unknown source";
49 public File inFile = null;
51 public int index = 1; // sequence counter for FileParse object created from
55 protected char suffixSeparator = '#';
58 * character used to write newlines
60 protected String newline = System.getProperty("line.separator");
62 public void setNewlineString(String nl)
67 public String getNewlineString()
73 * '#' separated string tagged on to end of filename or url that was clipped
74 * off to resolve to valid filename
76 protected String suffix = null;
78 protected String type = null;
80 protected BufferedReader dataIn = null;
82 protected String errormessage = "UNITIALISED SOURCE";
84 protected boolean error = true;
86 protected String warningMessage = null;
89 * size of readahead buffer used for when initial stream position is marked.
91 final int READAHEAD_LIMIT = 2048;
98 * Create a new FileParse instance reading from the same datasource starting
99 * at the current position. WARNING! Subsequent reads from either object will
100 * affect the read position of the other, but not the error state.
104 public FileParse(FileParse from) throws IOException
108 throw new Error(MessageManager.getString("error.implementation_error_null_fileparse"));
114 index = ++from.index;
115 inFile = from.inFile;
116 suffixSeparator = from.suffixSeparator;
117 suffix = from.suffix;
118 errormessage = from.errormessage; // inherit potential error messages
119 error = false; // reset any error condition.
121 dataIn = from.dataIn;
126 dataName = from.dataName;
130 * Attempt to open a file as a datasource. Sets error and errormessage if
131 * fileStr was invalid.
134 * @return this.error (true if the source was invalid)
136 private boolean checkFileSource(String fileStr) throws IOException
139 this.inFile = new File(fileStr);
140 // check to see if it's a Jar file in disguise.
141 if (!inFile.exists())
143 errormessage = "FILE NOT FOUND";
146 if (!inFile.canRead())
148 errormessage = "FILE CANNOT BE OPENED FOR READING";
151 if (inFile.isDirectory())
153 // this is really a 'complex' filetype - but we don't handle directory
155 errormessage = "FILE IS A DIRECTORY";
160 if (fileStr.toLowerCase().endsWith(".gz"))
164 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
167 } catch (Exception x)
169 warningMessage = "Failed to resolve as a GZ stream ("
170 + x.getMessage() + ")";
171 // x.printStackTrace();
176 dataIn = new BufferedReader(new FileReader(fileStr));
182 private BufferedReader tryAsGzipSource(InputStream inputStream)
185 BufferedReader inData = new BufferedReader(new InputStreamReader(
186 new GZIPInputStream(inputStream)));
193 private boolean checkURLSource(String fileStr) throws IOException,
194 MalformedURLException
196 errormessage = "URL NOT FOUND";
197 URL url = new URL(fileStr);
199 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
202 if (fileStr.toLowerCase().endsWith(".gz"))
206 InputStream inputStream = url.openStream();
207 dataIn = tryAsGzipSource(inputStream);
210 } catch (Exception ex)
218 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
219 } catch (IOException q)
223 throw new IOException(MessageManager.getString("exception.failed_to_resolve_gzip_stream"), e);
227 // record URL as name of datasource.
233 * sets the suffix string (if any) and returns remainder (if suffix was
237 * @return truncated fileStr or null
239 private String extractSuffix(String fileStr)
241 // first check that there wasn't a suffix string tagged on.
242 int sfpos = fileStr.lastIndexOf(suffixSeparator);
243 if (sfpos > -1 && sfpos < fileStr.length() - 1)
245 suffix = fileStr.substring(sfpos + 1);
246 // System.err.println("DEBUG: Found Suffix:"+suffix);
247 return fileStr.substring(0, sfpos);
253 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
254 * types of sources that are handled.
257 * - datasource locator/content
259 * - protocol of source
260 * @throws MalformedURLException
261 * @throws IOException
263 public FileParse(String fileStr, String type)
264 throws MalformedURLException, IOException
269 if (type.equals(AppletFormatAdapter.FILE))
271 if (checkFileSource(fileStr))
273 String suffixLess = extractSuffix(fileStr);
274 if (suffixLess != null)
276 if (checkFileSource(suffixLess))
278 throw new IOException(MessageManager.formatMessage("exception.problem_opening_file_also_tried", new String[]{inFile.getName(),suffixLess,errormessage}));
283 throw new IOException(MessageManager.formatMessage("exception.problem_opening_file", new String[]{inFile.getName(),errormessage}));
287 else if (type.equals(AppletFormatAdapter.URL))
293 checkURLSource(fileStr);
294 if (suffixSeparator == '#')
296 extractSuffix(fileStr); // URL lref is stored for later reference.
298 } catch (IOException e)
300 String suffixLess = extractSuffix(fileStr);
301 if (suffixLess == null)
309 checkURLSource(suffixLess);
310 } catch (IOException e2)
312 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
313 throw (e); // just pass back original - everything was wrong.
317 } catch (Exception e)
319 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
320 + e.getMessage() + ")";
324 else if (type.equals(AppletFormatAdapter.PASTE))
326 errormessage = "PASTE INACCESSIBLE!";
327 dataIn = new BufferedReader(new StringReader(fileStr));
330 else if (type.equals(AppletFormatAdapter.CLASSLOADER))
332 errormessage = "RESOURCE CANNOT BE LOCATED";
333 java.io.InputStream is = getClass()
334 .getResourceAsStream("/" + fileStr);
337 String suffixLess = extractSuffix(fileStr);
338 if (suffixLess != null)
340 is = getClass().getResourceAsStream("/" + suffixLess);
345 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
355 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
356 + (type != null ? type : "null") + "'";
359 if (dataIn == null || error)
361 // pass up the reason why we have no source to read from
362 throw new IOException(MessageManager.formatMessage("exception.failed_to_read_data_from_source", new String[]{errormessage}));
365 dataIn.mark(READAHEAD_LIMIT);
369 * mark the current position in the source as start for the purposes of it
370 * being analysed by IdentifyFile().identify
372 * @throws IOException
374 public void mark() throws IOException
378 dataIn.mark(READAHEAD_LIMIT);
382 throw new IOException(MessageManager.getString("exception.no_init_source_stream"));
386 public String nextLine() throws IOException
390 return dataIn.readLine();
392 throw new IOException(MessageManager.formatMessage("exception.invalid_source_stream", new String[]{errormessage}));
395 public boolean isValid()
401 * closes the datasource and tidies up. source will be left in an error state
403 public void close() throws IOException
405 errormessage = "EXCEPTION ON CLOSE";
409 errormessage = "SOURCE IS CLOSED";
413 * rewinds the datasource the beginning.
416 public void reset() throws IOException
418 if (dataIn != null && !error)
424 throw new IOException(MessageManager.getString("error.implementation_error_reset_called_for_invalid_source"));
430 * @return true if there is a warning for the user
432 public boolean hasWarningMessage()
434 return (warningMessage != null && warningMessage.length() > 0);
439 * @return empty string or warning message about file that was just parsed.
441 public String getWarningMessage()
443 return warningMessage;
446 public String getInFile()
450 return inFile.getAbsolutePath() + " (" + index + ")";
454 return "From Paste + (" + index + ")";
459 * @return the dataName
461 public String getDataName()
467 * set the (human readable) name or URI for this datasource
471 protected void setDataName(String dataname)
477 * get the underlying bufferedReader for this data source.
479 * @return null if no reader available
480 * @throws IOException
482 public Reader getReader()
484 if (dataIn != null) // Probably don't need to test for readiness &&