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
129 .getString("error.implementation_error_null_fileparse"));
135 index = ++from.index;
136 inFile = from.inFile;
137 suffixSeparator = from.suffixSeparator;
138 suffix = from.suffix;
139 errormessage = from.errormessage; // inherit potential error messages
140 error = false; // reset any error condition.
142 dataIn = from.dataIn;
147 dataName = from.dataName;
151 * Attempt to open a file as a datasource. Sets error and errormessage if
152 * fileStr was invalid.
155 * @return this.error (true if the source was invalid)
157 private boolean checkFileSource(String fileStr) throws IOException
160 this.inFile = new File(fileStr);
161 // check to see if it's a Jar file in disguise.
162 if (!inFile.exists())
164 errormessage = "FILE NOT FOUND";
167 if (!inFile.canRead())
169 errormessage = "FILE CANNOT BE OPENED FOR READING";
172 if (inFile.isDirectory())
174 // this is really a 'complex' filetype - but we don't handle directory
176 errormessage = "FILE IS A DIRECTORY";
181 if (fileStr.toLowerCase().endsWith(".gz"))
185 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
188 } catch (Exception x)
190 warningMessage = "Failed to resolve as a GZ stream ("
191 + x.getMessage() + ")";
192 // x.printStackTrace();
197 dataIn = new BufferedReader(new FileReader(fileStr));
203 private BufferedReader tryAsGzipSource(InputStream inputStream)
206 BufferedReader inData = new BufferedReader(new InputStreamReader(
207 new GZIPInputStream(inputStream)));
214 private boolean checkURLSource(String fileStr) throws IOException,
215 MalformedURLException
217 errormessage = "URL NOT FOUND";
218 URL url = new URL(fileStr);
220 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
223 if (fileStr.toLowerCase().endsWith(".gz"))
227 InputStream inputStream = url.openStream();
228 dataIn = tryAsGzipSource(inputStream);
231 } catch (Exception ex)
239 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
240 } catch (IOException q)
244 throw new IOException(
246 .getString("exception.failed_to_resolve_gzip_stream"),
251 // record URL as name of datasource.
257 * sets the suffix string (if any) and returns remainder (if suffix was
261 * @return truncated fileStr or null
263 private String extractSuffix(String fileStr)
265 // first check that there wasn't a suffix string tagged on.
266 int sfpos = fileStr.lastIndexOf(suffixSeparator);
267 if (sfpos > -1 && sfpos < fileStr.length() - 1)
269 suffix = fileStr.substring(sfpos + 1);
270 // System.err.println("DEBUG: Found Suffix:"+suffix);
271 return fileStr.substring(0, sfpos);
277 * not for general use, creates a fileParse object for an existing reader with
278 * configurable values for the origin and the type of the source
280 public FileParse(BufferedReader source, String originString,
286 dataName = originString;
290 if (dataIn.markSupported())
292 dataIn.mark(READAHEAD_LIMIT);
294 } catch (IOException q)
301 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
302 * types of sources that are handled.
305 * - datasource locator/content
307 * - protocol of source
308 * @throws MalformedURLException
309 * @throws IOException
311 public FileParse(String fileStr, String type)
312 throws MalformedURLException, IOException
317 if (type.equals(AppletFormatAdapter.FILE))
319 if (checkFileSource(fileStr))
321 String suffixLess = extractSuffix(fileStr);
322 if (suffixLess != null)
324 if (checkFileSource(suffixLess))
326 throw new IOException(MessageManager.formatMessage(
327 "exception.problem_opening_file_also_tried",
328 new String[] { inFile.getName(), suffixLess,
334 throw new IOException(MessageManager.formatMessage(
335 "exception.problem_opening_file",
336 new String[] { inFile.getName(), errormessage }));
340 else if (type.equals(AppletFormatAdapter.URL))
346 checkURLSource(fileStr);
347 if (suffixSeparator == '#')
349 extractSuffix(fileStr); // URL lref is stored for later reference.
351 } catch (IOException e)
353 String suffixLess = extractSuffix(fileStr);
354 if (suffixLess == null)
362 checkURLSource(suffixLess);
363 } catch (IOException e2)
365 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
366 throw (e); // just pass back original - everything was wrong.
370 } catch (Exception e)
372 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
373 + e.getMessage() + ")";
377 else if (type.equals(AppletFormatAdapter.PASTE))
379 errormessage = "PASTE INACCESSIBLE!";
380 dataIn = new BufferedReader(new StringReader(fileStr));
383 else if (type.equals(AppletFormatAdapter.CLASSLOADER))
385 errormessage = "RESOURCE CANNOT BE LOCATED";
386 java.io.InputStream is = getClass()
387 .getResourceAsStream("/" + fileStr);
390 String suffixLess = extractSuffix(fileStr);
391 if (suffixLess != null)
393 is = getClass().getResourceAsStream("/" + suffixLess);
398 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
408 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
409 + (type != null ? type : "null") + "'";
412 if (dataIn == null || error)
414 // pass up the reason why we have no source to read from
415 throw new IOException(MessageManager.formatMessage(
416 "exception.failed_to_read_data_from_source",
417 new String[] { errormessage }));
420 dataIn.mark(READAHEAD_LIMIT);
424 * mark the current position in the source as start for the purposes of it
425 * being analysed by IdentifyFile().identify
427 * @throws IOException
429 public void mark() throws IOException
433 dataIn.mark(READAHEAD_LIMIT);
437 throw new IOException(
438 MessageManager.getString("exception.no_init_source_stream"));
442 public String nextLine() throws IOException
446 return dataIn.readLine();
448 throw new IOException(MessageManager.formatMessage(
449 "exception.invalid_source_stream",
450 new String[] { errormessage }));
455 * @return true if this FileParse is configured for Export only
457 public boolean isExporting()
459 return !error && dataIn == null;
464 * @return true if the data source is valid
466 public boolean isValid()
472 * closes the datasource and tidies up. source will be left in an error state
474 public void close() throws IOException
476 errormessage = "EXCEPTION ON CLOSE";
480 errormessage = "SOURCE IS CLOSED";
484 * Rewinds the datasource to the marked point if possible
489 public void reset(int bytesRead) throws IOException
491 if (bytesRead >= READAHEAD_LIMIT)
493 System.err.println(String.format(
494 "File reset error: read %d bytes but reset limit is %d",
495 bytesRead, READAHEAD_LIMIT));
497 if (dataIn != null && !error)
503 throw new IOException(
505 .getString("error.implementation_error_reset_called_for_invalid_source"));
511 * @return true if there is a warning for the user
513 public boolean hasWarningMessage()
515 return (warningMessage != null && warningMessage.length() > 0);
520 * @return empty string or warning message about file that was just parsed.
522 public String getWarningMessage()
524 return warningMessage;
527 public String getInFile()
531 return inFile.getAbsolutePath() + " (" + index + ")";
535 return "From Paste + (" + index + ")";
540 * @return the dataName
542 public String getDataName()
548 * set the (human readable) name or URI for this datasource
552 protected void setDataName(String dataname)
558 * get the underlying bufferedReader for this data source.
560 * @return null if no reader available
561 * @throws IOException
563 public Reader getReader()
565 if (dataIn != null) // Probably don't need to test for readiness &&
573 public AlignViewportI getViewport()
578 public void setViewport(AlignViewportI viewport)
580 this.viewport = viewport;
584 * @return the currently configured exportSettings for writing data.
586 public AlignExportSettingI getExportSettings()
588 return exportSettings;
592 * Set configuration for export of data.
594 * @param exportSettings
595 * the exportSettings to set
597 public void setExportSettings(AlignExportSettingI exportSettings)
599 this.exportSettings = exportSettings;
603 * method overridden by complex file exporter/importers which support
604 * exporting visualisation and layout settings for a view
608 public void configureForView(AlignmentViewPanel avpanel)
612 setViewport(avpanel.getAlignViewport());
614 // could also set export/import settings