2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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;
27 import java.util.zip.GZIPInputStream;
30 * implements a random access wrapper around a particular datasource, for
31 * passing to identifyFile and AlignFile objects.
33 public class FileParse
36 * text specifying source of data. usually filename or url.
38 private String dataName = "unknown source";
40 public File inFile = null;
42 public int index = 1; // sequence counter for FileParse object created from
46 protected char suffixSeparator = '#';
49 * character used to write newlines
51 protected String newline = System.getProperty("line.separator");
53 public void setNewlineString(String nl)
58 public String getNewlineString()
64 * '#' separated string tagged on to end of filename or url that was clipped
65 * off to resolve to valid filename
67 protected String suffix = null;
69 protected String type = null;
71 protected BufferedReader dataIn = null;
73 protected String errormessage = "UNITIALISED SOURCE";
75 protected boolean error = true;
77 protected String warningMessage = null;
80 * size of readahead buffer used for when initial stream position is marked.
82 final int READAHEAD_LIMIT = 2048;
89 * Create a new FileParse instance reading from the same datasource starting
90 * at the current position. WARNING! Subsequent reads from either object will
91 * affect the read position of the other, but not the error state.
95 public FileParse(FileParse from) throws IOException
99 throw new Error(MessageManager.getString("error.implementation_error_null_fileparse"));
103 index = ++from.index;
104 inFile = from.inFile;
105 suffixSeparator = from.suffixSeparator;
106 suffix = from.suffix;
107 errormessage = from.errormessage; // inherit potential error messages
108 error = false; // reset any error condition.
110 dataIn = from.dataIn;
115 dataName = from.dataName;
119 * Attempt to open a file as a datasource. Sets error and errormessage if
120 * fileStr was invalid.
123 * @return this.error (true if the source was invalid)
125 private boolean checkFileSource(String fileStr) throws IOException
128 this.inFile = new File(fileStr);
129 // check to see if it's a Jar file in disguise.
130 if (!inFile.exists())
132 errormessage = "FILE NOT FOUND";
135 if (!inFile.canRead())
137 errormessage = "FILE CANNOT BE OPENED FOR READING";
140 if (inFile.isDirectory())
142 // this is really a 'complex' filetype - but we don't handle directory
144 errormessage = "FILE IS A DIRECTORY";
149 if (fileStr.toLowerCase().endsWith(".gz"))
153 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
156 } catch (Exception x)
158 warningMessage = "Failed to resolve as a GZ stream ("
159 + x.getMessage() + ")";
165 dataIn = new BufferedReader(new FileReader(fileStr));
171 private BufferedReader tryAsGzipSource(InputStream inputStream)
174 BufferedReader inData = new BufferedReader(new InputStreamReader(
175 new GZIPInputStream(inputStream)));
182 private boolean checkURLSource(String fileStr) throws IOException,
183 MalformedURLException
185 errormessage = "URL NOT FOUND";
186 URL url = new URL(fileStr);
188 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
191 if (fileStr.toLowerCase().endsWith(".gz"))
195 InputStream inputStream = url.openStream();
196 dataIn = tryAsGzipSource(inputStream);
199 } catch (Exception ex)
207 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
208 } catch (IOException q)
212 throw new IOException(MessageManager.getString("exception.failed_to_resolve_gzip_stream"), e);
216 // record URL as name of datasource.
222 * sets the suffix string (if any) and returns remainder (if suffix was
226 * @return truncated fileStr or null
228 private String extractSuffix(String fileStr)
230 // first check that there wasn't a suffix string tagged on.
231 int sfpos = fileStr.lastIndexOf(suffixSeparator);
232 if (sfpos > -1 && sfpos < fileStr.length() - 1)
234 suffix = fileStr.substring(sfpos + 1);
235 // System.err.println("DEBUG: Found Suffix:"+suffix);
236 return fileStr.substring(0, sfpos);
242 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
243 * types of sources that are handled.
246 * - datasource locator/content
248 * - protocol of source
249 * @throws MalformedURLException
250 * @throws IOException
252 public FileParse(String fileStr, String type)
253 throws MalformedURLException, IOException
258 if (type.equals(AppletFormatAdapter.FILE))
260 if (checkFileSource(fileStr))
262 String suffixLess = extractSuffix(fileStr);
263 if (suffixLess != null)
265 if (checkFileSource(suffixLess))
267 throw new IOException(MessageManager.formatMessage("exception.problem_opening_file_also_tried", new String[]{inFile.getName(),suffixLess,errormessage}));
272 throw new IOException(MessageManager.formatMessage("exception.problem_opening_file", new String[]{inFile.getName(),errormessage}));
276 else if (type.equals(AppletFormatAdapter.URL))
282 checkURLSource(fileStr);
283 if (suffixSeparator == '#')
284 extractSuffix(fileStr); // URL lref is stored for later reference.
285 } catch (IOException e)
287 String suffixLess = extractSuffix(fileStr);
288 if (suffixLess == null)
296 checkURLSource(suffixLess);
297 } catch (IOException e2)
299 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
300 throw (e); // just pass back original - everything was wrong.
304 } catch (Exception e)
306 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
307 + e.getMessage() + ")";
311 else if (type.equals(AppletFormatAdapter.PASTE))
313 errormessage = "PASTE INACCESSIBLE!";
314 dataIn = new BufferedReader(new StringReader(fileStr));
317 else if (type.equals(AppletFormatAdapter.CLASSLOADER))
319 errormessage = "RESOURCE CANNOT BE LOCATED";
320 java.io.InputStream is = getClass()
321 .getResourceAsStream("/" + fileStr);
324 String suffixLess = extractSuffix(fileStr);
325 if (suffixLess != null)
326 is = getClass().getResourceAsStream("/" + suffixLess);
330 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
340 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
341 + (type != null ? type : "null") + "'";
344 if (dataIn == null || error)
346 // pass up the reason why we have no source to read from
347 throw new IOException(MessageManager.formatMessage("exception.failed_to_read_data_from_source", new String[]{errormessage}));
350 dataIn.mark(READAHEAD_LIMIT);
354 * mark the current position in the source as start for the purposes of it
355 * being analysed by IdentifyFile().identify
357 * @throws IOException
359 public void mark() throws IOException
363 dataIn.mark(READAHEAD_LIMIT);
367 throw new IOException(MessageManager.getString("exception.no_init_source_stream"));
371 public String nextLine() throws IOException
374 return dataIn.readLine();
375 throw new IOException(MessageManager.formatMessage("exception.invalid_source_stream", new String[]{errormessage}));
378 public boolean isValid()
384 * closes the datasource and tidies up. source will be left in an error state
386 public void close() throws IOException
388 errormessage = "EXCEPTION ON CLOSE";
392 errormessage = "SOURCE IS CLOSED";
396 * rewinds the datasource the beginning.
399 public void reset() throws IOException
401 if (dataIn != null && !error)
407 throw new IOException(MessageManager.getString("error.implementation_error_reset_called_for_invalid_source"));
413 * @return true if there is a warning for the user
415 public boolean hasWarningMessage()
417 return (warningMessage != null && warningMessage.length() > 0);
422 * @return empty string or warning message about file that was just parsed.
424 public String getWarningMessage()
426 return warningMessage;
429 public String getInFile()
433 return inFile.getAbsolutePath() + " (" + index + ")";
437 return "From Paste + (" + index + ")";
442 * @return the dataName
444 public String getDataName()
450 * set the (human readable) name or URI for this datasource
454 protected void setDataName(String dataname)
460 * get the underlying bufferedReader for this data source.
462 * @return null if no reader available
463 * @throws IOException
465 public Reader getReader()
467 if (dataIn != null) // Probably don't need to test for readiness &&