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());
91 public AppletFormatAdapter()
95 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
97 this.viewpanel = viewpanel;
100 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
101 AlignExportSettingI settings)
103 viewpanel = alignPanel;
104 exportSettings = settings;
108 * Formats a grammatically correct(ish) list consisting of the given objects
113 public static String prettyPrint(List<? extends Object> things)
115 StringBuffer list = new StringBuffer();
116 for (int i = 0, iSize = things.size() - 1; i < iSize; i++)
118 list.append(things.get(i).toString());
121 // could i18n 'and' here
122 list.append(" and " + things.get(things.size() - 1).toString() + ".");
123 return list.toString();
126 public void setNewlineString(String nl)
131 public String getNewlineString()
137 * Constructs the correct filetype parser for a characterised datasource
147 public AlignmentI readFile(String file, DataSourceType sourceType,
148 FileFormatI fileFormat) throws IOException
150 if (alignFile == null)
152 prepareFileReader(file, sourceType, fileFormat);
158 return buildAlignmentFromFile();
161 public void prepareFileReader(String file, DataSourceType sourceType,
162 FileFormatI fileFormat) throws IOException
167 if (fileFormat.isStructureFile())
169 String structureParser = StructureImportSettings
170 .getDefaultPDBFileParser();
171 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
172 StructureImportSettings.StructureParser.JMOL_PARSER
174 StructureImportSettings.addSettings(annotFromStructure,
175 localSecondaryStruct, serviceSecondaryStruct);
178 alignFile = new JmolParser(inFile, sourceType);
182 // todo is MCview parsing obsolete yet? JAL-2120
183 StructureImportSettings.setShowSeqFeatures(true);
184 alignFile = new MCview.PDBfile(annotFromStructure,
185 localSecondaryStruct, serviceSecondaryStruct, inFile,
188 ((StructureFile) alignFile).setDbRefType(
189 FileFormat.PDB.equals(fileFormat) ? Type.PDB : Type.MMCIF);
193 alignFile = fileFormat.getReader(new FileParse(inFile, sourceType));
196 } catch (Exception e)
199 System.err.println("Failed to read alignment using the '" + fileFormat
200 + "' reader.\n" + e);
202 if (e.getMessage() != null
203 && e.getMessage().startsWith(INVALID_CHARACTERS))
205 throw new IOException(e.getMessage());
208 // Finally test if the user has pasted just the sequence, no id
209 if (sourceType == DataSourceType.PASTE)
213 // Possible sequence is just residues with no label
214 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
215 DataSourceType.PASTE);
218 } catch (Exception ex)
220 if (ex.toString().startsWith(INVALID_CHARACTERS))
222 throw new IOException(e.getMessage());
225 ex.printStackTrace();
228 if (FileFormat.Html.equals(fileFormat))
230 throw new IOException(e.getMessage());
233 throw new FileFormatException(getSupportedFormats());
237 * Constructs the correct filetype parser for an already open datasource
240 * an existing datasource
242 * File format of data that will be provided by datasource
246 public AlignmentI readFromFile(FileParse source, FileFormatI format)
249 this.inFile = source.getInFile();
250 DataSourceType type = source.dataSourceType;
253 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
255 // TODO obtain config value from preference settings
256 boolean isParseWithJMOL = false;
259 StructureImportSettings.addSettings(annotFromStructure,
260 localSecondaryStruct, serviceSecondaryStruct);
261 alignFile = new JmolParser(source);
265 StructureImportSettings.setShowSeqFeatures(true);
266 alignFile = new MCview.PDBfile(annotFromStructure,
267 localSecondaryStruct, serviceSecondaryStruct, source);
269 ((StructureFile) alignFile).setDbRefType(Type.PDB);
273 alignFile = format.getReader(source);
276 return buildAlignmentFromFile();
278 } catch (Exception e)
281 System.err.println("Failed to read alignment using the '" + format
282 + "' reader.\n" + e);
284 if (e.getMessage() != null
285 && e.getMessage().startsWith(INVALID_CHARACTERS))
287 throw new FileFormatException(e.getMessage());
290 // Finally test if the user has pasted just the sequence, no id
291 if (type == DataSourceType.PASTE)
295 // Possible sequence is just residues with no label
296 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
297 DataSourceType.PASTE);
298 return buildAlignmentFromFile();
300 } catch (Exception ex)
302 if (ex.toString().startsWith(INVALID_CHARACTERS))
304 throw new IOException(e.getMessage());
307 ex.printStackTrace();
311 // If we get to this stage, the format was not supported
312 throw new FileFormatException(getSupportedFormats());
317 * boilerplate method to handle data from an AlignFile and construct a new
318 * alignment or import to an existing alignment
320 * @return AlignmentI instance ready to pass to a UI constructor
322 private AlignmentI buildAlignmentFromFile()
324 // Standard boilerplate for creating alignment from parser
325 // alignFile.configureForView(viewpanel);
327 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
329 alignFile.addAnnotations(al);
331 alignFile.addGroups(al);
337 * create an alignment flatfile from a Jalview alignment view
342 * @param selectedOnly
343 * @return flatfile in a string
345 public String formatSequences(FileFormatI format, boolean jvsuffix,
346 AlignmentViewPanel ap, boolean selectedOnly)
349 AlignmentView selvew = ap.getAlignViewport()
350 .getAlignmentView(selectedOnly, false);
351 AlignmentI aselview = selvew
352 .getVisibleAlignment(ap.getAlignViewport().getGapCharacter());
353 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
354 .getVisibleAlignmentAnnotation(selectedOnly));
357 for (AlignmentAnnotation aa : ala)
359 aselview.addAnnotation(aa);
363 return formatSequences(format, aselview, jvsuffix);
367 * Construct an output class for an alignment in a particular filetype TODO:
368 * allow caller to detect errors and warnings encountered when generating
372 * string name of alignment format
374 * the alignment to be written out
376 * passed to AlnFile class controls whether /START-END is added to
379 * @return alignment flat file contents
381 public String formatSequences(FileFormatI format, AlignmentI alignment,
386 AlignmentFileWriterI afile = format.getWriter(alignment);
388 afile.setNewlineString(newline);
389 afile.setExportSettings(exportSettings);
390 afile.configureForView(viewpanel);
392 // check whether we were given a specific alignment to export, rather than
393 // the one in the viewpanel
394 SequenceI[] seqs = null;
395 if (viewpanel == null || viewpanel.getAlignment() == null
396 || viewpanel.getAlignment() != alignment)
398 seqs = alignment.getSequencesArray();
402 seqs = viewpanel.getAlignment().getSequencesArray();
405 String afileresp = afile.print(seqs, jvsuffix);
406 if (afile.hasWarningMessage())
408 System.err.println("Warning raised when writing as " + format
409 + " : " + afile.getWarningMessage());
412 } catch (Exception e)
414 System.err.println("Failed to write alignment as a '"
415 + format.getName() + "' file\n");
423 * Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
427 * @return the protocol for the input data
429 public static DataSourceType checkProtocol(String data)
431 DataSourceType protocol = DataSourceType.PASTE;
432 String ft = data.toLowerCase().trim();
433 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
434 || ft.indexOf("file:") == 0)
436 protocol = DataSourceType.URL;
438 else if (new File(data).exists())
440 protocol = DataSourceType.FILE;
445 public static void main(String[] args)
448 while (i < args.length)
450 File f = new File(args[i]);
455 System.out.println("Reading file: " + f);
456 AppletFormatAdapter afa = new AppletFormatAdapter();
457 Runtime r = Runtime.getRuntime();
459 long memf = -r.totalMemory() + r.freeMemory();
460 long t1 = -System.currentTimeMillis();
461 AlignmentI al = afa.readFile(args[i], DataSourceType.FILE,
462 new IdentifyFile().identify(args[i],
463 DataSourceType.FILE));
464 t1 += System.currentTimeMillis();
466 memf += r.totalMemory() - r.freeMemory();
469 System.out.println("Alignment contains " + al.getHeight()
470 + " sequences and " + al.getWidth() + " columns.");
473 System.out.println(new AppletFormatAdapter()
474 .formatSequences(FileFormat.Fasta, al, true));
475 } catch (Exception e)
478 "Couln't format the alignment for output as a FASTA file.");
479 e.printStackTrace(System.err);
484 System.out.println("Couldn't read alignment");
486 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
488 "Difference between free memory now and before is "
489 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
490 } catch (Exception e)
492 System.err.println("Exception when dealing with " + i
493 + "'th argument: " + args[i] + "\n" + e);
498 System.err.println("Ignoring argument '" + args[i] + "' (" + i
499 + "'th)- not a readable file.");
506 * try to discover how to access the given file as a valid datasource that
507 * will be identified as the given type.
511 * @return protocol that yields the data parsable as the given type
513 public static DataSourceType resolveProtocol(String file,
516 return resolveProtocol(file, format, false);
519 public static DataSourceType resolveProtocol(String file,
520 FileFormatI format, boolean debug)
522 // TODO: test thoroughly!
523 DataSourceType protocol = null;
526 System.out.println("resolving datasource started with:\n>>file\n"
527 + file + ">>endfile");
530 // This might throw a security exception in certain browsers
531 // Netscape Communicator for instance.
535 InputStream is = System.getSecurityManager().getClass()
536 .getResourceAsStream("/" + file);
544 System.err.println("Resource '" + file + "' was "
545 + (rtn ? "" : "not") + " located by classloader.");
549 protocol = DataSourceType.CLASSLOADER;
552 } catch (Exception ex)
555 .println("Exception checking resources: " + file + " " + ex);
558 if (file.indexOf("://") > -1)
560 protocol = DataSourceType.URL;
564 // skipping codebase prepend check.
565 protocol = DataSourceType.FILE;
573 "Trying to get contents of resource as " + protocol + ":");
575 fp = new FileParse(file, protocol);
584 System.out.println("Successful.");
587 } catch (Exception e)
591 System.err.println("Exception when accessing content: " + e);
599 System.out.println("Accessing as paste.");
601 protocol = DataSourceType.PASTE;
605 fp = new FileParse(file, protocol);
610 } catch (Exception e)
612 System.err.println("Failed to access content as paste!");
629 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
630 if (idformat == null)
634 System.out.println("Format not identified. Inaccessible file.");
640 System.out.println("Format identified as " + idformat
641 + "and expected as " + format);
643 if (idformat.equals(format))
647 System.out.println("Protocol identified as " + protocol);
656 .println("File deemed not accessible via " + protocol);
661 } catch (Exception e)
665 System.err.println("File deemed not accessible via " + protocol);
673 public AlignmentFileReaderI getAlignFile()