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.SeqDistanceContactMatrix;
30 import jalview.datamodel.PDBEntry.Type;
31 import jalview.datamodel.SequenceI;
32 import jalview.ext.jmol.JmolParser;
33 import jalview.structure.StructureImportSettings;
34 import jalview.util.Platform;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.util.List;
42 * A low level class for alignment and feature IO with alignment formatting
43 * methods used by both applet and application for generating flat alignment
44 * files. It also holds the lists of magic format names that the applet and
45 * application will allow the user to read or write files with.
50 public class AppletFormatAdapter
52 private AlignmentViewPanel viewpanel;
55 * add jalview-derived non-secondary structure annotation from PDB structure
57 boolean annotFromStructure = false;
60 * add secondary structure from PDB data with built-in algorithms
62 boolean localSecondaryStruct = false;
65 * process PDB data with web services
67 boolean serviceSecondaryStruct = false;
69 private AlignmentFileReaderI alignFile = null;
74 * character used to write newlines
76 protected String newline = System.getProperty("line.separator");
78 private AlignExportSettingsI exportSettings;
80 private File selectedFile;
82 public static String INVALID_CHARACTERS = "Contains invalid characters";
85 * Returns an error message with a list of supported readable file formats
89 public static String getSupportedFormats()
91 return "Formats currently supported are\n"
92 + prettyPrint(FileFormats.getInstance().getReadableFormats());
95 public AppletFormatAdapter()
99 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
101 this.viewpanel = viewpanel;
104 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
105 AlignExportSettingsI settings)
107 viewpanel = alignPanel;
108 exportSettings = settings;
112 * Formats a grammatically correct(ish) list consisting of the given objects
117 public static String prettyPrint(List<? extends Object> things)
119 StringBuffer list = new StringBuffer();
120 for (int i = 0, iSize = things.size() - 1; i < iSize; i++)
122 list.append(things.get(i).toString());
125 // could i18n 'and' here
126 list.append(" and " + things.get(things.size() - 1).toString() + ".");
127 return list.toString();
130 public void setNewlineString(String nl)
135 public String getNewlineString()
141 * Constructs the correct filetype parser for a characterised datasource
151 public AlignmentI readFile(String file, DataSourceType sourceType,
152 FileFormatI fileFormat) throws IOException
154 return readFile(null, file, sourceType, fileFormat);
157 public AlignmentI readFile(File selectedFile, String file, DataSourceType sourceType,
158 FileFormatI fileFormat) throws IOException
161 this.selectedFile = selectedFile;
162 if (selectedFile != null)
164 this.inFile = selectedFile.getPath();
169 if (fileFormat.isStructureFile())
171 String structureParser = StructureImportSettings
172 .getDefaultPDBFileParser();
173 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
174 StructureImportSettings.StructureParser.JMOL_PARSER
176 StructureImportSettings.addSettings(annotFromStructure,
177 localSecondaryStruct, serviceSecondaryStruct);
180 // needs a File option
181 alignFile = new JmolParser(selectedFile == null ? inFile : selectedFile, sourceType);
185 // todo is mc_view parsing obsolete yet? JAL-2120
186 StructureImportSettings.setShowSeqFeatures(true);
187 alignFile = new mc_view.PDBfile(annotFromStructure,
188 localSecondaryStruct, serviceSecondaryStruct, inFile,
191 ((StructureFile) alignFile).setDbRefType(
192 FileFormat.PDB.equals(fileFormat) ? Type.PDB : Type.MMCIF);
194 else if (selectedFile != null) {
195 alignFile = fileFormat.getReader(new FileParse(selectedFile, sourceType));
198 // alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
199 alignFile = fileFormat.getReader(new FileParse(inFile, sourceType));
201 return buildAlignmentFromFile();
202 } catch (Exception e)
205 System.err.println("Failed to read alignment using the '" + fileFormat
206 + "' reader.\n" + e);
208 if (e.getMessage() != null
209 && e.getMessage().startsWith(INVALID_CHARACTERS))
211 throw new IOException(e.getMessage());
214 // Finally test if the user has pasted just the sequence, no id
215 if (sourceType == DataSourceType.PASTE)
219 // Possible sequence is just residues with no label
220 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
221 DataSourceType.PASTE);
222 return buildAlignmentFromFile();
224 } catch (Exception ex)
226 if (ex.toString().startsWith(INVALID_CHARACTERS))
228 throw new IOException(e.getMessage());
231 ex.printStackTrace();
234 if (FileFormat.Html.equals(fileFormat))
236 throw new IOException(e.getMessage());
239 throw new FileFormatException(getSupportedFormats());
243 * Constructs the correct filetype parser for an already open datasource
246 * an existing datasource
248 * File format of data that will be provided by datasource
252 public AlignmentI readFromFile(FileParse source, FileFormatI format)
255 this.inFile = source.getInFile();
256 DataSourceType type = source.dataSourceType;
259 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
261 // TODO obtain config value from preference settings
262 boolean isParseWithJMOL = false;
265 StructureImportSettings.addSettings(annotFromStructure,
266 localSecondaryStruct, serviceSecondaryStruct);
267 alignFile = new JmolParser(source);
271 StructureImportSettings.setShowSeqFeatures(true);
272 alignFile = new mc_view.PDBfile(annotFromStructure,
273 localSecondaryStruct, serviceSecondaryStruct, source);
275 ((StructureFile) alignFile).setDbRefType(Type.PDB);
279 alignFile = format.getReader(source);
282 return buildAlignmentFromFile();
284 } catch (Exception e)
287 System.err.println("Failed to read alignment using the '" + format
288 + "' reader.\n" + e);
290 if (e.getMessage() != null
291 && e.getMessage().startsWith(INVALID_CHARACTERS))
293 throw new FileFormatException(e.getMessage());
296 // Finally test if the user has pasted just the sequence, no id
297 if (type == DataSourceType.PASTE)
301 // Possible sequence is just residues with no label
302 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
303 DataSourceType.PASTE);
304 return buildAlignmentFromFile();
306 } catch (Exception ex)
308 if (ex.toString().startsWith(INVALID_CHARACTERS))
310 throw new IOException(e.getMessage());
313 ex.printStackTrace();
317 // If we get to this stage, the format was not supported
318 throw new FileFormatException(getSupportedFormats());
323 * boilerplate method to handle data from an AlignFile and construct a new
324 * alignment or import to an existing alignment
326 * @return AlignmentI instance ready to pass to a UI constructor
328 private AlignmentI buildAlignmentFromFile()
330 // Standard boilerplate for creating alignment from parser
331 // alignFile.configureForView(viewpanel);
333 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
335 alignFile.addAnnotations(al);
337 alignFile.addGroups(al);
339 al.addContactList(new SeqDistanceContactMatrix(al.getWidth()));
345 * create an alignment flatfile from a Jalview alignment view
350 * @param selectedOnly
351 * @return flatfile in a string
353 public String formatSequences(FileFormatI format, boolean jvsuffix,
354 AlignmentViewPanel ap, boolean selectedOnly)
357 AlignmentView selvew = ap.getAlignViewport()
358 .getAlignmentView(selectedOnly, false);
359 AlignmentI aselview = selvew
360 .getVisibleAlignment(ap.getAlignViewport().getGapCharacter());
361 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
362 .getVisibleAlignmentAnnotation(selectedOnly));
365 for (AlignmentAnnotation aa : ala)
367 aselview.addAnnotation(aa);
371 return formatSequences(format, aselview, jvsuffix);
375 * Construct an output class for an alignment in a particular filetype TODO:
376 * allow caller to detect errors and warnings encountered when generating
380 * string name of alignment format
382 * the alignment to be written out
384 * passed to AlnFile class controls whether /START-END is added to
387 * @return alignment flat file contents
389 public String formatSequences(FileFormatI format, AlignmentI alignment,
394 AlignmentFileWriterI afile = format.getWriter(alignment);
396 afile.setNewlineString(newline);
397 afile.setExportSettings(exportSettings);
398 afile.configureForView(viewpanel);
400 // check whether we were given a specific alignment to export, rather than
401 // the one in the viewpanel
402 SequenceI[] seqs = null;
403 if (viewpanel == null || viewpanel.getAlignment() == null
404 || viewpanel.getAlignment() != alignment)
406 seqs = alignment.getSequencesArray();
410 seqs = viewpanel.getAlignment().getSequencesArray();
413 String afileresp = afile.print(seqs, jvsuffix);
414 if (afile.hasWarningMessage())
416 System.err.println("Warning raised when writing as " + format
417 + " : " + afile.getWarningMessage());
420 } catch (Exception e)
422 System.err.println("Failed to write alignment as a '"
423 + format.getName() + "' file\n");
432 * Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
435 * BH 2018 allows File or String, and can return RELATIVE_URL
437 * @param dataObject File or String
438 * @return the protocol for the input data
440 public static DataSourceType checkProtocol(Object dataObject)
442 if(dataObject instanceof File)
444 return DataSourceType.FILE;
447 String data = dataObject.toString();
448 DataSourceType protocol = DataSourceType.PASTE;
449 String ft = data.toLowerCase().trim();
450 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
451 || ft.indexOf("file:") == 0)
453 protocol = DataSourceType.URL;
455 else if (Platform.isJS())
457 protocol = DataSourceType.RELATIVE_URL;
459 else if (new File(data).exists())
461 protocol = DataSourceType.FILE;
470 public static void main(String[] args)
473 while (i < args.length)
475 File f = new File(args[i]);
480 System.out.println("Reading file: " + f);
481 AppletFormatAdapter afa = new AppletFormatAdapter();
482 Runtime r = Runtime.getRuntime();
484 long memf = -r.totalMemory() + r.freeMemory();
485 long t1 = -System.currentTimeMillis();
486 AlignmentI al = afa.readFile(args[i], DataSourceType.FILE,
487 new IdentifyFile().identify(args[i],
488 DataSourceType.FILE));
489 t1 += System.currentTimeMillis();
491 memf += r.totalMemory() - r.freeMemory();
494 System.out.println("Alignment contains " + al.getHeight()
495 + " sequences and " + al.getWidth() + " columns.");
498 System.out.println(new AppletFormatAdapter()
499 .formatSequences(FileFormat.Fasta, al, true));
500 } catch (Exception e)
503 "Couln't format the alignment for output as a FASTA file.");
504 e.printStackTrace(System.err);
509 System.out.println("Couldn't read alignment");
511 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
513 "Difference between free memory now and before is "
514 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
515 } catch (Exception e)
517 System.err.println("Exception when dealing with " + i
518 + "'th argument: " + args[i] + "\n" + e);
523 System.err.println("Ignoring argument '" + args[i] + "' (" + i
524 + "'th)- not a readable file.");
531 * try to discover how to access the given file as a valid datasource that
532 * will be identified as the given type.
536 * @return protocol that yields the data parsable as the given type
538 public static DataSourceType resolveProtocol(String file,
541 return resolveProtocol(file, format, false);
544 public static DataSourceType resolveProtocol(String file,
545 FileFormatI format, boolean debug)
547 // TODO: test thoroughly!
548 DataSourceType protocol = null;
551 System.out.println("resolving datasource started with:\n>>file\n"
552 + file + ">>endfile");
555 // This might throw a security exception in certain browsers
556 // Netscape Communicator for instance.
560 InputStream is = System.getSecurityManager().getClass()
561 .getResourceAsStream("/" + file);
569 System.err.println("Resource '" + file + "' was "
570 + (rtn ? "" : "not") + " located by classloader.");
574 protocol = DataSourceType.CLASSLOADER;
577 } catch (Exception ex)
580 .println("Exception checking resources: " + file + " " + ex);
583 if (file.indexOf("://") > -1)
585 protocol = DataSourceType.URL;
589 // skipping codebase prepend check.
590 protocol = DataSourceType.FILE;
598 "Trying to get contents of resource as " + protocol + ":");
600 fp = new FileParse(file, protocol);
609 System.out.println("Successful.");
612 } catch (Exception e)
616 System.err.println("Exception when accessing content: " + e);
624 System.out.println("Accessing as paste.");
626 protocol = DataSourceType.PASTE;
630 fp = new FileParse(file, protocol);
635 } catch (Exception e)
637 System.err.println("Failed to access content as paste!");
654 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
655 if (idformat == null)
659 System.out.println("Format not identified. Inaccessible file.");
665 System.out.println("Format identified as " + idformat
666 + "and expected as " + format);
668 if (idformat.equals(format))
672 System.out.println("Protocol identified as " + protocol);
681 .println("File deemed not accessible via " + protocol);
686 } catch (Exception e)
690 System.err.println("File deemed not accessible via " + protocol);
698 public AlignmentFileReaderI getAlignFile()