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.ContactMatrixTest;
30 import jalview.datamodel.PDBEntry.Type;
31 import jalview.datamodel.SequenceI;
32 import jalview.ext.jmol.JmolParser;
33 import jalview.structure.StructureImportSettings;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.util.List;
41 * A low level class for alignment and feature IO with alignment formatting
42 * methods used by both applet and application for generating flat alignment
43 * files. It also holds the lists of magic format names that the applet and
44 * application will allow the user to read or write files with.
49 public class AppletFormatAdapter
51 private AlignmentViewPanel viewpanel;
54 * add jalview-derived non-secondary structure annotation from PDB structure
56 boolean annotFromStructure = false;
59 * add secondary structure from PDB data with built-in algorithms
61 boolean localSecondaryStruct = false;
64 * process PDB data with web services
66 boolean serviceSecondaryStruct = false;
68 private AlignmentFileI alignFile = null;
73 * character used to write newlines
75 protected String newline = System.getProperty("line.separator");
77 private AlignExportSettingI exportSettings;
79 public static String INVALID_CHARACTERS = "Contains invalid characters";
81 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
82 + prettyPrint(FileFormat.getReadableFormats());
84 public AppletFormatAdapter()
88 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
90 this.viewpanel = viewpanel;
93 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
94 AlignExportSettingI settings)
96 viewpanel = alignPanel;
97 exportSettings = settings;
101 * Formats a grammatically correct(ish) list consisting of the given objects
106 public static String prettyPrint(List<? extends Object> things)
108 StringBuffer list = new StringBuffer();
109 for (int i = 0, iSize = things.size() - 1; i < iSize; i++)
111 list.append(things.get(i).toString());
114 // could i18n 'and' here
115 list.append(" and " + things.get(things.size() - 1).toString() + ".");
116 return list.toString();
119 public void setNewlineString(String nl)
124 public String getNewlineString()
130 * Constructs the correct filetype parser for a characterised datasource
140 public AlignmentI readFile(String file, DataSourceType sourceType,
141 FileFormatI fileFormat) throws IOException
146 if (fileFormat.isStructureFile())
148 String structureParser = StructureImportSettings
149 .getDefaultPDBFileParser();
150 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
151 StructureImportSettings.StructureParser.JMOL_PARSER
153 StructureImportSettings.addSettings(annotFromStructure,
154 localSecondaryStruct, serviceSecondaryStruct);
157 alignFile = new JmolParser(inFile, sourceType);
161 // todo is MCview parsing obsolete yet?
162 StructureImportSettings.setShowSeqFeatures(true);
163 alignFile = new MCview.PDBfile(annotFromStructure,
164 localSecondaryStruct, serviceSecondaryStruct, inFile,
167 ((StructureFile) alignFile).setDbRefType(FileFormat.PDB
168 .equals(fileFormat) ? Type.PDB : Type.MMCIF);
172 alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
174 return buildAlignmentFromFile();
175 } catch (Exception e)
178 System.err.println("Failed to read alignment using the '"
179 + fileFormat + "' reader.\n" + e);
181 if (e.getMessage() != null
182 && e.getMessage().startsWith(INVALID_CHARACTERS))
184 throw new IOException(e.getMessage());
187 // Finally test if the user has pasted just the sequence, no id
188 if (sourceType == DataSourceType.PASTE)
192 // Possible sequence is just residues with no label
193 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
194 DataSourceType.PASTE);
195 return buildAlignmentFromFile();
197 } catch (Exception ex)
199 if (ex.toString().startsWith(INVALID_CHARACTERS))
201 throw new IOException(e.getMessage());
204 ex.printStackTrace();
207 if (FileFormat.Html.equals(fileFormat))
209 throw new IOException(e.getMessage());
212 throw new FileFormatException(SUPPORTED_FORMATS);
216 * Constructs the correct filetype parser for an already open datasource
219 * an existing datasource
221 * File format of data that will be provided by datasource
225 public AlignmentI readFromFile(FileParse source, FileFormatI format)
228 this.inFile = source.getInFile();
229 DataSourceType type = source.dataSourceType;
232 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
234 // TODO obtain config value from preference settings
235 boolean isParseWithJMOL = false;
238 StructureImportSettings.addSettings(annotFromStructure,
239 localSecondaryStruct, serviceSecondaryStruct);
240 alignFile = new JmolParser(source);
244 StructureImportSettings.setShowSeqFeatures(true);
245 alignFile = new MCview.PDBfile(annotFromStructure,
246 localSecondaryStruct, serviceSecondaryStruct, source);
248 ((StructureFile) alignFile).setDbRefType(Type.PDB);
252 alignFile = format.getAlignmentFile(source);
255 return buildAlignmentFromFile();
257 } catch (Exception e)
260 System.err.println("Failed to read alignment using the '" + format
261 + "' reader.\n" + e);
263 if (e.getMessage() != null
264 && e.getMessage().startsWith(INVALID_CHARACTERS))
266 throw new FileFormatException(e.getMessage());
269 // Finally test if the user has pasted just the sequence, no id
270 if (type == DataSourceType.PASTE)
274 // Possible sequence is just residues with no label
275 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
276 DataSourceType.PASTE);
277 return buildAlignmentFromFile();
279 } catch (Exception ex)
281 if (ex.toString().startsWith(INVALID_CHARACTERS))
283 throw new IOException(e.getMessage());
286 ex.printStackTrace();
290 // If we get to this stage, the format was not supported
291 throw new FileFormatException(SUPPORTED_FORMATS);
296 * boilerplate method to handle data from an AlignFile and construct a new
297 * alignment or import to an existing alignment
299 * @return AlignmentI instance ready to pass to a UI constructor
301 private AlignmentI buildAlignmentFromFile()
303 // Standard boilerplate for creating alignment from parser
304 // alignFile.configureForView(viewpanel);
306 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
308 alignFile.addAnnotations(al);
310 alignFile.addGroups(al);
312 al.addContactList(new ContactMatrixTest(al.getWidth()));
318 * create an alignment flatfile from a Jalview alignment view
323 * @param selectedOnly
324 * @return flatfile in a string
326 public String formatSequences(FileFormatI format, boolean jvsuffix,
327 AlignmentViewPanel ap, boolean selectedOnly)
330 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
331 selectedOnly, false);
332 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
334 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
335 .getVisibleAlignmentAnnotation(selectedOnly));
338 for (AlignmentAnnotation aa : ala)
340 aselview.addAnnotation(aa);
344 return formatSequences(format, aselview, jvsuffix);
348 * Construct an output class for an alignment in a particular filetype TODO:
349 * allow caller to detect errors and warnings encountered when generating
353 * string name of alignment format
355 * the alignment to be written out
357 * passed to AlnFile class controls whether /START-END is added to
360 * @return alignment flat file contents
362 public String formatSequences(FileFormatI format, AlignmentI alignment,
367 AlignmentFileI afile = format.getAlignmentFile(alignment);
369 afile.setNewlineString(newline);
370 afile.setExportSettings(exportSettings);
371 afile.configureForView(viewpanel);
373 // check whether we were given a specific alignment to export, rather than
374 // the one in the viewpanel
375 SequenceI[] seqs = null;
376 if (viewpanel == null || viewpanel.getAlignment() == null
377 || viewpanel.getAlignment() != alignment)
379 seqs = alignment.getSequencesArray();
383 seqs = viewpanel.getAlignment().getSequencesArray();
386 String afileresp = afile.print(seqs, jvsuffix);
387 if (afile.hasWarningMessage())
389 System.err.println("Warning raised when writing as " + format
390 + " : " + afile.getWarningMessage());
393 } catch (Exception e)
395 System.err.println("Failed to write alignment as a '" + format
403 public static DataSourceType checkProtocol(String file)
405 DataSourceType protocol = DataSourceType.FILE;
406 String ft = file.toLowerCase().trim();
407 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
408 || ft.indexOf("file:") == 0)
410 protocol = DataSourceType.URL;
415 public static void main(String[] args)
418 while (i < args.length)
420 File f = new File(args[i]);
425 System.out.println("Reading file: " + f);
426 AppletFormatAdapter afa = new AppletFormatAdapter();
427 Runtime r = Runtime.getRuntime();
429 long memf = -r.totalMemory() + r.freeMemory();
430 long t1 = -System.currentTimeMillis();
432 .readFile(args[i], DataSourceType.FILE,
433 new IdentifyFile().identify(args[i],
434 DataSourceType.FILE));
435 t1 += System.currentTimeMillis();
437 memf += r.totalMemory() - r.freeMemory();
440 System.out.println("Alignment contains " + al.getHeight()
441 + " sequences and " + al.getWidth() + " columns.");
444 System.out.println(new AppletFormatAdapter().formatSequences(
445 FileFormat.Fasta, al, true));
446 } catch (Exception e)
449 .println("Couln't format the alignment for output as a FASTA file.");
450 e.printStackTrace(System.err);
455 System.out.println("Couldn't read alignment");
457 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
459 .println("Difference between free memory now and before is "
460 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
461 } catch (Exception e)
463 System.err.println("Exception when dealing with " + i
464 + "'th argument: " + args[i] + "\n" + e);
469 System.err.println("Ignoring argument '" + args[i] + "' (" + i
470 + "'th)- not a readable file.");
477 * try to discover how to access the given file as a valid datasource that
478 * will be identified as the given type.
482 * @return protocol that yields the data parsable as the given type
484 public static DataSourceType resolveProtocol(String file,
487 return resolveProtocol(file, format, false);
490 public static DataSourceType resolveProtocol(String file,
491 FileFormatI format, boolean debug)
493 // TODO: test thoroughly!
494 DataSourceType protocol = null;
497 System.out.println("resolving datasource started with:\n>>file\n"
498 + file + ">>endfile");
501 // This might throw a security exception in certain browsers
502 // Netscape Communicator for instance.
506 InputStream is = System.getSecurityManager().getClass()
507 .getResourceAsStream("/" + file);
515 System.err.println("Resource '" + file + "' was "
516 + (rtn ? "" : "not") + " located by classloader.");
520 protocol = DataSourceType.CLASSLOADER;
523 } catch (Exception ex)
526 .println("Exception checking resources: " + file + " " + ex);
529 if (file.indexOf("://") > -1)
531 protocol = DataSourceType.URL;
535 // skipping codebase prepend check.
536 protocol = DataSourceType.FILE;
543 System.out.println("Trying to get contents of resource as "
546 fp = new FileParse(file, protocol);
555 System.out.println("Successful.");
558 } catch (Exception e)
562 System.err.println("Exception when accessing content: " + e);
570 System.out.println("Accessing as paste.");
572 protocol = DataSourceType.PASTE;
576 fp = new FileParse(file, protocol);
581 } catch (Exception e)
583 System.err.println("Failed to access content as paste!");
600 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
601 if (idformat == null)
605 System.out.println("Format not identified. Inaccessible file.");
611 System.out.println("Format identified as " + idformat
612 + "and expected as " + format);
614 if (idformat.equals(format))
618 System.out.println("Protocol identified as " + protocol);
627 .println("File deemed not accessible via " + protocol);
632 } catch (Exception e)
636 System.err.println("File deemed not accessible via " + protocol);
644 public AlignmentFileI getAlignFile()