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.util.MessageManager;
28 import java.io.BufferedReader;
30 import java.io.FileInputStream;
31 import java.io.FileReader;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.InputStreamReader;
35 import java.io.Reader;
36 import java.io.StringReader;
37 import java.net.MalformedURLException;
39 import java.util.zip.GZIPInputStream;
42 * implements a random access wrapper around a particular datasource, for
43 * passing to identifyFile and AlignFile objects.
45 public class FileParse
48 * text specifying source of data. usually filename or url.
50 private String dataName = "unknown source";
52 public File inFile = null;
55 * a viewport associated with the current file operation. May be null. May
56 * move to different object.
58 private AlignViewportI viewport;
61 * specific settings for exporting data from the current context
63 private AlignExportSettingI exportSettings;
66 * sequence counter for FileParse object created from same data source
71 * separator for extracting specific 'frame' of a datasource for formats that
72 * support multiple records (e.g. BLC, Stockholm, etc)
74 protected char suffixSeparator = '#';
77 * character used to write newlines
79 protected String newline = System.getProperty("line.separator");
81 public void setNewlineString(String nl)
86 public String getNewlineString()
92 * '#' separated string tagged on to end of filename or url that was clipped
93 * off to resolve to valid filename
95 protected String suffix = null;
97 protected String type = null;
99 protected BufferedReader dataIn = null;
101 protected String errormessage = "UNINITIALISED SOURCE";
103 protected boolean error = true;
105 protected String warningMessage = null;
108 * size of readahead buffer used for when initial stream position is marked.
110 final int READAHEAD_LIMIT = 2048;
117 * Create a new FileParse instance reading from the same datasource starting
118 * at the current position. WARNING! Subsequent reads from either object will
119 * affect the read position of the other, but not the error state.
123 public FileParse(FileParse from) throws IOException
127 throw new Error(MessageManager.getString("error.implementation_error_null_fileparse"));
133 index = ++from.index;
134 inFile = from.inFile;
135 suffixSeparator = from.suffixSeparator;
136 suffix = from.suffix;
137 errormessage = from.errormessage; // inherit potential error messages
138 error = false; // reset any error condition.
140 dataIn = from.dataIn;
145 dataName = from.dataName;
149 * Attempt to open a file as a datasource. Sets error and errormessage if
150 * fileStr was invalid.
153 * @return this.error (true if the source was invalid)
155 private boolean checkFileSource(String fileStr) throws IOException
158 this.inFile = new File(fileStr);
159 // check to see if it's a Jar file in disguise.
160 if (!inFile.exists())
162 errormessage = "FILE NOT FOUND";
165 if (!inFile.canRead())
167 errormessage = "FILE CANNOT BE OPENED FOR READING";
170 if (inFile.isDirectory())
172 // this is really a 'complex' filetype - but we don't handle directory
174 errormessage = "FILE IS A DIRECTORY";
179 if (fileStr.toLowerCase().endsWith(".gz"))
183 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
186 } catch (Exception x)
188 warningMessage = "Failed to resolve as a GZ stream ("
189 + x.getMessage() + ")";
190 // x.printStackTrace();
195 dataIn = new BufferedReader(new FileReader(fileStr));
201 private BufferedReader tryAsGzipSource(InputStream inputStream)
204 BufferedReader inData = new BufferedReader(new InputStreamReader(
205 new GZIPInputStream(inputStream)));
212 private boolean checkURLSource(String fileStr) throws IOException,
213 MalformedURLException
215 errormessage = "URL NOT FOUND";
216 URL url = new URL(fileStr);
218 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
221 if (fileStr.toLowerCase().endsWith(".gz"))
225 InputStream inputStream = url.openStream();
226 dataIn = tryAsGzipSource(inputStream);
229 } catch (Exception ex)
237 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
238 } catch (IOException q)
242 throw new IOException(MessageManager.getString("exception.failed_to_resolve_gzip_stream"), e);
246 // record URL as name of datasource.
252 * sets the suffix string (if any) and returns remainder (if suffix was
256 * @return truncated fileStr or null
258 private String extractSuffix(String fileStr)
260 // first check that there wasn't a suffix string tagged on.
261 int sfpos = fileStr.lastIndexOf(suffixSeparator);
262 if (sfpos > -1 && sfpos < fileStr.length() - 1)
264 suffix = fileStr.substring(sfpos + 1);
265 // System.err.println("DEBUG: Found Suffix:"+suffix);
266 return fileStr.substring(0, sfpos);
272 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
273 * types of sources that are handled.
276 * - datasource locator/content
278 * - protocol of source
279 * @throws MalformedURLException
280 * @throws IOException
282 public FileParse(String fileStr, String type)
283 throws MalformedURLException, IOException
288 if (type.equals(AppletFormatAdapter.FILE))
290 if (checkFileSource(fileStr))
292 String suffixLess = extractSuffix(fileStr);
293 if (suffixLess != null)
295 if (checkFileSource(suffixLess))
297 throw new IOException(MessageManager.formatMessage("exception.problem_opening_file_also_tried", new String[]{inFile.getName(),suffixLess,errormessage}));
302 throw new IOException(MessageManager.formatMessage("exception.problem_opening_file", new String[]{inFile.getName(),errormessage}));
306 else if (type.equals(AppletFormatAdapter.URL))
312 checkURLSource(fileStr);
313 if (suffixSeparator == '#')
315 extractSuffix(fileStr); // URL lref is stored for later reference.
317 } catch (IOException e)
319 String suffixLess = extractSuffix(fileStr);
320 if (suffixLess == null)
328 checkURLSource(suffixLess);
329 } catch (IOException e2)
331 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
332 throw (e); // just pass back original - everything was wrong.
336 } catch (Exception e)
338 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
339 + e.getMessage() + ")";
343 else if (type.equals(AppletFormatAdapter.PASTE))
345 errormessage = "PASTE INACCESSIBLE!";
346 dataIn = new BufferedReader(new StringReader(fileStr));
349 else if (type.equals(AppletFormatAdapter.CLASSLOADER))
351 errormessage = "RESOURCE CANNOT BE LOCATED";
352 java.io.InputStream is = getClass()
353 .getResourceAsStream("/" + fileStr);
356 String suffixLess = extractSuffix(fileStr);
357 if (suffixLess != null)
359 is = getClass().getResourceAsStream("/" + suffixLess);
364 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
374 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
375 + (type != null ? type : "null") + "'";
378 if (dataIn == null || error)
380 // pass up the reason why we have no source to read from
381 throw new IOException(MessageManager.formatMessage("exception.failed_to_read_data_from_source", new String[]{errormessage}));
384 dataIn.mark(READAHEAD_LIMIT);
388 * mark the current position in the source as start for the purposes of it
389 * being analysed by IdentifyFile().identify
391 * @throws IOException
393 public void mark() throws IOException
397 dataIn.mark(READAHEAD_LIMIT);
401 throw new IOException(MessageManager.getString("exception.no_init_source_stream"));
405 public String nextLine() throws IOException
409 return dataIn.readLine();
411 throw new IOException(MessageManager.formatMessage("exception.invalid_source_stream", new String[]{errormessage}));
416 * @return true if this FileParse is configured for Export only
418 public boolean isExporting()
420 return !error && dataIn == null;
425 * @return true if the data source is valid
427 public boolean isValid()
433 * closes the datasource and tidies up. source will be left in an error state
435 public void close() throws IOException
437 errormessage = "EXCEPTION ON CLOSE";
441 errormessage = "SOURCE IS CLOSED";
445 * rewinds the datasource the beginning.
448 public void reset() throws IOException
450 if (dataIn != null && !error)
456 throw new IOException(MessageManager.getString("error.implementation_error_reset_called_for_invalid_source"));
462 * @return true if there is a warning for the user
464 public boolean hasWarningMessage()
466 return (warningMessage != null && warningMessage.length() > 0);
471 * @return empty string or warning message about file that was just parsed.
473 public String getWarningMessage()
475 return warningMessage;
478 public String getInFile()
482 return inFile.getAbsolutePath() + " (" + index + ")";
486 return "From Paste + (" + index + ")";
491 * @return the dataName
493 public String getDataName()
499 * set the (human readable) name or URI for this datasource
503 protected void setDataName(String dataname)
509 * get the underlying bufferedReader for this data source.
511 * @return null if no reader available
512 * @throws IOException
514 public Reader getReader()
516 if (dataIn != null) // Probably don't need to test for readiness &&
524 public AlignViewportI getViewport()
529 public void setViewport(AlignViewportI viewport)
531 this.viewport = viewport;
535 * @return the currently configured exportSettings for writing data.
537 public AlignExportSettingI getExportSettings()
539 return exportSettings;
543 * Set configuration for export of data.
545 * @param exportSettings
546 * the exportSettings to set
548 public void setExportSettings(AlignExportSettingI exportSettings)
550 this.exportSettings = exportSettings;
554 * method overridden by complex file exporter/importers which support
555 * exporting visualisation and layout settings for a view
559 public void configureForView(AlignmentViewPanel avpanel)
562 setViewport(avpanel.getAlignViewport());
564 // could also set export/import settings