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 java.util.Locale;
25 import jalview.api.AlignExportSettingsI;
26 import jalview.api.AlignmentViewPanel;
27 import jalview.datamodel.Alignment;
28 import jalview.datamodel.AlignmentAnnotation;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.AlignmentView;
31 import jalview.datamodel.PDBEntry.Type;
32 import jalview.datamodel.SequenceI;
33 import jalview.ext.jmol.JmolParser;
34 import jalview.structure.StructureImportSettings;
35 import jalview.util.Platform;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.util.List;
43 * A low level class for alignment and feature IO with alignment formatting
44 * methods used by both applet and application for generating flat alignment
45 * files. It also holds the lists of magic format names that the applet and
46 * application will allow the user to read or write files with.
51 public class AppletFormatAdapter
53 private AlignmentViewPanel viewpanel;
56 * add jalview-derived non-secondary structure annotation from PDB structure
58 boolean annotFromStructure = false;
61 * add secondary structure from PDB data with built-in algorithms
63 boolean localSecondaryStruct = false;
66 * process PDB data with web services
68 boolean serviceSecondaryStruct = false;
70 private AlignmentFileReaderI alignFile = null;
75 * character used to write newlines
77 protected String newline = System.getProperty("line.separator");
79 private AlignExportSettingsI exportSettings;
81 private File selectedFile;
83 public static String INVALID_CHARACTERS = "Contains invalid characters";
86 * Returns an error message with a list of supported readable file formats
90 public static String getSupportedFormats()
92 return "Formats currently supported are\n"
93 + prettyPrint(FileFormats.getInstance().getReadableFormats());
96 public AppletFormatAdapter()
100 public AppletFormatAdapter(AlignmentViewPanel viewpanel)
102 this.viewpanel = viewpanel;
105 public AppletFormatAdapter(AlignmentViewPanel alignPanel,
106 AlignExportSettingsI settings)
108 viewpanel = alignPanel;
109 exportSettings = settings;
113 * Formats a grammatically correct(ish) list consisting of the given objects
118 public static String prettyPrint(List<? extends Object> things)
120 StringBuffer list = new StringBuffer();
121 for (int i = 0, iSize = things.size() - 1; i < iSize; i++)
123 list.append(things.get(i).toString());
126 // could i18n 'and' here
127 list.append(" and " + things.get(things.size() - 1).toString() + ".");
128 return list.toString();
131 public void setNewlineString(String nl)
136 public String getNewlineString()
142 * Constructs the correct filetype parser for a characterised datasource
152 public AlignmentI readFile(String file, DataSourceType sourceType,
153 FileFormatI fileFormat) throws IOException
155 return readFile(null, file, sourceType, fileFormat);
158 public AlignmentI readFile(File selectedFile, String file, DataSourceType sourceType,
159 FileFormatI fileFormat) throws IOException
162 this.selectedFile = selectedFile;
163 if (selectedFile != null)
165 this.inFile = selectedFile.getPath();
170 if (fileFormat.isStructureFile())
172 String structureParser = StructureImportSettings
173 .getDefaultPDBFileParser();
174 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
175 StructureImportSettings.StructureParser.JMOL_PARSER
177 StructureImportSettings.addSettings(annotFromStructure,
178 localSecondaryStruct, serviceSecondaryStruct);
181 // needs a File option
182 alignFile = new JmolParser(selectedFile == null ? inFile : selectedFile, sourceType);
186 // todo is mc_view parsing obsolete yet? JAL-2120
187 StructureImportSettings.setShowSeqFeatures(true);
188 alignFile = new mc_view.PDBfile(annotFromStructure,
189 localSecondaryStruct, serviceSecondaryStruct, inFile,
192 ((StructureFile) alignFile).setDbRefType(
193 FileFormat.PDB.equals(fileFormat) ? Type.PDB : Type.MMCIF);
195 else if (selectedFile != null) {
196 alignFile = fileFormat.getReader(new FileParse(selectedFile, sourceType));
199 // alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
200 alignFile = fileFormat.getReader(new FileParse(inFile, sourceType));
202 return buildAlignmentFromFile();
203 } catch (Exception e)
206 System.err.println("Failed to read alignment using the '" + fileFormat
207 + "' reader.\n" + e);
209 if (e.getMessage() != null
210 && e.getMessage().startsWith(INVALID_CHARACTERS))
212 throw new IOException(e.getMessage());
215 // Finally test if the user has pasted just the sequence, no id
216 if (sourceType == DataSourceType.PASTE)
220 // Possible sequence is just residues with no label
221 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
222 DataSourceType.PASTE);
223 return buildAlignmentFromFile();
225 } catch (Exception ex)
227 if (ex.toString().startsWith(INVALID_CHARACTERS))
229 throw new IOException(e.getMessage());
232 ex.printStackTrace();
235 if (FileFormat.Html.equals(fileFormat))
237 throw new IOException(e.getMessage());
240 throw new FileFormatException(getSupportedFormats());
244 * Constructs the correct filetype parser for an already open datasource
247 * an existing datasource
249 * File format of data that will be provided by datasource
253 public AlignmentI readFromFile(FileParse source, FileFormatI format)
256 this.inFile = source.getInFile();
257 DataSourceType type = source.dataSourceType;
260 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
262 // TODO obtain config value from preference settings
263 boolean isParseWithJMOL = false;
266 StructureImportSettings.addSettings(annotFromStructure,
267 localSecondaryStruct, serviceSecondaryStruct);
268 alignFile = new JmolParser(source);
272 StructureImportSettings.setShowSeqFeatures(true);
273 alignFile = new mc_view.PDBfile(annotFromStructure,
274 localSecondaryStruct, serviceSecondaryStruct, source);
276 ((StructureFile) alignFile).setDbRefType(Type.PDB);
280 alignFile = format.getReader(source);
283 return buildAlignmentFromFile();
285 } catch (Exception e)
288 System.err.println("Failed to read alignment using the '" + format
289 + "' reader.\n" + e);
291 if (e.getMessage() != null
292 && e.getMessage().startsWith(INVALID_CHARACTERS))
294 throw new FileFormatException(e.getMessage());
297 // Finally test if the user has pasted just the sequence, no id
298 if (type == DataSourceType.PASTE)
302 // Possible sequence is just residues with no label
303 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
304 DataSourceType.PASTE);
305 return buildAlignmentFromFile();
307 } catch (Exception ex)
309 if (ex.toString().startsWith(INVALID_CHARACTERS))
311 throw new IOException(e.getMessage());
314 ex.printStackTrace();
318 // If we get to this stage, the format was not supported
319 throw new FileFormatException(getSupportedFormats());
324 * boilerplate method to handle data from an AlignFile and construct a new
325 * alignment or import to an existing alignment
327 * @return AlignmentI instance ready to pass to a UI constructor
329 private AlignmentI buildAlignmentFromFile()
331 // Standard boilerplate for creating alignment from parser
332 // alignFile.configureForView(viewpanel);
334 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
336 alignFile.addAnnotations(al);
338 alignFile.addGroups(al);
344 * create an alignment flatfile from a Jalview alignment view
349 * @param selectedOnly
350 * @return flatfile in a string
352 public String formatSequences(FileFormatI format, boolean jvsuffix,
353 AlignmentViewPanel ap, boolean selectedOnly)
356 AlignmentView selvew = ap.getAlignViewport()
357 .getAlignmentView(selectedOnly, false);
358 AlignmentI aselview = selvew
359 .getVisibleAlignment(ap.getAlignViewport().getGapCharacter());
360 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
361 .getVisibleAlignmentAnnotation(selectedOnly));
364 for (AlignmentAnnotation aa : ala)
366 aselview.addAnnotation(aa);
370 return formatSequences(format, aselview, jvsuffix);
374 * Construct an output class for an alignment in a particular filetype TODO:
375 * allow caller to detect errors and warnings encountered when generating
379 * string name of alignment format
381 * the alignment to be written out
383 * passed to AlnFile class controls whether /START-END is added to
386 * @return alignment flat file contents
388 public String formatSequences(FileFormatI format, AlignmentI alignment,
393 AlignmentFileWriterI afile = format.getWriter(alignment);
395 afile.setNewlineString(newline);
396 afile.setExportSettings(exportSettings);
397 afile.configureForView(viewpanel);
399 // check whether we were given a specific alignment to export, rather than
400 // the one in the viewpanel
401 SequenceI[] seqs = null;
402 if (viewpanel == null || viewpanel.getAlignment() == null
403 || viewpanel.getAlignment() != alignment)
405 seqs = alignment.getSequencesArray();
409 seqs = viewpanel.getAlignment().getSequencesArray();
412 String afileresp = afile.print(seqs, jvsuffix);
413 if (afile.hasWarningMessage())
415 System.err.println("Warning raised when writing as " + format
416 + " : " + afile.getWarningMessage());
419 } catch (Exception e)
421 System.err.println("Failed to write alignment as a '"
422 + format.getName() + "' file\n");
431 * Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
434 * BH 2018 allows File or String, and can return RELATIVE_URL
436 * @param dataObject File or String
437 * @return the protocol for the input data
439 public static DataSourceType checkProtocol(Object dataObject)
441 if(dataObject instanceof File)
443 return DataSourceType.FILE;
446 String data = dataObject.toString();
447 DataSourceType protocol = DataSourceType.PASTE;
448 String ft = data.toLowerCase(Locale.ROOT).trim();
449 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
450 || ft.indexOf("file:") == 0)
452 protocol = DataSourceType.URL;
454 else if (Platform.isJS())
456 protocol = DataSourceType.RELATIVE_URL;
458 else if (new File(data).exists())
460 protocol = DataSourceType.FILE;
469 public static void main(String[] args)
472 while (i < args.length)
474 File f = new File(args[i]);
479 System.out.println("Reading file: " + f);
480 AppletFormatAdapter afa = new AppletFormatAdapter();
481 Runtime r = Runtime.getRuntime();
483 long memf = -r.totalMemory() + r.freeMemory();
484 long t1 = -System.currentTimeMillis();
485 AlignmentI al = afa.readFile(args[i], DataSourceType.FILE,
486 new IdentifyFile().identify(args[i],
487 DataSourceType.FILE));
488 t1 += System.currentTimeMillis();
490 memf += r.totalMemory() - r.freeMemory();
493 System.out.println("Alignment contains " + al.getHeight()
494 + " sequences and " + al.getWidth() + " columns.");
497 System.out.println(new AppletFormatAdapter()
498 .formatSequences(FileFormat.Fasta, al, true));
499 } catch (Exception e)
502 "Couln't format the alignment for output as a FASTA file.");
503 e.printStackTrace(System.err);
508 System.out.println("Couldn't read alignment");
510 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
512 "Difference between free memory now and before is "
513 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
514 } catch (Exception e)
516 System.err.println("Exception when dealing with " + i
517 + "'th argument: " + args[i] + "\n" + e);
522 System.err.println("Ignoring argument '" + args[i] + "' (" + i
523 + "'th)- not a readable file.");
530 * try to discover how to access the given file as a valid datasource that
531 * will be identified as the given type.
535 * @return protocol that yields the data parsable as the given type
537 public static DataSourceType resolveProtocol(String file,
540 return resolveProtocol(file, format, false);
543 public static DataSourceType resolveProtocol(String file,
544 FileFormatI format, boolean debug)
546 // TODO: test thoroughly!
547 DataSourceType protocol = null;
550 System.out.println("resolving datasource started with:\n>>file\n"
551 + file + ">>endfile");
554 // This might throw a security exception in certain browsers
555 // Netscape Communicator for instance.
559 InputStream is = System.getSecurityManager().getClass()
560 .getResourceAsStream("/" + file);
568 System.err.println("Resource '" + file + "' was "
569 + (rtn ? "" : "not") + " located by classloader.");
573 protocol = DataSourceType.CLASSLOADER;
576 } catch (Exception ex)
579 .println("Exception checking resources: " + file + " " + ex);
582 if (file.indexOf("://") > -1)
584 protocol = DataSourceType.URL;
588 // skipping codebase prepend check.
589 protocol = DataSourceType.FILE;
597 "Trying to get contents of resource as " + protocol + ":");
599 fp = new FileParse(file, protocol);
608 System.out.println("Successful.");
611 } catch (Exception e)
615 System.err.println("Exception when accessing content: " + e);
623 System.out.println("Accessing as paste.");
625 protocol = DataSourceType.PASTE;
629 fp = new FileParse(file, protocol);
634 } catch (Exception e)
636 System.err.println("Failed to access content as paste!");
653 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
654 if (idformat == null)
658 System.out.println("Format not identified. Inaccessible file.");
664 System.out.println("Format identified as " + idformat
665 + "and expected as " + format);
667 if (idformat.equals(format))
671 System.out.println("Protocol identified as " + protocol);
680 .println("File deemed not accessible via " + protocol);
685 } catch (Exception e)
689 System.err.println("File deemed not accessible via " + protocol);
697 public AlignmentFileReaderI getAlignFile()