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 AlignmentFileI 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";
80 public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
81 + prettyPrint(FileFormat.getReadableFormats());
83 public AppletFormatAdapter()
87 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
89 this.viewpanel = viewpanel;
92 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
93 AlignExportSettingI settings)
95 viewpanel = alignPanel;
96 exportSettings = settings;
100 * Formats a grammatically correct(ish) list consisting of the given objects
105 public static String prettyPrint(List<? extends Object> things)
107 StringBuffer list = new StringBuffer();
108 for (int i = 0, iSize = things.size() - 1; i < iSize; i++)
110 list.append(things.get(i).toString());
113 // could i18n 'and' here
114 list.append(" and " + things.get(things.size() - 1).toString() + ".");
115 return list.toString();
118 public void setNewlineString(String nl)
123 public String getNewlineString()
129 * Constructs the correct filetype parser for a characterised datasource
139 public AlignmentI readFile(String file, DataSourceType sourceType,
140 FileFormatI fileFormat) throws IOException
145 if (fileFormat.isStructureFile())
147 String structureParser = StructureImportSettings
148 .getDefaultPDBFileParser();
149 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
150 StructureImportSettings.StructureParser.JMOL_PARSER
152 StructureImportSettings.addSettings(annotFromStructure,
153 localSecondaryStruct, serviceSecondaryStruct);
156 alignFile = new JmolParser(inFile, sourceType);
160 // todo is MCview parsing obsolete yet?
161 StructureImportSettings.setShowSeqFeatures(true);
162 alignFile = new MCview.PDBfile(annotFromStructure,
163 localSecondaryStruct, serviceSecondaryStruct, inFile,
166 ((StructureFile) alignFile).setDbRefType(FileFormat.PDB
167 .equals(fileFormat) ? Type.PDB : Type.MMCIF);
171 alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
173 return buildAlignmentFromFile();
174 } catch (Exception e)
177 System.err.println("Failed to read alignment using the '"
178 + fileFormat + "' reader.\n" + e);
180 if (e.getMessage() != null
181 && e.getMessage().startsWith(INVALID_CHARACTERS))
183 throw new IOException(e.getMessage());
186 // Finally test if the user has pasted just the sequence, no id
187 if (sourceType == DataSourceType.PASTE)
191 // Possible sequence is just residues with no label
192 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
193 DataSourceType.PASTE);
194 return buildAlignmentFromFile();
196 } catch (Exception ex)
198 if (ex.toString().startsWith(INVALID_CHARACTERS))
200 throw new IOException(e.getMessage());
203 ex.printStackTrace();
206 if (FileFormat.Html.equals(fileFormat))
208 throw new IOException(e.getMessage());
211 throw new FileFormatException(SUPPORTED_FORMATS);
215 * Constructs the correct filetype parser for an already open datasource
218 * an existing datasource
220 * File format of data that will be provided by datasource
224 public AlignmentI readFromFile(FileParse source, FileFormatI format)
227 this.inFile = source.getInFile();
228 DataSourceType type = source.dataSourceType;
231 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
233 // TODO obtain config value from preference settings
234 boolean isParseWithJMOL = false;
237 StructureImportSettings.addSettings(annotFromStructure,
238 localSecondaryStruct, serviceSecondaryStruct);
239 alignFile = new JmolParser(source);
243 StructureImportSettings.setShowSeqFeatures(true);
244 alignFile = new MCview.PDBfile(annotFromStructure,
245 localSecondaryStruct, serviceSecondaryStruct, source);
247 ((StructureFile) alignFile).setDbRefType(Type.PDB);
251 alignFile = format.getAlignmentFile(source);
254 return buildAlignmentFromFile();
256 } catch (Exception e)
259 System.err.println("Failed to read alignment using the '" + format
260 + "' reader.\n" + e);
262 if (e.getMessage() != null
263 && e.getMessage().startsWith(INVALID_CHARACTERS))
265 throw new FileFormatException(e.getMessage());
268 // Finally test if the user has pasted just the sequence, no id
269 if (type == DataSourceType.PASTE)
273 // Possible sequence is just residues with no label
274 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
275 DataSourceType.PASTE);
276 return buildAlignmentFromFile();
278 } catch (Exception ex)
280 if (ex.toString().startsWith(INVALID_CHARACTERS))
282 throw new IOException(e.getMessage());
285 ex.printStackTrace();
289 // If we get to this stage, the format was not supported
290 throw new FileFormatException(SUPPORTED_FORMATS);
295 * boilerplate method to handle data from an AlignFile and construct a new
296 * alignment or import to an existing alignment
298 * @return AlignmentI instance ready to pass to a UI constructor
300 private AlignmentI buildAlignmentFromFile()
302 // Standard boilerplate for creating alignment from parser
303 // alignFile.configureForView(viewpanel);
305 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
307 alignFile.addAnnotations(al);
309 alignFile.addGroups(al);
315 * create an alignment flatfile from a Jalview alignment view
320 * @param selectedOnly
321 * @return flatfile in a string
323 public String formatSequences(FileFormatI format, boolean jvsuffix,
324 AlignmentViewPanel ap, boolean selectedOnly)
327 AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
328 selectedOnly, false);
329 AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
331 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
332 .getVisibleAlignmentAnnotation(selectedOnly));
335 for (AlignmentAnnotation aa : ala)
337 aselview.addAnnotation(aa);
341 return formatSequences(format, aselview, jvsuffix);
345 * Construct an output class for an alignment in a particular filetype TODO:
346 * allow caller to detect errors and warnings encountered when generating
350 * string name of alignment format
352 * the alignment to be written out
354 * passed to AlnFile class controls whether /START-END is added to
357 * @return alignment flat file contents
359 public String formatSequences(FileFormatI format, AlignmentI alignment,
364 AlignmentFileI afile = format.getAlignmentFile(alignment);
366 afile.setNewlineString(newline);
367 afile.setExportSettings(exportSettings);
368 afile.configureForView(viewpanel);
370 // check whether we were given a specific alignment to export, rather than
371 // the one in the viewpanel
372 SequenceI[] seqs = null;
373 if (viewpanel == null || viewpanel.getAlignment() == null
374 || viewpanel.getAlignment() != alignment)
376 seqs = alignment.getSequencesArray();
380 seqs = viewpanel.getAlignment().getSequencesArray();
383 String afileresp = afile.print(seqs, jvsuffix);
384 if (afile.hasWarningMessage())
386 System.err.println("Warning raised when writing as " + format
387 + " : " + afile.getWarningMessage());
390 } catch (Exception e)
392 System.err.println("Failed to write alignment as a '" + format
400 public static DataSourceType checkProtocol(String file)
402 DataSourceType protocol = DataSourceType.FILE;
403 String ft = file.toLowerCase().trim();
404 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
405 || ft.indexOf("file:") == 0)
407 protocol = DataSourceType.URL;
412 public static void main(String[] args)
415 while (i < args.length)
417 File f = new File(args[i]);
422 System.out.println("Reading file: " + f);
423 AppletFormatAdapter afa = new AppletFormatAdapter();
424 Runtime r = Runtime.getRuntime();
426 long memf = -r.totalMemory() + r.freeMemory();
427 long t1 = -System.currentTimeMillis();
429 .readFile(args[i], DataSourceType.FILE,
430 new IdentifyFile().identify(args[i],
431 DataSourceType.FILE));
432 t1 += System.currentTimeMillis();
434 memf += r.totalMemory() - r.freeMemory();
437 System.out.println("Alignment contains " + al.getHeight()
438 + " sequences and " + al.getWidth() + " columns.");
441 System.out.println(new AppletFormatAdapter().formatSequences(
442 FileFormat.Fasta, al, true));
443 } catch (Exception e)
446 .println("Couln't format the alignment for output as a FASTA file.");
447 e.printStackTrace(System.err);
452 System.out.println("Couldn't read alignment");
454 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
456 .println("Difference between free memory now and before is "
457 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
458 } catch (Exception e)
460 System.err.println("Exception when dealing with " + i
461 + "'th argument: " + args[i] + "\n" + e);
466 System.err.println("Ignoring argument '" + args[i] + "' (" + i
467 + "'th)- not a readable file.");
474 * try to discover how to access the given file as a valid datasource that
475 * will be identified as the given type.
479 * @return protocol that yields the data parsable as the given type
481 public static DataSourceType resolveProtocol(String file,
484 return resolveProtocol(file, format, false);
487 public static DataSourceType resolveProtocol(String file,
488 FileFormatI format, boolean debug)
490 // TODO: test thoroughly!
491 DataSourceType protocol = null;
494 System.out.println("resolving datasource started with:\n>>file\n"
495 + file + ">>endfile");
498 // This might throw a security exception in certain browsers
499 // Netscape Communicator for instance.
503 InputStream is = System.getSecurityManager().getClass()
504 .getResourceAsStream("/" + file);
512 System.err.println("Resource '" + file + "' was "
513 + (rtn ? "" : "not") + " located by classloader.");
517 protocol = DataSourceType.CLASSLOADER;
520 } catch (Exception ex)
523 .println("Exception checking resources: " + file + " " + ex);
526 if (file.indexOf("://") > -1)
528 protocol = DataSourceType.URL;
532 // skipping codebase prepend check.
533 protocol = DataSourceType.FILE;
540 System.out.println("Trying to get contents of resource as "
543 fp = new FileParse(file, protocol);
552 System.out.println("Successful.");
555 } catch (Exception e)
559 System.err.println("Exception when accessing content: " + e);
567 System.out.println("Accessing as paste.");
569 protocol = DataSourceType.PASTE;
573 fp = new FileParse(file, protocol);
578 } catch (Exception e)
580 System.err.println("Failed to access content as paste!");
597 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
598 if (idformat == null)
602 System.out.println("Format not identified. Inaccessible file.");
608 System.out.println("Format identified as " + idformat
609 + "and expected as " + format);
611 if (idformat.equals(format))
615 System.out.println("Protocol identified as " + protocol);
624 .println("File deemed not accessible via " + protocol);
629 } catch (Exception e)
633 System.err.println("File deemed not accessible via " + protocol);
641 public AlignmentFileI getAlignFile()