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 = "UNITIALISED 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 * not for general use, creates a fileParse object for an existing reader with
273 * configurable values for the origin and the type of the source
275 public FileParse(BufferedReader source, String originString,
281 dataName = originString;
285 if (dataIn.markSupported())
287 dataIn.mark(READAHEAD_LIMIT);
289 } catch (IOException q)
296 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
297 * types of sources that are handled.
300 * - datasource locator/content
302 * - protocol of source
303 * @throws MalformedURLException
304 * @throws IOException
306 public FileParse(String fileStr, String type)
307 throws MalformedURLException, IOException
312 if (type.equals(AppletFormatAdapter.FILE))
314 if (checkFileSource(fileStr))
316 String suffixLess = extractSuffix(fileStr);
317 if (suffixLess != null)
319 if (checkFileSource(suffixLess))
321 throw new IOException(MessageManager.formatMessage("exception.problem_opening_file_also_tried", new String[]{inFile.getName(),suffixLess,errormessage}));
326 throw new IOException(MessageManager.formatMessage("exception.problem_opening_file", new String[]{inFile.getName(),errormessage}));
330 else if (type.equals(AppletFormatAdapter.URL))
336 checkURLSource(fileStr);
337 if (suffixSeparator == '#')
339 extractSuffix(fileStr); // URL lref is stored for later reference.
341 } catch (IOException e)
343 String suffixLess = extractSuffix(fileStr);
344 if (suffixLess == null)
352 checkURLSource(suffixLess);
353 } catch (IOException e2)
355 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
356 throw (e); // just pass back original - everything was wrong.
360 } catch (Exception e)
362 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
363 + e.getMessage() + ")";
367 else if (type.equals(AppletFormatAdapter.PASTE))
369 errormessage = "PASTE INACCESSIBLE!";
370 dataIn = new BufferedReader(new StringReader(fileStr));
373 else if (type.equals(AppletFormatAdapter.CLASSLOADER))
375 errormessage = "RESOURCE CANNOT BE LOCATED";
376 java.io.InputStream is = getClass()
377 .getResourceAsStream("/" + fileStr);
380 String suffixLess = extractSuffix(fileStr);
381 if (suffixLess != null)
383 is = getClass().getResourceAsStream("/" + suffixLess);
388 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
398 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
399 + (type != null ? type : "null") + "'";
402 if (dataIn == null || error)
404 // pass up the reason why we have no source to read from
405 throw new IOException(MessageManager.formatMessage("exception.failed_to_read_data_from_source", new String[]{errormessage}));
408 dataIn.mark(READAHEAD_LIMIT);
412 * mark the current position in the source as start for the purposes of it
413 * being analysed by IdentifyFile().identify
415 * @throws IOException
417 public void mark() throws IOException
421 dataIn.mark(READAHEAD_LIMIT);
425 throw new IOException(MessageManager.getString("exception.no_init_source_stream"));
429 public String nextLine() throws IOException
433 return dataIn.readLine();
435 throw new IOException(MessageManager.formatMessage("exception.invalid_source_stream", new String[]{errormessage}));
440 * @return true if this FileParse is configured for Export only
442 public boolean isExporting()
444 return !error && dataIn == null;
449 * @return true if the data source is valid
451 public boolean isValid()
457 * closes the datasource and tidies up. source will be left in an error state
459 public void close() throws IOException
461 errormessage = "EXCEPTION ON CLOSE";
465 errormessage = "SOURCE IS CLOSED";
469 * rewinds the datasource the beginning.
472 public void reset() throws IOException
474 if (dataIn != null && !error)
480 throw new IOException(MessageManager.getString("error.implementation_error_reset_called_for_invalid_source"));
486 * @return true if there is a warning for the user
488 public boolean hasWarningMessage()
490 return (warningMessage != null && warningMessage.length() > 0);
495 * @return empty string or warning message about file that was just parsed.
497 public String getWarningMessage()
499 return warningMessage;
502 public String getInFile()
506 return inFile.getAbsolutePath() + " (" + index + ")";
510 return "From Paste + (" + index + ")";
515 * @return the dataName
517 public String getDataName()
523 * set the (human readable) name or URI for this datasource
527 protected void setDataName(String dataname)
533 * get the underlying bufferedReader for this data source.
535 * @return null if no reader available
536 * @throws IOException
538 public Reader getReader()
540 if (dataIn != null) // Probably don't need to test for readiness &&
548 public AlignViewportI getViewport()
553 public void setViewport(AlignViewportI viewport)
555 this.viewport = viewport;
559 * @return the currently configured exportSettings for writing data.
561 public AlignExportSettingI getExportSettings()
563 return exportSettings;
567 * Set configuration for export of data.
569 * @param exportSettings
570 * the exportSettings to set
572 public void setExportSettings(AlignExportSettingI exportSettings)
574 this.exportSettings = exportSettings;
578 * method overridden by complex file exporter/importers which support
579 * exporting visualisation and layout settings for a view
583 public void configureForView(AlignmentViewPanel avpanel)
586 setViewport(avpanel.getAlignViewport());
588 // could also set export/import settings