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 java.util.Locale;
25 import jalview.api.AlignExportSettingsI;
26 import jalview.api.AlignmentViewPanel;
27 import jalview.datamodel.Alignment;
28 import jalview.datamodel.AlignmentAnnotation;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.AlignmentView;
31 import jalview.datamodel.SeqDistanceContactMatrix;
32 import jalview.datamodel.PDBEntry.Type;
33 import jalview.datamodel.SequenceI;
34 import jalview.ext.jmol.JmolParser;
35 import jalview.structure.StructureImportSettings;
36 import jalview.util.Platform;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.util.List;
44 * A low level class for alignment and feature IO with alignment formatting
45 * methods used by both applet and application for generating flat alignment
46 * files. It also holds the lists of magic format names that the applet and
47 * application will allow the user to read or write files with.
52 public class AppletFormatAdapter
54 private AlignmentViewPanel viewpanel;
57 * add jalview-derived non-secondary structure annotation from PDB structure
59 boolean annotFromStructure = false;
62 * add secondary structure from PDB data with built-in algorithms
64 boolean localSecondaryStruct = false;
67 * process PDB data with web services
69 boolean serviceSecondaryStruct = false;
71 private AlignmentFileReaderI alignFile = null;
76 * character used to write newlines
78 protected String newline = System.getProperty("line.separator");
80 private AlignExportSettingsI exportSettings;
82 private File selectedFile;
84 public static String INVALID_CHARACTERS = "Contains invalid characters";
87 * Returns an error message with a list of supported readable file formats
91 public static String getSupportedFormats()
93 return "Formats currently supported are\n"
94 + prettyPrint(FileFormats.getInstance().getReadableFormats());
97 public AppletFormatAdapter()
101 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
103 this.viewpanel = viewpanel;
106 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
107 AlignExportSettingsI settings)
109 viewpanel = alignPanel;
110 exportSettings = settings;
114 * Formats a grammatically correct(ish) list consisting of the given objects
119 public static String prettyPrint(List<? extends Object> things)
121 StringBuffer list = new StringBuffer();
122 for (int i = 0, iSize = things.size() - 1; i < iSize; i++)
124 list.append(things.get(i).toString());
127 // could i18n 'and' here
128 list.append(" and " + things.get(things.size() - 1).toString() + ".");
129 return list.toString();
132 public void setNewlineString(String nl)
137 public String getNewlineString()
143 * Constructs the correct filetype parser for a characterised datasource
153 public AlignmentI readFile(String file, DataSourceType sourceType,
154 FileFormatI fileFormat) throws IOException
156 return readFile(null, file, sourceType, fileFormat);
159 public AlignmentI readFile(File selectedFile, String file,
160 DataSourceType sourceType, FileFormatI fileFormat)
164 this.selectedFile = selectedFile;
165 if (selectedFile != null)
167 this.inFile = selectedFile.getPath();
172 if (fileFormat.isStructureFile())
174 String structureParser = StructureImportSettings
175 .getDefaultPDBFileParser();
176 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
177 StructureImportSettings.StructureParser.JMOL_PARSER
179 StructureImportSettings.addSettings(annotFromStructure,
180 localSecondaryStruct, serviceSecondaryStruct);
183 // needs a File option
184 alignFile = new JmolParser(
185 selectedFile == null ? inFile : selectedFile, sourceType);
189 // todo is mc_view parsing obsolete yet? JAL-2120
190 StructureImportSettings.setShowSeqFeatures(true);
191 alignFile = new mc_view.PDBfile(annotFromStructure,
192 localSecondaryStruct, serviceSecondaryStruct, inFile,
195 ((StructureFile) alignFile).setDbRefType(
196 FileFormat.PDB.equals(fileFormat) ? Type.PDB : Type.MMCIF);
198 else if (selectedFile != null)
200 alignFile = fileFormat
201 .getReader(new FileParse(selectedFile, sourceType));
205 // alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
206 alignFile = fileFormat.getReader(new FileParse(inFile, sourceType));
208 return buildAlignmentFromFile();
209 } catch (Exception e)
212 System.err.println("Failed to read alignment using the '" + fileFormat
213 + "' reader.\n" + e);
215 if (e.getMessage() != null
216 && e.getMessage().startsWith(INVALID_CHARACTERS))
218 throw new IOException(e.getMessage());
221 // Finally test if the user has pasted just the sequence, no id
222 if (sourceType == DataSourceType.PASTE)
226 // Possible sequence is just residues with no label
227 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
228 DataSourceType.PASTE);
229 return buildAlignmentFromFile();
231 } catch (Exception ex)
233 if (ex.toString().startsWith(INVALID_CHARACTERS))
235 throw new IOException(e.getMessage());
238 ex.printStackTrace();
241 if (FileFormat.Html.equals(fileFormat))
243 throw new IOException(e.getMessage());
246 throw new FileFormatException(getSupportedFormats());
250 * Constructs the correct filetype parser for an already open datasource
253 * an existing datasource
255 * File format of data that will be provided by datasource
259 public AlignmentI readFromFile(FileParse source, FileFormatI format)
262 this.inFile = source.getInFile();
263 DataSourceType type = source.dataSourceType;
266 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
268 // TODO obtain config value from preference settings
269 boolean isParseWithJMOL = false;
272 StructureImportSettings.addSettings(annotFromStructure,
273 localSecondaryStruct, serviceSecondaryStruct);
274 alignFile = new JmolParser(source);
278 StructureImportSettings.setShowSeqFeatures(true);
279 alignFile = new mc_view.PDBfile(annotFromStructure,
280 localSecondaryStruct, serviceSecondaryStruct, source);
282 ((StructureFile) alignFile).setDbRefType(Type.PDB);
286 alignFile = format.getReader(source);
289 return buildAlignmentFromFile();
291 } catch (Exception e)
294 System.err.println("Failed to read alignment using the '" + format
295 + "' reader.\n" + e);
297 if (e.getMessage() != null
298 && e.getMessage().startsWith(INVALID_CHARACTERS))
300 throw new FileFormatException(e.getMessage());
303 // Finally test if the user has pasted just the sequence, no id
304 if (type == DataSourceType.PASTE)
308 // Possible sequence is just residues with no label
309 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
310 DataSourceType.PASTE);
311 return buildAlignmentFromFile();
313 } catch (Exception ex)
315 if (ex.toString().startsWith(INVALID_CHARACTERS))
317 throw new IOException(e.getMessage());
320 ex.printStackTrace();
324 // If we get to this stage, the format was not supported
325 throw new FileFormatException(getSupportedFormats());
330 * boilerplate method to handle data from an AlignFile and construct a new
331 * alignment or import to an existing alignment
333 * @return AlignmentI instance ready to pass to a UI constructor
335 private AlignmentI buildAlignmentFromFile()
337 // Standard boilerplate for creating alignment from parser
338 // alignFile.configureForView(viewpanel);
340 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
342 alignFile.addAnnotations(al);
344 alignFile.addGroups(al);
350 * create an alignment flatfile from a Jalview alignment view
355 * @param selectedOnly
356 * @return flatfile in a string
358 public String formatSequences(FileFormatI format, boolean jvsuffix,
359 AlignmentViewPanel ap, boolean selectedOnly)
362 AlignmentView selvew = ap.getAlignViewport()
363 .getAlignmentView(selectedOnly, false);
364 AlignmentI aselview = selvew
365 .getVisibleAlignment(ap.getAlignViewport().getGapCharacter());
366 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
367 .getVisibleAlignmentAnnotation(selectedOnly));
370 for (AlignmentAnnotation aa : ala)
372 aselview.addAnnotation(aa);
376 return formatSequences(format, aselview, jvsuffix);
380 * Construct an output class for an alignment in a particular filetype TODO:
381 * allow caller to detect errors and warnings encountered when generating
385 * string name of alignment format
387 * the alignment to be written out
389 * passed to AlnFile class controls whether /START-END is added to
392 * @return alignment flat file contents
394 public String formatSequences(FileFormatI format, AlignmentI alignment,
399 AlignmentFileWriterI afile = format.getWriter(alignment);
401 afile.setNewlineString(newline);
402 afile.setExportSettings(exportSettings);
403 afile.configureForView(viewpanel);
405 // check whether we were given a specific alignment to export, rather than
406 // the one in the viewpanel
407 SequenceI[] seqs = null;
408 if (viewpanel == null || viewpanel.getAlignment() == null
409 || viewpanel.getAlignment() != alignment)
411 seqs = alignment.getSequencesArray();
415 seqs = viewpanel.getAlignment().getSequencesArray();
418 String afileresp = afile.print(seqs, jvsuffix);
419 if (afile.hasWarningMessage())
421 System.err.println("Warning raised when writing as " + format
422 + " : " + afile.getWarningMessage());
425 } catch (Exception e)
427 System.err.println("Failed to write alignment as a '"
428 + format.getName() + "' file\n");
436 * Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
439 * BH 2018 allows File or String, and can return RELATIVE_URL
443 * @return the protocol for the input data
445 public static DataSourceType checkProtocol(Object dataObject)
447 if (dataObject instanceof File)
449 return DataSourceType.FILE;
452 String data = dataObject.toString();
453 DataSourceType protocol = DataSourceType.PASTE;
454 String ft = data.toLowerCase(Locale.ROOT).trim();
455 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
456 || ft.indexOf("file:") == 0)
458 protocol = DataSourceType.URL;
460 else if (Platform.isJS())
462 protocol = DataSourceType.RELATIVE_URL;
464 else if (new File(data).exists())
466 protocol = DataSourceType.FILE;
475 public static void main(String[] args)
478 while (i < args.length)
480 File f = new File(args[i]);
485 System.out.println("Reading file: " + f);
486 AppletFormatAdapter afa = new AppletFormatAdapter();
487 Runtime r = Runtime.getRuntime();
489 long memf = -r.totalMemory() + r.freeMemory();
490 long t1 = -System.currentTimeMillis();
491 AlignmentI al = afa.readFile(args[i], DataSourceType.FILE,
492 new IdentifyFile().identify(args[i],
493 DataSourceType.FILE));
494 t1 += System.currentTimeMillis();
496 memf += r.totalMemory() - r.freeMemory();
499 System.out.println("Alignment contains " + al.getHeight()
500 + " sequences and " + al.getWidth() + " columns.");
503 System.out.println(new AppletFormatAdapter()
504 .formatSequences(FileFormat.Fasta, al, true));
505 } catch (Exception e)
508 "Couln't format the alignment for output as a FASTA file.");
509 e.printStackTrace(System.err);
514 System.out.println("Couldn't read alignment");
516 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
518 "Difference between free memory now and before is "
519 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
520 } catch (Exception e)
522 System.err.println("Exception when dealing with " + i
523 + "'th argument: " + args[i] + "\n" + e);
528 System.err.println("Ignoring argument '" + args[i] + "' (" + i
529 + "'th)- not a readable file.");
536 * try to discover how to access the given file as a valid datasource that
537 * will be identified as the given type.
541 * @return protocol that yields the data parsable as the given type
543 public static DataSourceType resolveProtocol(String file,
546 return resolveProtocol(file, format, false);
549 public static DataSourceType resolveProtocol(String file,
550 FileFormatI format, boolean debug)
552 // TODO: test thoroughly!
553 DataSourceType protocol = null;
556 System.out.println("resolving datasource started with:\n>>file\n"
557 + file + ">>endfile");
560 // This might throw a security exception in certain browsers
561 // Netscape Communicator for instance.
565 InputStream is = System.getSecurityManager().getClass()
566 .getResourceAsStream("/" + file);
574 System.err.println("Resource '" + file + "' was "
575 + (rtn ? "" : "not") + " located by classloader.");
579 protocol = DataSourceType.CLASSLOADER;
582 } catch (Exception ex)
585 .println("Exception checking resources: " + file + " " + ex);
588 if (file.indexOf("://") > -1)
590 protocol = DataSourceType.URL;
594 // skipping codebase prepend check.
595 protocol = DataSourceType.FILE;
603 "Trying to get contents of resource as " + protocol + ":");
605 fp = new FileParse(file, protocol);
614 System.out.println("Successful.");
617 } catch (Exception e)
621 System.err.println("Exception when accessing content: " + e);
629 System.out.println("Accessing as paste.");
631 protocol = DataSourceType.PASTE;
635 fp = new FileParse(file, protocol);
640 } catch (Exception e)
642 System.err.println("Failed to access content as paste!");
659 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
660 if (idformat == null)
664 System.out.println("Format not identified. Inaccessible file.");
670 System.out.println("Format identified as " + idformat
671 + "and expected as " + format);
673 if (idformat.equals(format))
677 System.out.println("Protocol identified as " + protocol);
686 .println("File deemed not accessible via " + protocol);
691 } catch (Exception e)
695 System.err.println("File deemed not accessible via " + protocol);
703 public AlignmentFileReaderI getAlignFile()