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.AlignExportSettingI;
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;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.util.List;
40 * A low level class for alignment and feature IO with alignment formatting
41 * methods used by both applet and application for generating flat alignment
42 * files. It also holds the lists of magic format names that the applet and
43 * application will allow the user to read or write files with.
48 public class AppletFormatAdapter
50 private AlignmentViewPanel viewpanel;
53 * add jalview-derived non-secondary structure annotation from PDB structure
55 boolean annotFromStructure = false;
58 * add secondary structure from PDB data with built-in algorithms
60 boolean localSecondaryStruct = false;
63 * process PDB data with web services
65 boolean serviceSecondaryStruct = false;
67 private AlignmentFileReaderI alignFile = null;
72 * character used to write newlines
74 protected String newline = System.getProperty("line.separator");
76 private AlignExportSettingI exportSettings;
78 private File selectedFile;
80 public static String INVALID_CHARACTERS = "Contains invalid characters";
83 * Returns an error message with a list of supported readable file formats
87 public static String getSupportedFormats()
89 return "Formats currently supported are\n"
90 + prettyPrint(FileFormats.getInstance().getReadableFormats());
93 public AppletFormatAdapter()
97 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
99 this.viewpanel = viewpanel;
102 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
103 AlignExportSettingI settings)
105 viewpanel = alignPanel;
106 exportSettings = settings;
110 * Formats a grammatically correct(ish) list consisting of the given objects
115 public static String prettyPrint(List<? extends Object> things)
117 StringBuffer list = new StringBuffer();
118 for (int i = 0, iSize = things.size() - 1; i < iSize; i++)
120 list.append(things.get(i).toString());
123 // could i18n 'and' here
124 list.append(" and " + things.get(things.size() - 1).toString() + ".");
125 return list.toString();
128 public void setNewlineString(String nl)
133 public String getNewlineString()
139 * Constructs the correct filetype parser for a characterised datasource
149 public AlignmentI readFile(String file, DataSourceType sourceType,
150 FileFormatI fileFormat) throws IOException
152 return readFile(null, file, sourceType, fileFormat);
155 public AlignmentI readFile(File selectedFile, String file, DataSourceType sourceType,
156 FileFormatI fileFormat) throws IOException
159 this.selectedFile = selectedFile;
160 if (selectedFile != null)
161 this.inFile = selectedFile.getPath();
165 if (fileFormat.isStructureFile())
167 String structureParser = StructureImportSettings
168 .getDefaultPDBFileParser();
169 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
170 StructureImportSettings.StructureParser.JMOL_PARSER
172 StructureImportSettings.addSettings(annotFromStructure,
173 localSecondaryStruct, serviceSecondaryStruct);
176 // needs a File option
177 alignFile = new JmolParser(selectedFile == null ? inFile : selectedFile, sourceType);
181 // todo is MCview parsing obsolete yet? JAL-2120
182 StructureImportSettings.setShowSeqFeatures(true);
183 alignFile = new MCview.PDBfile(annotFromStructure,
184 localSecondaryStruct, serviceSecondaryStruct, inFile,
187 ((StructureFile) alignFile).setDbRefType(
188 FileFormat.PDB.equals(fileFormat) ? Type.PDB : Type.MMCIF);
190 else if (selectedFile != null) {
191 alignFile = fileFormat.getReader(new FileParse(selectedFile, sourceType));
194 // alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
195 alignFile = fileFormat.getReader(new FileParse(inFile, sourceType));
197 return buildAlignmentFromFile();
198 } catch (Exception e)
201 System.err.println("Failed to read alignment using the '" + fileFormat
202 + "' reader.\n" + e);
204 if (e.getMessage() != null
205 && e.getMessage().startsWith(INVALID_CHARACTERS))
207 throw new IOException(e.getMessage());
210 // Finally test if the user has pasted just the sequence, no id
211 if (sourceType == DataSourceType.PASTE)
215 // Possible sequence is just residues with no label
216 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
217 DataSourceType.PASTE);
218 return buildAlignmentFromFile();
220 } catch (Exception ex)
222 if (ex.toString().startsWith(INVALID_CHARACTERS))
224 throw new IOException(e.getMessage());
227 ex.printStackTrace();
230 if (FileFormat.Html.equals(fileFormat))
232 throw new IOException(e.getMessage());
235 throw new FileFormatException(getSupportedFormats());
239 * Constructs the correct filetype parser for an already open datasource
242 * an existing datasource
244 * File format of data that will be provided by datasource
248 public AlignmentI readFromFile(FileParse source, FileFormatI format)
251 this.inFile = source.getInFile();
252 DataSourceType type = source.dataSourceType;
255 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
257 // TODO obtain config value from preference settings
258 boolean isParseWithJMOL = false;
261 StructureImportSettings.addSettings(annotFromStructure,
262 localSecondaryStruct, serviceSecondaryStruct);
263 alignFile = new JmolParser(source);
267 StructureImportSettings.setShowSeqFeatures(true);
268 alignFile = new MCview.PDBfile(annotFromStructure,
269 localSecondaryStruct, serviceSecondaryStruct, source);
271 ((StructureFile) alignFile).setDbRefType(Type.PDB);
275 alignFile = format.getReader(source);
278 return buildAlignmentFromFile();
280 } catch (Exception e)
283 System.err.println("Failed to read alignment using the '" + format
284 + "' reader.\n" + e);
286 if (e.getMessage() != null
287 && e.getMessage().startsWith(INVALID_CHARACTERS))
289 throw new FileFormatException(e.getMessage());
292 // Finally test if the user has pasted just the sequence, no id
293 if (type == DataSourceType.PASTE)
297 // Possible sequence is just residues with no label
298 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
299 DataSourceType.PASTE);
300 return buildAlignmentFromFile();
302 } catch (Exception ex)
304 if (ex.toString().startsWith(INVALID_CHARACTERS))
306 throw new IOException(e.getMessage());
309 ex.printStackTrace();
313 // If we get to this stage, the format was not supported
314 throw new FileFormatException(getSupportedFormats());
319 * boilerplate method to handle data from an AlignFile and construct a new
320 * alignment or import to an existing alignment
322 * @return AlignmentI instance ready to pass to a UI constructor
324 private AlignmentI buildAlignmentFromFile()
326 // Standard boilerplate for creating alignment from parser
327 // alignFile.configureForView(viewpanel);
329 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
331 alignFile.addAnnotations(al);
333 alignFile.addGroups(al);
339 * create an alignment flatfile from a Jalview alignment view
344 * @param selectedOnly
345 * @return flatfile in a string
347 public String formatSequences(FileFormatI format, boolean jvsuffix,
348 AlignmentViewPanel ap, boolean selectedOnly)
351 AlignmentView selvew = ap.getAlignViewport()
352 .getAlignmentView(selectedOnly, false);
353 AlignmentI aselview = selvew
354 .getVisibleAlignment(ap.getAlignViewport().getGapCharacter());
355 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
356 .getVisibleAlignmentAnnotation(selectedOnly));
359 for (AlignmentAnnotation aa : ala)
361 aselview.addAnnotation(aa);
365 return formatSequences(format, aselview, jvsuffix);
369 * Construct an output class for an alignment in a particular filetype TODO:
370 * allow caller to detect errors and warnings encountered when generating
374 * string name of alignment format
376 * the alignment to be written out
378 * passed to AlnFile class controls whether /START-END is added to
381 * @return alignment flat file contents
383 public String formatSequences(FileFormatI format, AlignmentI alignment,
388 AlignmentFileWriterI afile = format.getWriter(alignment);
390 afile.setNewlineString(newline);
391 afile.setExportSettings(exportSettings);
392 afile.configureForView(viewpanel);
394 // check whether we were given a specific alignment to export, rather than
395 // the one in the viewpanel
396 SequenceI[] seqs = null;
397 if (viewpanel == null || viewpanel.getAlignment() == null
398 || viewpanel.getAlignment() != alignment)
400 seqs = alignment.getSequencesArray();
404 seqs = viewpanel.getAlignment().getSequencesArray();
407 String afileresp = afile.print(seqs, jvsuffix);
408 if (afile.hasWarningMessage())
410 System.err.println("Warning raised when writing as " + format
411 + " : " + afile.getWarningMessage());
414 } catch (Exception e)
416 System.err.println("Failed to write alignment as a '"
417 + format.getName() + "' file\n");
426 * Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
429 * BH 2018 allows File or String, and can return RELATIVE_URL
431 * @param dataObject File or String
432 * @return the protocol for the input data
434 public static DataSourceType checkProtocol(Object dataObject)
436 if(dataObject instanceof File)
437 return DataSourceType.FILE;
439 String data = dataObject.toString();
440 DataSourceType protocol = DataSourceType.PASTE;
441 String ft = data.toLowerCase().trim();
442 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
443 || ft.indexOf("file:") == 0)
445 protocol = DataSourceType.URL;
447 else if (jalview.bin.Jalview.isJS)
449 protocol = DataSourceType.RELATIVE_URL;
451 else if (new File(data).exists())
453 protocol = DataSourceType.FILE;
458 public static void main(String[] args)
461 while (i < args.length)
463 File f = new File(args[i]);
468 System.out.println("Reading file: " + f);
469 AppletFormatAdapter afa = new AppletFormatAdapter();
470 Runtime r = Runtime.getRuntime();
472 long memf = -r.totalMemory() + r.freeMemory();
473 long t1 = -System.currentTimeMillis();
474 AlignmentI al = afa.readFile(args[i], DataSourceType.FILE,
475 new IdentifyFile().identify(args[i],
476 DataSourceType.FILE));
477 t1 += System.currentTimeMillis();
479 memf += r.totalMemory() - r.freeMemory();
482 System.out.println("Alignment contains " + al.getHeight()
483 + " sequences and " + al.getWidth() + " columns.");
486 System.out.println(new AppletFormatAdapter()
487 .formatSequences(FileFormat.Fasta, al, true));
488 } catch (Exception e)
491 "Couln't format the alignment for output as a FASTA file.");
492 e.printStackTrace(System.err);
497 System.out.println("Couldn't read alignment");
499 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
501 "Difference between free memory now and before is "
502 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
503 } catch (Exception e)
505 System.err.println("Exception when dealing with " + i
506 + "'th argument: " + args[i] + "\n" + e);
511 System.err.println("Ignoring argument '" + args[i] + "' (" + i
512 + "'th)- not a readable file.");
519 * try to discover how to access the given file as a valid datasource that
520 * will be identified as the given type.
524 * @return protocol that yields the data parsable as the given type
526 public static DataSourceType resolveProtocol(String file,
529 return resolveProtocol(file, format, false);
532 public static DataSourceType resolveProtocol(String file,
533 FileFormatI format, boolean debug)
535 // TODO: test thoroughly!
536 DataSourceType protocol = null;
539 System.out.println("resolving datasource started with:\n>>file\n"
540 + file + ">>endfile");
543 // This might throw a security exception in certain browsers
544 // Netscape Communicator for instance.
548 InputStream is = System.getSecurityManager().getClass()
549 .getResourceAsStream("/" + file);
557 System.err.println("Resource '" + file + "' was "
558 + (rtn ? "" : "not") + " located by classloader.");
562 protocol = DataSourceType.CLASSLOADER;
565 } catch (Exception ex)
568 .println("Exception checking resources: " + file + " " + ex);
571 if (file.indexOf("://") > -1)
573 protocol = DataSourceType.URL;
577 // skipping codebase prepend check.
578 protocol = DataSourceType.FILE;
586 "Trying to get contents of resource as " + protocol + ":");
588 fp = new FileParse(file, protocol);
597 System.out.println("Successful.");
600 } catch (Exception e)
604 System.err.println("Exception when accessing content: " + e);
612 System.out.println("Accessing as paste.");
614 protocol = DataSourceType.PASTE;
618 fp = new FileParse(file, protocol);
623 } catch (Exception e)
625 System.err.println("Failed to access content as paste!");
642 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
643 if (idformat == null)
647 System.out.println("Format not identified. Inaccessible file.");
653 System.out.println("Format identified as " + idformat
654 + "and expected as " + format);
656 if (idformat.equals(format))
660 System.out.println("Protocol identified as " + protocol);
669 .println("File deemed not accessible via " + protocol);
674 } catch (Exception e)
678 System.err.println("File deemed not accessible via " + protocol);
686 public AlignmentFileReaderI getAlignFile()