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 public static String INVALID_CHARACTERS = "Contains invalid characters";
81 * Returns an error message with a list of supported readable file formats
85 public static String getSupportedFormats()
87 return "Formats currently supported are\n"
88 + prettyPrint(FileFormats.getInstance().getReadableFormats());
90 public AppletFormatAdapter()
94 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
96 this.viewpanel = viewpanel;
99 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
100 AlignExportSettingI settings)
102 viewpanel = alignPanel;
103 exportSettings = settings;
107 * Formats a grammatically correct(ish) list consisting of the given objects
112 public static String prettyPrint(List<? extends Object> things)
114 StringBuffer list = new StringBuffer();
115 for (int i = 0, iSize = things.size() - 1; i < iSize; i++)
117 list.append(things.get(i).toString());
120 // could i18n 'and' here
121 list.append(" and " + things.get(things.size() - 1).toString() + ".");
122 return list.toString();
125 public void setNewlineString(String nl)
130 public String getNewlineString()
136 * Constructs the correct filetype parser for a characterised datasource
146 public AlignmentI readFile(String file, DataSourceType sourceType,
147 FileFormatI fileFormat) throws IOException
152 if (fileFormat.isStructureFile())
154 String structureParser = StructureImportSettings
155 .getDefaultPDBFileParser();
156 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
157 StructureImportSettings.StructureParser.JMOL_PARSER
159 StructureImportSettings.addSettings(annotFromStructure,
160 localSecondaryStruct, serviceSecondaryStruct);
163 alignFile = new JmolParser(inFile, sourceType);
167 // todo is MCview parsing obsolete yet? JAL-2120
168 StructureImportSettings.setShowSeqFeatures(true);
169 alignFile = new MCview.PDBfile(annotFromStructure,
170 localSecondaryStruct, serviceSecondaryStruct, inFile,
173 ((StructureFile) alignFile).setDbRefType(FileFormat.PDB
174 .equals(fileFormat) ? Type.PDB : Type.MMCIF);
178 // alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
179 alignFile = fileFormat.getReader(new FileParse(inFile,
182 return buildAlignmentFromFile();
183 } catch (Exception e)
186 System.err.println("Failed to read alignment using the '"
187 + fileFormat + "' reader.\n" + e);
189 if (e.getMessage() != null
190 && e.getMessage().startsWith(INVALID_CHARACTERS))
192 throw new IOException(e.getMessage());
195 // Finally test if the user has pasted just the sequence, no id
196 if (sourceType == DataSourceType.PASTE)
200 // Possible sequence is just residues with no label
201 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
202 DataSourceType.PASTE);
203 return buildAlignmentFromFile();
205 } catch (Exception ex)
207 if (ex.toString().startsWith(INVALID_CHARACTERS))
209 throw new IOException(e.getMessage());
212 ex.printStackTrace();
215 if (FileFormat.Html.equals(fileFormat))
217 throw new IOException(e.getMessage());
220 throw new FileFormatException(getSupportedFormats());
224 * Constructs the correct filetype parser for an already open datasource
227 * an existing datasource
229 * File format of data that will be provided by datasource
233 public AlignmentI readFromFile(FileParse source, FileFormatI format)
236 this.inFile = source.getInFile();
237 DataSourceType type = source.dataSourceType;
240 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
242 // TODO obtain config value from preference settings
243 boolean isParseWithJMOL = false;
246 StructureImportSettings.addSettings(annotFromStructure,
247 localSecondaryStruct, serviceSecondaryStruct);
248 alignFile = new JmolParser(source);
252 StructureImportSettings.setShowSeqFeatures(true);
253 alignFile = new MCview.PDBfile(annotFromStructure,
254 localSecondaryStruct, serviceSecondaryStruct, source);
256 ((StructureFile) alignFile).setDbRefType(Type.PDB);
260 alignFile = format.getReader(source);
263 return buildAlignmentFromFile();
265 } catch (Exception e)
268 System.err.println("Failed to read alignment using the '" + format
269 + "' reader.\n" + e);
271 if (e.getMessage() != null
272 && e.getMessage().startsWith(INVALID_CHARACTERS))
274 throw new FileFormatException(e.getMessage());
277 // Finally test if the user has pasted just the sequence, no id
278 if (type == DataSourceType.PASTE)
282 // Possible sequence is just residues with no label
283 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
284 DataSourceType.PASTE);
285 return buildAlignmentFromFile();
287 } catch (Exception ex)
289 if (ex.toString().startsWith(INVALID_CHARACTERS))
291 throw new IOException(e.getMessage());
294 ex.printStackTrace();
298 // If we get to this stage, the format was not supported
299 throw new FileFormatException(getSupportedFormats());
304 * boilerplate method to handle data from an AlignFile and construct a new
305 * alignment or import to an existing alignment
307 * @return AlignmentI instance ready to pass to a UI constructor
309 private AlignmentI buildAlignmentFromFile()
311 // Standard boilerplate for creating alignment from parser
312 // alignFile.configureForView(viewpanel);
314 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
316 alignFile.addAnnotations(al);
318 alignFile.addGroups(al);
324 * create an alignment flatfile from a Jalview alignment view
329 * @param selectedOnly
330 * @return flatfile in a string
332 public String formatSequences(FileFormatI format, boolean jvsuffix,
333 AlignmentViewPanel ap, boolean selectedOnly)
336 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
337 selectedOnly, false);
338 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
340 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
341 .getVisibleAlignmentAnnotation(selectedOnly));
344 for (AlignmentAnnotation aa : ala)
346 aselview.addAnnotation(aa);
350 return formatSequences(format, aselview, jvsuffix);
354 * Construct an output class for an alignment in a particular filetype TODO:
355 * allow caller to detect errors and warnings encountered when generating
359 * string name of alignment format
361 * the alignment to be written out
363 * passed to AlnFile class controls whether /START-END is added to
366 * @return alignment flat file contents
368 public String formatSequences(FileFormatI format, AlignmentI alignment,
373 AlignmentFileWriterI afile = format.getWriter(alignment);
375 afile.setNewlineString(newline);
376 afile.setExportSettings(exportSettings);
377 afile.configureForView(viewpanel);
379 // check whether we were given a specific alignment to export, rather than
380 // the one in the viewpanel
381 SequenceI[] seqs = null;
382 if (viewpanel == null || viewpanel.getAlignment() == null
383 || viewpanel.getAlignment() != alignment)
385 seqs = alignment.getSequencesArray();
389 seqs = viewpanel.getAlignment().getSequencesArray();
392 String afileresp = afile.print(seqs, jvsuffix);
393 if (afile.hasWarningMessage())
395 System.err.println("Warning raised when writing as " + format
396 + " : " + afile.getWarningMessage());
399 } catch (Exception e)
401 System.err.println("Failed to write alignment as a '"
411 * Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
415 * @return the protocol for the input data
417 public static DataSourceType checkProtocol(String data)
419 DataSourceType protocol = DataSourceType.PASTE;
420 String ft = data.toLowerCase().trim();
421 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
422 || ft.indexOf("file:") == 0)
424 protocol = DataSourceType.URL;
426 else if (new File(data).exists())
428 protocol = DataSourceType.FILE;
433 public static void main(String[] args)
436 while (i < args.length)
438 File f = new File(args[i]);
443 System.out.println("Reading file: " + f);
444 AppletFormatAdapter afa = new AppletFormatAdapter();
445 Runtime r = Runtime.getRuntime();
447 long memf = -r.totalMemory() + r.freeMemory();
448 long t1 = -System.currentTimeMillis();
450 .readFile(args[i], DataSourceType.FILE,
451 new IdentifyFile().identify(args[i],
452 DataSourceType.FILE));
453 t1 += System.currentTimeMillis();
455 memf += r.totalMemory() - r.freeMemory();
458 System.out.println("Alignment contains " + al.getHeight()
459 + " sequences and " + al.getWidth() + " columns.");
462 System.out.println(new AppletFormatAdapter().formatSequences(
463 FileFormat.Fasta, al, true));
464 } catch (Exception e)
467 .println("Couln't format the alignment for output as a FASTA file.");
468 e.printStackTrace(System.err);
473 System.out.println("Couldn't read alignment");
475 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
477 .println("Difference between free memory now and before is "
478 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
479 } catch (Exception e)
481 System.err.println("Exception when dealing with " + i
482 + "'th argument: " + args[i] + "\n" + e);
487 System.err.println("Ignoring argument '" + args[i] + "' (" + i
488 + "'th)- not a readable file.");
495 * try to discover how to access the given file as a valid datasource that
496 * will be identified as the given type.
500 * @return protocol that yields the data parsable as the given type
502 public static DataSourceType resolveProtocol(String file,
505 return resolveProtocol(file, format, false);
508 public static DataSourceType resolveProtocol(String file,
509 FileFormatI format, boolean debug)
511 // TODO: test thoroughly!
512 DataSourceType protocol = null;
515 System.out.println("resolving datasource started with:\n>>file\n"
516 + file + ">>endfile");
519 // This might throw a security exception in certain browsers
520 // Netscape Communicator for instance.
524 InputStream is = System.getSecurityManager().getClass()
525 .getResourceAsStream("/" + file);
533 System.err.println("Resource '" + file + "' was "
534 + (rtn ? "" : "not") + " located by classloader.");
538 protocol = DataSourceType.CLASSLOADER;
541 } catch (Exception ex)
544 .println("Exception checking resources: " + file + " " + ex);
547 if (file.indexOf("://") > -1)
549 protocol = DataSourceType.URL;
553 // skipping codebase prepend check.
554 protocol = DataSourceType.FILE;
561 System.out.println("Trying to get contents of resource as "
564 fp = new FileParse(file, protocol);
573 System.out.println("Successful.");
576 } catch (Exception e)
580 System.err.println("Exception when accessing content: " + e);
588 System.out.println("Accessing as paste.");
590 protocol = DataSourceType.PASTE;
594 fp = new FileParse(file, protocol);
599 } catch (Exception e)
601 System.err.println("Failed to access content as paste!");
618 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
619 if (idformat == null)
623 System.out.println("Format not identified. Inaccessible file.");
629 System.out.println("Format identified as " + idformat
630 + "and expected as " + format);
632 if (idformat.equals(format))
636 System.out.println("Protocol identified as " + protocol);
645 .println("File deemed not accessible via " + protocol);
650 } catch (Exception e)
654 System.err.println("File deemed not accessible via " + protocol);
662 public AlignmentFileReaderI getAlignFile()