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;
41 import javajs.J2SIgnoreImport;
44 * implements a random access wrapper around a particular datasource, for
45 * passing to identifyFile and AlignFile objects.
47 @J2SIgnoreImport({java.io.File.class, java.io.FileReader.class, java.io.FileInputStream.class })
48 public class FileParse
51 * text specifying source of data. usually filename or url.
53 private String dataName = "unknown source";
55 public File inFile = null;
58 * a viewport associated with the current file operation. May be null. May
59 * move to different object.
61 private AlignViewportI viewport;
64 * specific settings for exporting data from the current context
66 private AlignExportSettingI exportSettings;
69 * sequence counter for FileParse object created from same data source
74 * separator for extracting specific 'frame' of a datasource for formats that
75 * support multiple records (e.g. BLC, Stockholm, etc)
77 protected char suffixSeparator = '#';
80 * character used to write newlines
82 protected String newline = System.getProperty("line.separator");
84 public void setNewlineString(String nl)
89 public String getNewlineString()
95 * '#' separated string tagged on to end of filename or url that was clipped
96 * off to resolve to valid filename
98 protected String suffix = null;
100 protected String type = null;
102 protected BufferedReader dataIn = null;
104 protected String errormessage = "UNITIALISED SOURCE";
106 protected boolean error = true;
108 protected String warningMessage = null;
111 * size of readahead buffer used for when initial stream position is marked.
113 final int READAHEAD_LIMIT = 2048;
120 * Create a new FileParse instance reading from the same datasource starting
121 * at the current position. WARNING! Subsequent reads from either object will
122 * affect the read position of the other, but not the error state.
126 public FileParse(FileParse from) throws IOException
130 throw new Error(MessageManager.getString("error.implementation_error_null_fileparse"));
136 index = ++from.index;
137 inFile = from.inFile;
138 suffixSeparator = from.suffixSeparator;
139 suffix = from.suffix;
140 errormessage = from.errormessage; // inherit potential error messages
141 error = false; // reset any error condition.
143 dataIn = from.dataIn;
148 dataName = from.dataName;
152 * Attempt to open a file as a datasource. Sets error and errormessage if
153 * fileStr was invalid.
160 * @return this.error (true if the source was invalid)
162 private boolean checkFileSource(String fileStr) throws IOException
165 this.inFile = new File(fileStr);
166 // check to see if it's a Jar file in disguise.
167 if (!inFile.exists())
169 errormessage = "FILE NOT FOUND";
172 if (!inFile.canRead())
174 errormessage = "FILE CANNOT BE OPENED FOR READING";
177 if (inFile.isDirectory())
179 // this is really a 'complex' filetype - but we don't handle directory
181 errormessage = "FILE IS A DIRECTORY";
186 if (fileStr.toLowerCase().endsWith(".gz"))
190 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
193 } catch (Exception x)
195 warningMessage = "Failed to resolve as a GZ stream ("
196 + x.getMessage() + ")";
197 // x.printStackTrace();
201 dataIn = new BufferedReader(new FileReader(fileStr));
213 private BufferedReader tryAsGzipSource(InputStream inputStream)
216 BufferedReader inData = new BufferedReader(new InputStreamReader(
217 new GZIPInputStream(inputStream)));
224 private boolean checkURLSource(String fileStr) throws IOException,
225 MalformedURLException
227 errormessage = "URL NOT FOUND";
228 URL url = new URL(fileStr);
230 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
233 if (fileStr.toLowerCase().endsWith(".gz"))
237 InputStream inputStream = url.openStream();
238 dataIn = tryAsGzipSource(inputStream);
241 } catch (Exception ex)
249 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
250 } catch (IOException q)
254 throw new IOException(MessageManager.getString("exception.failed_to_resolve_gzip_stream"), e);
258 // record URL as name of datasource.
264 * sets the suffix string (if any) and returns remainder (if suffix was
268 * @return truncated fileStr or null
270 private String extractSuffix(String fileStr)
272 // first check that there wasn't a suffix string tagged on.
273 int sfpos = fileStr.lastIndexOf(suffixSeparator);
274 if (sfpos > -1 && sfpos < fileStr.length() - 1)
276 suffix = fileStr.substring(sfpos + 1);
277 // System.err.println("DEBUG: Found Suffix:"+suffix);
278 return fileStr.substring(0, sfpos);
284 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
285 * types of sources that are handled.
288 * - datasource locator/content
290 * - protocol of source
291 * @throws MalformedURLException
292 * @throws IOException
294 public FileParse(String fileStr, String type) throws MalformedURLException, IOException {
298 if (type.equals(AppletFormatAdapter.FILE)) {
304 if (checkFileSource(fileStr)) {
305 String suffixLess = extractSuffix(fileStr);
306 if (suffixLess != null) {
307 if (checkFileSource(suffixLess)) {
308 throw new IOException(MessageManager.formatMessage(
309 "exception.problem_opening_file_also_tried", new String[] {
310 inFile.getName(), suffixLess, errormessage }));
313 throw new IOException(MessageManager.formatMessage(
314 "exception.problem_opening_file",
315 new String[] { inFile.getName(), errormessage }));
319 } else if (type.equals(AppletFormatAdapter.URL)) {
322 checkURLSource(fileStr);
323 if (suffixSeparator == '#') {
324 extractSuffix(fileStr); // URL lref is stored for later reference.
326 } catch (IOException e) {
327 String suffixLess = extractSuffix(fileStr);
328 if (suffixLess == null) {
332 checkURLSource(suffixLess);
333 } catch (IOException e2) {
334 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
335 throw (e); // just pass back original - everything was wrong.
339 } catch (Exception e) {
340 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
341 + e.getMessage() + ")";
344 } else if (type.equals(AppletFormatAdapter.PASTE)) {
345 errormessage = "PASTE INACCESSIBLE!";
346 dataIn = new BufferedReader(new StringReader(fileStr));
348 } else if (type.equals(AppletFormatAdapter.CLASSLOADER)) {
349 errormessage = "RESOURCE CANNOT BE LOCATED";
350 java.io.InputStream is = getClass().getResourceAsStream("/" + fileStr);
352 String suffixLess = extractSuffix(fileStr);
353 if (suffixLess != null) {
354 is = getClass().getResourceAsStream("/" + suffixLess);
358 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
364 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
365 + (type != null ? type : "null") + "'";
368 if (dataIn == null || error) {
369 // pass up the reason why we have no source to read from
370 throw new IOException(MessageManager.formatMessage(
371 "exception.failed_to_read_data_from_source",
372 new String[] { errormessage }));
375 dataIn.mark(READAHEAD_LIMIT);
379 * mark the current position in the source as start for the purposes of it
380 * being analysed by IdentifyFile().identify
382 * @throws IOException
384 public void mark() throws IOException
388 dataIn.mark(READAHEAD_LIMIT);
392 throw new IOException(MessageManager.getString("exception.no_init_source_stream"));
396 public String nextLine() throws IOException
400 return dataIn.readLine();
402 throw new IOException(MessageManager.formatMessage("exception.invalid_source_stream", new String[]{errormessage}));
407 * @return true if this FileParse is configured for Export only
409 public boolean isExporting()
411 return !error && dataIn == null;
416 * @return true if the data source is valid
418 public boolean isValid()
424 * closes the datasource and tidies up. source will be left in an error state
426 public void close() throws IOException
428 errormessage = "EXCEPTION ON CLOSE";
432 errormessage = "SOURCE IS CLOSED";
436 * rewinds the datasource the beginning.
439 public void reset() throws IOException
441 if (dataIn != null && !error)
447 throw new IOException(MessageManager.getString("error.implementation_error_reset_called_for_invalid_source"));
453 * @return true if there is a warning for the user
455 public boolean hasWarningMessage()
457 return (warningMessage != null && warningMessage.length() > 0);
462 * @return empty string or warning message about file that was just parsed.
464 public String getWarningMessage()
466 return warningMessage;
469 public String getInFile()
473 return inFile.getAbsolutePath() + " (" + index + ")";
477 return "From Paste + (" + index + ")";
482 * @return the dataName
484 public String getDataName()
490 * set the (human readable) name or URI for this datasource
494 protected void setDataName(String dataname)
500 * get the underlying bufferedReader for this data source.
502 * @return null if no reader available
503 * @throws IOException
505 public Reader getReader()
507 if (dataIn != null) // Probably don't need to test for readiness &&
515 public AlignViewportI getViewport()
520 public void setViewport(AlignViewportI viewport)
522 this.viewport = viewport;
526 * @return the currently configured exportSettings for writing data.
528 public AlignExportSettingI getExportSettings()
530 return exportSettings;
534 * Set configuration for export of data.
536 * @param exportSettings
537 * the exportSettings to set
539 public void setExportSettings(AlignExportSettingI exportSettings)
541 this.exportSettings = exportSettings;
545 * method overridden by complex file exporter/importers which support
546 * exporting visualisation and layout settings for a view
550 public void configureForView(AlignmentViewPanel avpanel)
553 setViewport(avpanel.getAlignViewport());
555 // could also set export/import settings