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.
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.List;
27 import java.util.Locale;
29 import jalview.api.AlignExportSettingsI;
30 import jalview.api.AlignmentViewPanel;
31 import jalview.datamodel.Alignment;
32 import jalview.datamodel.AlignmentAnnotation;
33 import jalview.datamodel.AlignmentI;
34 import jalview.datamodel.AlignmentView;
35 import jalview.datamodel.PDBEntry.Type;
36 import jalview.datamodel.SequenceI;
37 import jalview.ext.jmol.JmolParser;
38 import jalview.structure.StructureImportSettings;
39 import jalview.structure.StructureImportSettings.TFType;
40 import jalview.util.Platform;
43 * A low level class for alignment and feature IO with alignment formatting
44 * methods used by both applet and application for generating flat alignment
45 * files. It also holds the lists of magic format names that the applet and
46 * application will allow the user to read or write files with.
51 public class AppletFormatAdapter
53 private AlignmentViewPanel viewpanel;
56 * add jalview-derived non-secondary structure annotation from PDB structure
58 boolean annotFromStructure = false;
61 * add secondary structure from PDB data with built-in algorithms
63 boolean localSecondaryStruct = false;
66 * process PDB data with web services
68 boolean serviceSecondaryStruct = false;
70 private AlignmentFileReaderI alignFile = null;
75 * character used to write newlines
77 protected String newline = System.getProperty("line.separator");
79 private AlignExportSettingsI exportSettings;
81 private File selectedFile;
83 public static String INVALID_CHARACTERS = "Contains invalid characters";
86 * Returns an error message with a list of supported readable file formats
90 public static String getSupportedFormats()
92 return "Formats currently supported are\n"
93 + prettyPrint(FileFormats.getInstance().getReadableFormats());
96 public AppletFormatAdapter()
100 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
102 this.viewpanel = viewpanel;
105 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
106 AlignExportSettingsI settings)
108 viewpanel = alignPanel;
109 exportSettings = settings;
113 * Formats a grammatically correct(ish) list consisting of the given objects
118 public static String prettyPrint(List<? extends Object> things)
120 StringBuffer list = new StringBuffer();
121 for (int i = 0, iSize = things.size() - 1; i < iSize; i++)
123 list.append(things.get(i).toString());
126 // could i18n 'and' here
127 list.append(" and " + things.get(things.size() - 1).toString() + ".");
128 return list.toString();
131 public void setNewlineString(String nl)
136 public String getNewlineString()
142 * Constructs the correct filetype parser for a characterised datasource
152 public AlignmentI readFile(String file, DataSourceType sourceType,
153 FileFormatI fileFormat) throws IOException
155 return readFile(null, file, sourceType, fileFormat);
158 public AlignmentI readFile(File selectedFile, String file,
159 DataSourceType sourceType, FileFormatI fileFormat)
162 return readFile(selectedFile, file, sourceType, fileFormat, null);
165 public AlignmentI readFile(File selectedFile, String file,
166 DataSourceType sourceType, FileFormatI fileFormat,
167 StructureImportSettings.TFType tempfacType) throws IOException
170 this.selectedFile = selectedFile;
171 if (selectedFile != null)
173 this.inFile = selectedFile.getPath();
178 if (fileFormat.isStructureFile())
180 String structureParser = StructureImportSettings
181 .getDefaultPDBFileParser();
182 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
183 StructureImportSettings.StructureParser.JMOL_PARSER
185 StructureImportSettings.addSettings(annotFromStructure,
186 localSecondaryStruct, serviceSecondaryStruct);
189 // needs a File option
190 alignFile = new JmolParser(
191 selectedFile == null ? inFile : selectedFile, sourceType,
196 // todo is mc_view parsing obsolete yet? JAL-2120
197 StructureImportSettings.setShowSeqFeatures(true);
198 alignFile = new mc_view.PDBfile(annotFromStructure,
199 localSecondaryStruct, serviceSecondaryStruct, inFile,
202 ((StructureFile) alignFile).setDbRefType(
203 FileFormat.PDB.equals(fileFormat) ? Type.PDB : Type.MMCIF);
205 else if (selectedFile != null)
207 alignFile = fileFormat
208 .getReader(new FileParse(selectedFile, sourceType));
212 // alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
213 alignFile = fileFormat.getReader(new FileParse(inFile, sourceType));
215 return buildAlignmentFromFile();
216 } catch (Exception e)
219 System.err.println("Failed to read alignment using the '" + fileFormat
220 + "' reader.\n" + e);
222 if (e.getMessage() != null
223 && e.getMessage().startsWith(INVALID_CHARACTERS))
225 throw new IOException(e.getMessage());
228 // Finally test if the user has pasted just the sequence, no id
229 if (sourceType == DataSourceType.PASTE)
233 // Possible sequence is just residues with no label
234 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
235 DataSourceType.PASTE);
236 return buildAlignmentFromFile();
238 } catch (Exception ex)
240 if (ex.toString().startsWith(INVALID_CHARACTERS))
242 throw new IOException(e.getMessage());
245 ex.printStackTrace();
248 if (FileFormat.Html.equals(fileFormat))
250 throw new IOException(e.getMessage());
253 throw new FileFormatException(getSupportedFormats());
257 * Constructs the correct filetype parser for an already open datasource
260 * an existing datasource
262 * File format of data that will be provided by datasource
266 public AlignmentI readFromFile(FileParse source, FileFormatI format)
269 this.inFile = source.getInFile();
270 DataSourceType type = source.dataSourceType;
273 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
275 // TODO obtain config value from preference settings
276 boolean isParseWithJMOL = false;
279 StructureImportSettings.addSettings(annotFromStructure,
280 localSecondaryStruct, serviceSecondaryStruct);
281 alignFile = new JmolParser(source);
285 StructureImportSettings.setShowSeqFeatures(true);
286 alignFile = new mc_view.PDBfile(annotFromStructure,
287 localSecondaryStruct, serviceSecondaryStruct, source);
289 ((StructureFile) alignFile).setDbRefType(Type.PDB);
293 alignFile = format.getReader(source);
296 return buildAlignmentFromFile();
298 } catch (Exception e)
301 System.err.println("Failed to read alignment using the '" + format
302 + "' reader.\n" + e);
304 if (e.getMessage() != null
305 && e.getMessage().startsWith(INVALID_CHARACTERS))
307 throw new FileFormatException(e.getMessage());
310 // Finally test if the user has pasted just the sequence, no id
311 if (type == DataSourceType.PASTE)
315 // Possible sequence is just residues with no label
316 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
317 DataSourceType.PASTE);
318 return buildAlignmentFromFile();
320 } catch (Exception ex)
322 if (ex.toString().startsWith(INVALID_CHARACTERS))
324 throw new IOException(e.getMessage());
327 ex.printStackTrace();
331 // If we get to this stage, the format was not supported
332 throw new FileFormatException(getSupportedFormats());
337 * boilerplate method to handle data from an AlignFile and construct a new
338 * alignment or import to an existing alignment
340 * @return AlignmentI instance ready to pass to a UI constructor
342 private AlignmentI buildAlignmentFromFile()
344 // Standard boilerplate for creating alignment from parser
345 // alignFile.configureForView(viewpanel);
347 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
349 alignFile.addAnnotations(al);
351 alignFile.addGroups(al);
357 * create an alignment flatfile from a Jalview alignment view
362 * @param selectedOnly
363 * @return flatfile in a string
365 public String formatSequences(FileFormatI format, boolean jvsuffix,
366 AlignmentViewPanel ap, boolean selectedOnly)
369 AlignmentView selvew = ap.getAlignViewport()
370 .getAlignmentView(selectedOnly, false);
371 AlignmentI aselview = selvew
372 .getVisibleAlignment(ap.getAlignViewport().getGapCharacter());
373 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
374 .getVisibleAlignmentAnnotation(selectedOnly));
377 for (AlignmentAnnotation aa : ala)
379 aselview.addAnnotation(aa);
383 return formatSequences(format, aselview, jvsuffix);
387 * Construct an output class for an alignment in a particular filetype TODO:
388 * allow caller to detect errors and warnings encountered when generating
392 * string name of alignment format
394 * the alignment to be written out
396 * passed to AlnFile class controls whether /START-END is added to
399 * @return alignment flat file contents
401 public String formatSequences(FileFormatI format, AlignmentI alignment,
406 AlignmentFileWriterI afile = format.getWriter(alignment);
408 afile.setNewlineString(newline);
409 afile.setExportSettings(exportSettings);
410 afile.configureForView(viewpanel);
412 // check whether we were given a specific alignment to export, rather than
413 // the one in the viewpanel
414 SequenceI[] seqs = null;
415 if (viewpanel == null || viewpanel.getAlignment() == null
416 || viewpanel.getAlignment() != alignment)
418 seqs = alignment.getSequencesArray();
422 seqs = viewpanel.getAlignment().getSequencesArray();
425 String afileresp = afile.print(seqs, jvsuffix);
426 if (afile.hasWarningMessage())
428 System.err.println("Warning raised when writing as " + format
429 + " : " + afile.getWarningMessage());
432 } catch (Exception e)
434 System.err.println("Failed to write alignment as a '"
435 + format.getName() + "' file\n");
443 * Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
446 * BH 2018 allows File or String, and can return RELATIVE_URL
450 * @return the protocol for the input data
452 public static DataSourceType checkProtocol(Object dataObject)
454 if (dataObject instanceof File)
456 return DataSourceType.FILE;
459 String data = dataObject.toString();
460 DataSourceType protocol = DataSourceType.PASTE;
461 String ft = data.toLowerCase(Locale.ROOT).trim();
462 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
463 || ft.indexOf("file:") == 0)
465 protocol = DataSourceType.URL;
467 else if (Platform.isJS())
469 protocol = DataSourceType.RELATIVE_URL;
471 else if (new File(data).exists())
473 protocol = DataSourceType.FILE;
482 public static void main(String[] args)
485 while (i < args.length)
487 File f = new File(args[i]);
492 System.out.println("Reading file: " + f);
493 AppletFormatAdapter afa = new AppletFormatAdapter();
494 Runtime r = Runtime.getRuntime();
496 long memf = -r.totalMemory() + r.freeMemory();
497 long t1 = -System.currentTimeMillis();
498 AlignmentI al = afa.readFile(args[i], DataSourceType.FILE,
499 new IdentifyFile().identify(args[i],
500 DataSourceType.FILE));
501 t1 += System.currentTimeMillis();
503 memf += r.totalMemory() - r.freeMemory();
506 System.out.println("Alignment contains " + al.getHeight()
507 + " sequences and " + al.getWidth() + " columns.");
510 System.out.println(new AppletFormatAdapter()
511 .formatSequences(FileFormat.Fasta, al, true));
512 } catch (Exception e)
515 "Couln't format the alignment for output as a FASTA file.");
516 e.printStackTrace(System.err);
521 System.out.println("Couldn't read alignment");
523 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
525 "Difference between free memory now and before is "
526 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
527 } catch (Exception e)
529 System.err.println("Exception when dealing with " + i
530 + "'th argument: " + args[i] + "\n" + e);
535 System.err.println("Ignoring argument '" + args[i] + "' (" + i
536 + "'th)- not a readable file.");
543 * try to discover how to access the given file as a valid datasource that
544 * will be identified as the given type.
548 * @return protocol that yields the data parsable as the given type
550 public static DataSourceType resolveProtocol(String file,
553 return resolveProtocol(file, format, false);
556 public static DataSourceType resolveProtocol(String file,
557 FileFormatI format, boolean debug)
559 // TODO: test thoroughly!
560 DataSourceType protocol = null;
563 System.out.println("resolving datasource started with:\n>>file\n"
564 + file + ">>endfile");
567 // This might throw a security exception in certain browsers
568 // Netscape Communicator for instance.
572 InputStream is = System.getSecurityManager().getClass()
573 .getResourceAsStream("/" + file);
581 System.err.println("Resource '" + file + "' was "
582 + (rtn ? "" : "not") + " located by classloader.");
586 protocol = DataSourceType.CLASSLOADER;
589 } catch (Exception ex)
592 .println("Exception checking resources: " + file + " " + ex);
595 if (file.indexOf("://") > -1)
597 protocol = DataSourceType.URL;
601 // skipping codebase prepend check.
602 protocol = DataSourceType.FILE;
610 "Trying to get contents of resource as " + protocol + ":");
612 fp = new FileParse(file, protocol);
621 System.out.println("Successful.");
624 } catch (Exception e)
628 System.err.println("Exception when accessing content: " + e);
636 System.out.println("Accessing as paste.");
638 protocol = DataSourceType.PASTE;
642 fp = new FileParse(file, protocol);
647 } catch (Exception e)
649 System.err.println("Failed to access content as paste!");
666 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
667 if (idformat == null)
671 System.out.println("Format not identified. Inaccessible file.");
677 System.out.println("Format identified as " + idformat
678 + "and expected as " + format);
680 if (idformat.equals(format))
684 System.out.println("Protocol identified as " + protocol);
693 .println("File deemed not accessible via " + protocol);
698 } catch (Exception e)
702 System.err.println("File deemed not accessible via " + protocol);
710 public AlignmentFileReaderI getAlignFile()