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.util.Platform;
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,
158 DataSourceType sourceType, FileFormatI fileFormat)
161 return readFile(selectedFile, file, sourceType, fileFormat, null);
164 public AlignmentI readFile(File selectedFile, String file,
165 DataSourceType sourceType, FileFormatI fileFormat,
166 StructureImportSettings.TFType tempfacType) throws IOException
169 this.selectedFile = selectedFile;
170 this.inFile = selectedFile != null ? selectedFile.getPath() : file;
173 if (fileFormat.isStructureFile())
175 String structureParser = StructureImportSettings
176 .getDefaultPDBFileParser();
177 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
178 StructureImportSettings.StructureParser.JMOL_PARSER
180 StructureImportSettings.addSettings(annotFromStructure,
181 localSecondaryStruct, serviceSecondaryStruct);
182 if (tempfacType != null)
184 StructureImportSettings.setTemperatureFactorType(tempfacType);
188 // needs a File option
189 alignFile = new JmolParser(
190 selectedFile == null ? inFile : selectedFile, sourceType,
191 StructureImportSettings.getTemperatureFactorType());
195 // todo is mc_view parsing obsolete yet? JAL-2120
196 StructureImportSettings.setShowSeqFeatures(true);
197 alignFile = new mc_view.PDBfile(annotFromStructure,
198 localSecondaryStruct, serviceSecondaryStruct, inFile,
201 ((StructureFile) alignFile).setDbRefType(
202 FileFormat.PDB.equals(fileFormat) ? Type.PDB : Type.MMCIF);
204 else if (selectedFile != null)
206 alignFile = fileFormat
207 .getReader(new FileParse(selectedFile, sourceType));
211 // alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
212 alignFile = fileFormat.getReader(new FileParse(inFile, sourceType));
214 return buildAlignmentFromFile();
215 } catch (Exception e)
218 jalview.bin.Console.errPrintln("Failed to read alignment using the '"
219 + fileFormat + "' reader.\n" + e);
221 if (e.getMessage() != null
222 && e.getMessage().startsWith(INVALID_CHARACTERS))
224 throw new IOException(e.getMessage());
227 // Finally test if the user has pasted just the sequence, no id
228 if (sourceType == DataSourceType.PASTE)
232 // Possible sequence is just residues with no label
233 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
234 DataSourceType.PASTE);
235 return buildAlignmentFromFile();
237 } catch (Exception ex)
239 if (ex.toString().startsWith(INVALID_CHARACTERS))
241 throw new IOException(e.getMessage());
244 ex.printStackTrace();
247 if (FileFormat.Html.equals(fileFormat))
249 throw new IOException(e.getMessage());
252 throw new FileFormatException(getSupportedFormats());
256 * Constructs the correct filetype parser for an already open datasource
259 * an existing datasource
261 * File format of data that will be provided by datasource
265 public AlignmentI readFromFile(FileParse source, FileFormatI format)
268 this.inFile = source.getInFile();
269 DataSourceType type = source.dataSourceType;
272 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
274 // TODO obtain config value from preference settings
275 boolean isParseWithJMOL = false;
278 StructureImportSettings.addSettings(annotFromStructure,
279 localSecondaryStruct, serviceSecondaryStruct);
280 alignFile = new JmolParser(source);
284 StructureImportSettings.setShowSeqFeatures(true);
285 alignFile = new mc_view.PDBfile(annotFromStructure,
286 localSecondaryStruct, serviceSecondaryStruct, source);
288 ((StructureFile) alignFile).setDbRefType(Type.PDB);
292 alignFile = format.getReader(source);
295 return buildAlignmentFromFile();
297 } catch (Exception e)
300 jalview.bin.Console.errPrintln("Failed to read alignment using the '"
301 + format + "' reader.\n" + e);
303 if (e.getMessage() != null
304 && e.getMessage().startsWith(INVALID_CHARACTERS))
306 throw new FileFormatException(e.getMessage());
309 // Finally test if the user has pasted just the sequence, no id
310 if (type == DataSourceType.PASTE)
314 // Possible sequence is just residues with no label
315 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
316 DataSourceType.PASTE);
317 return buildAlignmentFromFile();
319 } catch (Exception ex)
321 if (ex.toString().startsWith(INVALID_CHARACTERS))
323 throw new IOException(e.getMessage());
326 ex.printStackTrace();
330 // If we get to this stage, the format was not supported
331 throw new FileFormatException(getSupportedFormats());
336 * boilerplate method to handle data from an AlignFile and construct a new
337 * alignment or import to an existing alignment
339 * @return AlignmentI instance ready to pass to a UI constructor
341 private AlignmentI buildAlignmentFromFile()
343 // Standard boilerplate for creating alignment from parser
344 // alignFile.configureForView(viewpanel);
346 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
348 alignFile.addAnnotations(al);
350 alignFile.addGroups(al);
356 * create an alignment flatfile from a Jalview alignment view
361 * @param selectedOnly
362 * @return flatfile in a string
364 public String formatSequences(FileFormatI format, boolean jvsuffix,
365 AlignmentViewPanel ap, boolean selectedOnly)
368 AlignmentView selvew = ap.getAlignViewport()
369 .getAlignmentView(selectedOnly, false);
370 AlignmentI aselview = selvew
371 .getVisibleAlignment(ap.getAlignViewport().getGapCharacter());
372 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
373 .getVisibleAlignmentAnnotation(selectedOnly));
376 for (AlignmentAnnotation aa : ala)
378 aselview.addAnnotation(aa);
382 return formatSequences(format, aselview, jvsuffix);
386 * Construct an output class for an alignment in a particular filetype TODO:
387 * allow caller to detect errors and warnings encountered when generating
391 * string name of alignment format
393 * the alignment to be written out
395 * passed to AlnFile class controls whether /START-END is added to
398 * @return alignment flat file contents
400 public String formatSequences(FileFormatI format, AlignmentI alignment,
405 AlignmentFileWriterI afile = format.getWriter(alignment);
407 afile.setNewlineString(newline);
408 afile.setExportSettings(exportSettings);
409 afile.configureForView(viewpanel);
411 // check whether we were given a specific alignment to export, rather than
412 // the one in the viewpanel
413 SequenceI[] seqs = null;
414 if (viewpanel == null || viewpanel.getAlignment() == null
415 || viewpanel.getAlignment() != alignment)
417 seqs = alignment.getSequencesArray();
421 seqs = viewpanel.getAlignment().getSequencesArray();
424 String afileresp = afile.print(seqs, jvsuffix);
425 if (afile.hasWarningMessage())
427 jalview.bin.Console.errPrintln("Warning raised when writing as "
428 + format + " : " + afile.getWarningMessage());
431 } catch (Exception e)
433 jalview.bin.Console.errPrintln("Failed to write alignment as a '"
434 + format.getName() + "' file\n");
442 * Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
445 * BH 2018 allows File or String, and can return RELATIVE_URL
449 * @return the protocol for the input data
451 public static DataSourceType checkProtocol(Object dataObject)
453 if (dataObject instanceof File)
455 return DataSourceType.FILE;
458 String data = dataObject.toString();
459 DataSourceType protocol = DataSourceType.PASTE;
460 String ft = data.toLowerCase(Locale.ROOT).trim();
461 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
462 || ft.indexOf("file:") == 0)
464 protocol = DataSourceType.URL;
466 else if (Platform.isJS())
468 protocol = DataSourceType.RELATIVE_URL;
470 else if (new File(data).exists())
472 protocol = DataSourceType.FILE;
481 public static void main(String[] args)
484 while (i < args.length)
486 File f = new File(args[i]);
491 jalview.bin.Console.outPrintln("Reading file: " + f);
492 AppletFormatAdapter afa = new AppletFormatAdapter();
493 Runtime r = Runtime.getRuntime();
495 long memf = -r.totalMemory() + r.freeMemory();
496 long t1 = -System.currentTimeMillis();
497 AlignmentI al = afa.readFile(args[i], DataSourceType.FILE,
498 new IdentifyFile().identify(args[i],
499 DataSourceType.FILE));
500 t1 += System.currentTimeMillis();
502 memf += r.totalMemory() - r.freeMemory();
505 jalview.bin.Console.outPrintln("Alignment contains "
506 + al.getHeight() + " sequences and " + al.getWidth()
510 jalview.bin.Console.outPrintln(new AppletFormatAdapter()
511 .formatSequences(FileFormat.Fasta, al, true));
512 } catch (Exception e)
514 jalview.bin.Console.errPrintln(
515 "Couln't format the alignment for output as a FASTA file.");
516 e.printStackTrace(System.err);
521 jalview.bin.Console.outPrintln("Couldn't read alignment");
524 .outPrintln("Read took " + (t1 / 1000.0) + " seconds.");
525 jalview.bin.Console.outPrintln(
526 "Difference between free memory now and before is "
527 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
528 } catch (Exception e)
530 jalview.bin.Console.errPrintln("Exception when dealing with " + i
531 + "'th argument: " + args[i] + "\n" + e);
536 jalview.bin.Console.errPrintln("Ignoring argument '" + args[i]
537 + "' (" + i + "'th)- not a readable file.");
544 * try to discover how to access the given file as a valid datasource that
545 * will be identified as the given type.
549 * @return protocol that yields the data parsable as the given type
551 public static DataSourceType resolveProtocol(String file,
554 return resolveProtocol(file, format, false);
557 public static DataSourceType resolveProtocol(String file,
558 FileFormatI format, boolean debug)
560 // TODO: test thoroughly!
561 DataSourceType protocol = null;
565 .outPrintln("resolving datasource started with:\n>>file\n"
566 + file + ">>endfile");
569 // This might throw a security exception in certain browsers
570 // Netscape Communicator for instance.
574 InputStream is = System.getSecurityManager().getClass()
575 .getResourceAsStream("/" + file);
583 jalview.bin.Console.errPrintln("Resource '" + file + "' was "
584 + (rtn ? "" : "not") + " located by classloader.");
588 protocol = DataSourceType.CLASSLOADER;
591 } catch (Exception ex)
594 .println("Exception checking resources: " + file + " " + ex);
597 if (file.indexOf("://") > -1)
599 protocol = DataSourceType.URL;
603 // skipping codebase prepend check.
604 protocol = DataSourceType.FILE;
611 jalview.bin.Console.outPrintln(
612 "Trying to get contents of resource as " + protocol + ":");
614 fp = new FileParse(file, protocol);
623 jalview.bin.Console.outPrintln("Successful.");
626 } catch (Exception e)
631 .errPrintln("Exception when accessing content: " + e);
639 jalview.bin.Console.outPrintln("Accessing as paste.");
641 protocol = DataSourceType.PASTE;
645 fp = new FileParse(file, protocol);
650 } catch (Exception e)
653 .errPrintln("Failed to access content as paste!");
670 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
671 if (idformat == null)
675 jalview.bin.Console.outPrintln(
676 "Format not identified. Inaccessible file.");
682 jalview.bin.Console.outPrintln("Format identified as " + idformat
683 + "and expected as " + format);
685 if (idformat.equals(format))
690 .outPrintln("Protocol identified as " + protocol);
699 .println("File deemed not accessible via " + protocol);
704 } catch (Exception e)
709 .errPrintln("File deemed not accessible via " + protocol);
717 public AlignmentFileReaderI getAlignFile()