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.AlignExportSettingsI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.AlignmentView;
29 import jalview.datamodel.PDBEntry.Type;
30 import jalview.datamodel.SequenceI;
31 import jalview.ext.jmol.JmolParser;
32 import jalview.structure.StructureImportSettings;
33 import jalview.util.Platform;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.util.List;
41 * A low level class for alignment and feature IO with alignment formatting
42 * methods used by both applet and application for generating flat alignment
43 * files. It also holds the lists of magic format names that the applet and
44 * application will allow the user to read or write files with.
49 public class AppletFormatAdapter
51 private AlignmentViewPanel viewpanel;
54 * add jalview-derived non-secondary structure annotation from PDB structure
56 boolean annotFromStructure = false;
59 * add secondary structure from PDB data with built-in algorithms
61 boolean localSecondaryStruct = false;
64 * process PDB data with web services
66 boolean serviceSecondaryStruct = false;
68 private AlignmentFileReaderI alignFile = null;
73 * character used to write newlines
75 protected String newline = System.getProperty("line.separator");
77 private AlignExportSettingsI exportSettings;
79 private File selectedFile;
81 public static String INVALID_CHARACTERS = "Contains invalid characters";
84 * Returns an error message with a list of supported readable file formats
88 public static String getSupportedFormats()
90 return "Formats currently supported are\n"
91 + prettyPrint(FileFormats.getInstance().getReadableFormats());
94 public AppletFormatAdapter()
98 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
100 this.viewpanel = viewpanel;
103 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
104 AlignExportSettingsI settings)
106 viewpanel = alignPanel;
107 exportSettings = settings;
111 * Formats a grammatically correct(ish) list consisting of the given objects
116 public static String prettyPrint(List<? extends Object> things)
118 StringBuffer list = new StringBuffer();
119 for (int i = 0, iSize = things.size() - 1; i < iSize; i++)
121 list.append(things.get(i).toString());
124 // could i18n 'and' here
125 list.append(" and " + things.get(things.size() - 1).toString() + ".");
126 return list.toString();
129 public void setNewlineString(String nl)
134 public String getNewlineString()
140 * Constructs the correct filetype parser for a characterised datasource
150 public AlignmentI readFile(String file, DataSourceType sourceType,
151 FileFormatI fileFormat) throws IOException
153 return readFile(null, file, sourceType, fileFormat);
156 public AlignmentI readFile(File selectedFile, String file, DataSourceType sourceType,
157 FileFormatI fileFormat) throws IOException
160 this.selectedFile = selectedFile;
161 if (selectedFile != null)
163 this.inFile = selectedFile.getPath();
168 if (fileFormat.isStructureFile())
170 String structureParser = StructureImportSettings
171 .getDefaultPDBFileParser();
172 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
173 StructureImportSettings.StructureParser.JMOL_PARSER
175 StructureImportSettings.addSettings(annotFromStructure,
176 localSecondaryStruct, serviceSecondaryStruct);
179 // needs a File option
180 alignFile = new JmolParser(selectedFile == null ? inFile : selectedFile, sourceType);
184 // todo is mc_view parsing obsolete yet? JAL-2120
185 StructureImportSettings.setShowSeqFeatures(true);
186 alignFile = new mc_view.PDBfile(annotFromStructure,
187 localSecondaryStruct, serviceSecondaryStruct, inFile,
190 ((StructureFile) alignFile).setDbRefType(
191 FileFormat.PDB.equals(fileFormat) ? Type.PDB : Type.MMCIF);
193 else if (selectedFile != null) {
194 alignFile = fileFormat.getReader(new FileParse(selectedFile, sourceType));
197 // alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
198 alignFile = fileFormat.getReader(new FileParse(inFile, sourceType));
200 return buildAlignmentFromFile();
201 } catch (Exception e)
204 System.err.println("Failed to read alignment using the '" + fileFormat
205 + "' reader.\n" + e);
207 if (e.getMessage() != null
208 && e.getMessage().startsWith(INVALID_CHARACTERS))
210 throw new IOException(e.getMessage());
213 // Finally test if the user has pasted just the sequence, no id
214 if (sourceType == DataSourceType.PASTE)
218 // Possible sequence is just residues with no label
219 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
220 DataSourceType.PASTE);
221 return buildAlignmentFromFile();
223 } catch (Exception ex)
225 if (ex.toString().startsWith(INVALID_CHARACTERS))
227 throw new IOException(e.getMessage());
230 ex.printStackTrace();
233 if (FileFormat.Html.equals(fileFormat))
235 throw new IOException(e.getMessage());
238 throw new FileFormatException(getSupportedFormats());
242 * Constructs the correct filetype parser for an already open datasource
245 * an existing datasource
247 * File format of data that will be provided by datasource
251 public AlignmentI readFromFile(FileParse source, FileFormatI format)
254 this.inFile = source.getInFile();
255 DataSourceType type = source.dataSourceType;
258 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
260 // TODO obtain config value from preference settings
261 boolean isParseWithJMOL = false;
264 StructureImportSettings.addSettings(annotFromStructure,
265 localSecondaryStruct, serviceSecondaryStruct);
266 alignFile = new JmolParser(source);
270 StructureImportSettings.setShowSeqFeatures(true);
271 alignFile = new mc_view.PDBfile(annotFromStructure,
272 localSecondaryStruct, serviceSecondaryStruct, source);
274 ((StructureFile) alignFile).setDbRefType(Type.PDB);
278 alignFile = format.getReader(source);
281 return buildAlignmentFromFile();
283 } catch (Exception e)
286 System.err.println("Failed to read alignment using the '" + format
287 + "' reader.\n" + e);
289 if (e.getMessage() != null
290 && e.getMessage().startsWith(INVALID_CHARACTERS))
292 throw new FileFormatException(e.getMessage());
295 // Finally test if the user has pasted just the sequence, no id
296 if (type == DataSourceType.PASTE)
300 // Possible sequence is just residues with no label
301 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
302 DataSourceType.PASTE);
303 return buildAlignmentFromFile();
305 } catch (Exception ex)
307 if (ex.toString().startsWith(INVALID_CHARACTERS))
309 throw new IOException(e.getMessage());
312 ex.printStackTrace();
316 // If we get to this stage, the format was not supported
317 throw new FileFormatException(getSupportedFormats());
322 * boilerplate method to handle data from an AlignFile and construct a new
323 * alignment or import to an existing alignment
325 * @return AlignmentI instance ready to pass to a UI constructor
327 private AlignmentI buildAlignmentFromFile()
329 // Standard boilerplate for creating alignment from parser
330 // alignFile.configureForView(viewpanel);
332 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
334 alignFile.addAnnotations(al);
336 alignFile.addGroups(al);
342 * create an alignment flatfile from a Jalview alignment view
347 * @param selectedOnly
348 * @return flatfile in a string
350 public String formatSequences(FileFormatI format, boolean jvsuffix,
351 AlignmentViewPanel ap, boolean selectedOnly)
354 AlignmentView selvew = ap.getAlignViewport()
355 .getAlignmentView(selectedOnly, false);
356 AlignmentI aselview = selvew
357 .getVisibleAlignment(ap.getAlignViewport().getGapCharacter());
358 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
359 .getVisibleAlignmentAnnotation(selectedOnly));
362 for (AlignmentAnnotation aa : ala)
364 aselview.addAnnotation(aa);
368 return formatSequences(format, aselview, jvsuffix);
372 * Construct an output class for an alignment in a particular filetype TODO:
373 * allow caller to detect errors and warnings encountered when generating
377 * string name of alignment format
379 * the alignment to be written out
381 * passed to AlnFile class controls whether /START-END is added to
384 * @return alignment flat file contents
386 public String formatSequences(FileFormatI format, AlignmentI alignment,
391 AlignmentFileWriterI afile = format.getWriter(alignment);
393 afile.setNewlineString(newline);
394 afile.setExportSettings(exportSettings);
395 afile.configureForView(viewpanel);
397 // check whether we were given a specific alignment to export, rather than
398 // the one in the viewpanel
399 SequenceI[] seqs = null;
400 if (viewpanel == null || viewpanel.getAlignment() == null
401 || viewpanel.getAlignment() != alignment)
403 seqs = alignment.getSequencesArray();
407 seqs = viewpanel.getAlignment().getSequencesArray();
410 String afileresp = afile.print(seqs, jvsuffix);
411 if (afile.hasWarningMessage())
413 System.err.println("Warning raised when writing as " + format
414 + " : " + afile.getWarningMessage());
417 } catch (Exception e)
419 System.err.println("Failed to write alignment as a '"
420 + format.getName() + "' file\n");
429 * Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
432 * BH 2018 allows File or String, and can return RELATIVE_URL
434 * @param dataObject File or String
435 * @return the protocol for the input data
437 public static DataSourceType checkProtocol(Object dataObject)
439 if(dataObject instanceof File)
441 return DataSourceType.FILE;
444 String data = dataObject.toString();
445 DataSourceType protocol = DataSourceType.PASTE;
446 String ft = data.toLowerCase().trim();
447 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
448 || ft.indexOf("file:") == 0)
450 protocol = DataSourceType.URL;
452 else if (Platform.isJS())
454 protocol = DataSourceType.RELATIVE_URL;
456 else if (new File(data).exists())
458 protocol = DataSourceType.FILE;
467 public static void main(String[] args)
470 while (i < args.length)
472 File f = new File(args[i]);
477 System.out.println("Reading file: " + f);
478 AppletFormatAdapter afa = new AppletFormatAdapter();
479 Runtime r = Runtime.getRuntime();
481 long memf = -r.totalMemory() + r.freeMemory();
482 long t1 = -System.currentTimeMillis();
483 AlignmentI al = afa.readFile(args[i], DataSourceType.FILE,
484 new IdentifyFile().identify(args[i],
485 DataSourceType.FILE));
486 t1 += System.currentTimeMillis();
488 memf += r.totalMemory() - r.freeMemory();
491 System.out.println("Alignment contains " + al.getHeight()
492 + " sequences and " + al.getWidth() + " columns.");
495 System.out.println(new AppletFormatAdapter()
496 .formatSequences(FileFormat.Fasta, al, true));
497 } catch (Exception e)
500 "Couln't format the alignment for output as a FASTA file.");
501 e.printStackTrace(System.err);
506 System.out.println("Couldn't read alignment");
508 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
510 "Difference between free memory now and before is "
511 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
512 } catch (Exception e)
514 System.err.println("Exception when dealing with " + i
515 + "'th argument: " + args[i] + "\n" + e);
520 System.err.println("Ignoring argument '" + args[i] + "' (" + i
521 + "'th)- not a readable file.");
528 * try to discover how to access the given file as a valid datasource that
529 * will be identified as the given type.
533 * @return protocol that yields the data parsable as the given type
535 public static DataSourceType resolveProtocol(String file,
538 return resolveProtocol(file, format, false);
541 public static DataSourceType resolveProtocol(String file,
542 FileFormatI format, boolean debug)
544 // TODO: test thoroughly!
545 DataSourceType protocol = null;
548 System.out.println("resolving datasource started with:\n>>file\n"
549 + file + ">>endfile");
552 // This might throw a security exception in certain browsers
553 // Netscape Communicator for instance.
557 InputStream is = System.getSecurityManager().getClass()
558 .getResourceAsStream("/" + file);
566 System.err.println("Resource '" + file + "' was "
567 + (rtn ? "" : "not") + " located by classloader.");
571 protocol = DataSourceType.CLASSLOADER;
574 } catch (Exception ex)
577 .println("Exception checking resources: " + file + " " + ex);
580 if (file.indexOf("://") > -1)
582 protocol = DataSourceType.URL;
586 // skipping codebase prepend check.
587 protocol = DataSourceType.FILE;
595 "Trying to get contents of resource as " + protocol + ":");
597 fp = new FileParse(file, protocol);
606 System.out.println("Successful.");
609 } catch (Exception e)
613 System.err.println("Exception when accessing content: " + e);
621 System.out.println("Accessing as paste.");
623 protocol = DataSourceType.PASTE;
627 fp = new FileParse(file, protocol);
632 } catch (Exception e)
634 System.err.println("Failed to access content as paste!");
651 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
652 if (idformat == null)
656 System.out.println("Format not identified. Inaccessible file.");
662 System.out.println("Format identified as " + idformat
663 + "and expected as " + format);
665 if (idformat.equals(format))
669 System.out.println("Protocol identified as " + protocol);
678 .println("File deemed not accessible via " + protocol);
683 } catch (Exception e)
687 System.err.println("File deemed not accessible via " + protocol);
695 public AlignmentFileReaderI getAlignFile()