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.api.FeatureSettingsModelI;
27 import jalview.util.MessageManager;
29 import java.io.BufferedReader;
31 import java.io.FileInputStream;
32 import java.io.FileReader;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.InputStreamReader;
36 import java.io.Reader;
37 import java.io.StringReader;
38 import java.net.MalformedURLException;
40 import java.util.zip.GZIPInputStream;
42 import javajs.util.Rdr;
45 * implements a random access wrapper around a particular datasource, for
46 * passing to identifyFile and AlignFile objects.
48 public class FileParse
50 protected static final String SPACE = " ";
52 protected static final String TAB = "\t";
55 * text specifying source of data. usually filename or url.
57 private String dataName = "unknown source";
59 public File inFile = null;
62 * a viewport associated with the current file operation. May be null. May
63 * move to different object.
65 private AlignViewportI viewport;
68 * specific settings for exporting data from the current context
70 private AlignExportSettingI exportSettings;
73 * sequence counter for FileParse object created from same data source
78 * separator for extracting specific 'frame' of a datasource for formats that
79 * support multiple records (e.g. BLC, Stockholm, etc)
81 protected char suffixSeparator = '#';
84 * character used to write newlines
86 protected String newline = System.getProperty("line.separator");
88 public void setNewlineString(String nl)
93 public String getNewlineString()
99 * '#' separated string tagged on to end of filename or url that was clipped
100 * off to resolve to valid filename
102 protected String suffix = null;
104 protected DataSourceType dataSourceType = null;
106 protected BufferedReader dataIn = null;
108 protected String errormessage = "UNINITIALISED SOURCE";
110 protected boolean error = true;
112 protected String warningMessage = null;
115 * size of readahead buffer used for when initial stream position is marked.
117 final int READAHEAD_LIMIT = 2048;
124 * Create a new FileParse instance reading from the same datasource starting
125 * at the current position. WARNING! Subsequent reads from either object will
126 * affect the read position of the other, but not the error state.
130 public FileParse(FileParse from) throws IOException
134 throw new Error(MessageManager
135 .getString("error.implementation_error_null_fileparse"));
141 index = ++from.index;
142 inFile = from.inFile;
143 suffixSeparator = from.suffixSeparator;
144 suffix = from.suffix;
145 errormessage = from.errormessage; // inherit potential error messages
146 error = false; // reset any error condition.
147 dataSourceType = from.dataSourceType;
148 dataIn = from.dataIn;
153 dataName = from.dataName;
157 * Attempt to open a file as a datasource. Sets error and errormessage if
158 * fileStr was invalid.
161 * @return this.error (true if the source was invalid)
163 private boolean checkFileSource(String fileStr) throws IOException
166 this.inFile = new File(fileStr);
167 // check to see if it's a Jar file in disguise.
168 if (!inFile.exists())
170 errormessage = "FILE NOT FOUND";
173 if (!inFile.canRead())
175 errormessage = "FILE CANNOT BE OPENED FOR READING";
178 if (inFile.isDirectory())
180 // this is really a 'complex' filetype - but we don't handle directory
182 errormessage = "FILE IS A DIRECTORY";
187 if (fileStr.toLowerCase().endsWith(".gz"))
191 dataIn = tryAsGzipSource(new FileInputStream(fileStr));
194 } catch (Exception x)
196 warningMessage = "Failed to resolve as a GZ stream ("
197 + x.getMessage() + ")";
198 // x.printStackTrace();
203 dataIn = new BufferedReader(new FileReader(fileStr));
209 private BufferedReader tryAsGzipSource(InputStream inputStream)
212 BufferedReader inData = new BufferedReader(
213 new InputStreamReader(new GZIPInputStream(inputStream)));
220 private boolean checkURLSource(String fileStr)
221 throws IOException, MalformedURLException
223 errormessage = "URL NOT FOUND";
224 URL url = new URL(fileStr);
226 // GZIPInputStream code borrowed from Aquaria (soon to be open sourced) via
229 if (fileStr.toLowerCase().endsWith(".gz"))
233 InputStream inputStream = url.openStream();
234 dataIn = tryAsGzipSource(inputStream);
237 } catch (Exception ex)
245 dataIn = new BufferedReader(new InputStreamReader(url.openStream()));
246 } catch (IOException q)
250 throw new IOException(MessageManager
251 .getString("exception.failed_to_resolve_gzip_stream"), e);
255 // record URL as name of datasource.
261 * sets the suffix string (if any) and returns remainder (if suffix was
265 * @return truncated fileStr or null
267 private String extractSuffix(String fileStr)
269 // first check that there wasn't a suffix string tagged on.
270 int sfpos = fileStr.lastIndexOf(suffixSeparator);
271 if (sfpos > -1 && sfpos < fileStr.length() - 1)
273 suffix = fileStr.substring(sfpos + 1);
274 // System.err.println("DEBUG: Found Suffix:"+suffix);
275 return fileStr.substring(0, sfpos);
281 * not for general use, creates a fileParse object for an existing reader with
282 * configurable values for the origin and the type of the source
284 public FileParse(BufferedReader source, String originString,
285 DataSourceType sourceType)
287 dataSourceType = sourceType;
290 dataName = originString;
294 if (dataIn.markSupported())
296 dataIn.mark(READAHEAD_LIMIT);
298 } catch (IOException q)
305 * Create a datasource for input to Jalview. See AppletFormatAdapter for the
306 * types of sources that are handled.
309 * - datasource locator/content
311 * - protocol of source
312 * @throws MalformedURLException
313 * @throws IOException
315 public FileParse(String fileStr, DataSourceType sourceType)
316 throws MalformedURLException, IOException
318 this.dataSourceType = sourceType;
321 if (sourceType == DataSourceType.FILE)
323 if (checkFileSource(fileStr))
325 String suffixLess = extractSuffix(fileStr);
326 if (suffixLess != null)
328 if (checkFileSource(suffixLess))
330 throw new IOException(MessageManager.formatMessage(
331 "exception.problem_opening_file_also_tried",
333 { inFile.getName(), suffixLess, errormessage }));
338 throw new IOException(MessageManager.formatMessage(
339 "exception.problem_opening_file", new String[]
340 { inFile.getName(), errormessage }));
344 else if (sourceType == DataSourceType.RELATIVE_URL)
348 * BH 2018 hack for no support for access-origin
352 * data = $.ajax({url:fileStr, async:false}).responseText;
356 System.out.println(data);
357 dataIn = Rdr.getBR(data);
361 else if (sourceType == DataSourceType.URL)
367 checkURLSource(fileStr);
368 if (suffixSeparator == '#')
370 extractSuffix(fileStr); // URL lref is stored for later reference.
372 } catch (IOException e)
374 String suffixLess = extractSuffix(fileStr);
375 if (suffixLess == null)
383 checkURLSource(suffixLess);
384 } catch (IOException e2)
386 errormessage = "BAD URL WITH OR WITHOUT SUFFIX";
387 throw (e); // just pass back original - everything was wrong.
391 } catch (Exception e)
393 errormessage = "CANNOT ACCESS DATA AT URL '" + fileStr + "' ("
394 + e.getMessage() + ")";
398 else if (sourceType == DataSourceType.PASTE)
400 errormessage = "PASTE INACCESSIBLE!";
401 dataIn = new BufferedReader(new StringReader(fileStr));
404 else if (sourceType == DataSourceType.CLASSLOADER)
406 errormessage = "RESOURCE CANNOT BE LOCATED";
407 java.io.InputStream is = getClass()
408 .getResourceAsStream("/" + fileStr);
411 String suffixLess = extractSuffix(fileStr);
412 if (suffixLess != null)
414 is = getClass().getResourceAsStream("/" + suffixLess);
419 dataIn = new BufferedReader(new java.io.InputStreamReader(is));
429 errormessage = "PROBABLE IMPLEMENTATION ERROR : Datasource Type given as '"
430 + (sourceType != null ? sourceType : "null") + "'";
433 if (dataIn == null || error)
435 // pass up the reason why we have no source to read from
436 throw new IOException(MessageManager.formatMessage(
437 "exception.failed_to_read_data_from_source", new String[]
441 dataIn.mark(READAHEAD_LIMIT);
445 * mark the current position in the source as start for the purposes of it
446 * being analysed by IdentifyFile().identify
448 * @throws IOException
450 public void mark() throws IOException
454 dataIn.mark(READAHEAD_LIMIT);
458 throw new IOException(
459 MessageManager.getString("exception.no_init_source_stream"));
463 public String nextLine() throws IOException
467 return dataIn.readLine();
469 throw new IOException(MessageManager
470 .formatMessage("exception.invalid_source_stream", new String[]
476 * @return true if this FileParse is configured for Export only
478 public boolean isExporting()
480 return !error && dataIn == null;
485 * @return true if the data source is valid
487 public boolean isValid()
493 * closes the datasource and tidies up. source will be left in an error state
495 public void close() throws IOException
497 errormessage = "EXCEPTION ON CLOSE";
501 errormessage = "SOURCE IS CLOSED";
505 * Rewinds the datasource to the marked point if possible
510 public void reset(int bytesRead) throws IOException
512 if (bytesRead >= READAHEAD_LIMIT)
514 System.err.println(String.format(
515 "File reset error: read %d bytes but reset limit is %d",
516 bytesRead, READAHEAD_LIMIT));
518 if (dataIn != null && !error)
524 throw new IOException(MessageManager.getString(
525 "error.implementation_error_reset_called_for_invalid_source"));
531 * @return true if there is a warning for the user
533 public boolean hasWarningMessage()
535 return (warningMessage != null && warningMessage.length() > 0);
540 * @return empty string or warning message about file that was just parsed.
542 public String getWarningMessage()
544 return warningMessage;
547 public String getInFile()
551 return inFile.getAbsolutePath() + " (" + index + ")";
555 return "From Paste + (" + index + ")";
560 * @return the dataName
562 public String getDataName()
568 * set the (human readable) name or URI for this datasource
572 protected void setDataName(String dataname)
578 * get the underlying bufferedReader for this data source.
580 * @return null if no reader available
581 * @throws IOException
583 public Reader getReader()
585 if (dataIn != null) // Probably don't need to test for readiness &&
593 public AlignViewportI getViewport()
598 public void setViewport(AlignViewportI viewport)
600 this.viewport = viewport;
604 * @return the currently configured exportSettings for writing data.
606 public AlignExportSettingI getExportSettings()
608 return exportSettings;
612 * Set configuration for export of data.
614 * @param exportSettings
615 * the exportSettings to set
617 public void setExportSettings(AlignExportSettingI exportSettings)
619 this.exportSettings = exportSettings;
623 * method overridden by complex file exporter/importers which support
624 * exporting visualisation and layout settings for a view
628 public void configureForView(AlignmentViewPanel avpanel)
632 setViewport(avpanel.getAlignViewport());
634 // could also set export/import settings
638 * Returns the preferred feature colour configuration if there is one, else
643 public FeatureSettingsModelI getFeatureColourScheme()
648 public DataSourceType getDataSourceType()
650 return dataSourceType;