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,
159 DataSourceType sourceType, FileFormatI fileFormat)
163 this.selectedFile = selectedFile;
164 if (selectedFile != null)
166 this.inFile = selectedFile.getPath();
171 if (fileFormat.isStructureFile())
173 String structureParser = StructureImportSettings
174 .getDefaultPDBFileParser();
175 boolean isParseWithJMOL = structureParser.equalsIgnoreCase(
176 StructureImportSettings.StructureParser.JMOL_PARSER
178 StructureImportSettings.addSettings(annotFromStructure,
179 localSecondaryStruct, serviceSecondaryStruct);
182 // needs a File option
183 alignFile = new JmolParser(
184 selectedFile == null ? inFile : selectedFile, sourceType);
188 // todo is mc_view parsing obsolete yet? JAL-2120
189 StructureImportSettings.setShowSeqFeatures(true);
190 alignFile = new mc_view.PDBfile(annotFromStructure,
191 localSecondaryStruct, serviceSecondaryStruct, inFile,
194 ((StructureFile) alignFile).setDbRefType(
195 FileFormat.PDB.equals(fileFormat) ? Type.PDB : Type.MMCIF);
197 else if (selectedFile != null)
199 alignFile = fileFormat
200 .getReader(new FileParse(selectedFile, sourceType));
204 // alignFile = fileFormat.getAlignmentFile(inFile, sourceType);
205 alignFile = fileFormat.getReader(new FileParse(inFile, sourceType));
207 return buildAlignmentFromFile();
208 } catch (Exception e)
211 System.err.println("Failed to read alignment using the '" + fileFormat
212 + "' reader.\n" + e);
214 if (e.getMessage() != null
215 && e.getMessage().startsWith(INVALID_CHARACTERS))
217 throw new IOException(e.getMessage());
220 // Finally test if the user has pasted just the sequence, no id
221 if (sourceType == DataSourceType.PASTE)
225 // Possible sequence is just residues with no label
226 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
227 DataSourceType.PASTE);
228 return buildAlignmentFromFile();
230 } catch (Exception ex)
232 if (ex.toString().startsWith(INVALID_CHARACTERS))
234 throw new IOException(e.getMessage());
237 ex.printStackTrace();
240 if (FileFormat.Html.equals(fileFormat))
242 throw new IOException(e.getMessage());
245 throw new FileFormatException(getSupportedFormats());
249 * Constructs the correct filetype parser for an already open datasource
252 * an existing datasource
254 * File format of data that will be provided by datasource
258 public AlignmentI readFromFile(FileParse source, FileFormatI format)
261 this.inFile = source.getInFile();
262 DataSourceType type = source.dataSourceType;
265 if (FileFormat.PDB.equals(format) || FileFormat.MMCif.equals(format))
267 // TODO obtain config value from preference settings
268 boolean isParseWithJMOL = false;
271 StructureImportSettings.addSettings(annotFromStructure,
272 localSecondaryStruct, serviceSecondaryStruct);
273 alignFile = new JmolParser(source);
277 StructureImportSettings.setShowSeqFeatures(true);
278 alignFile = new mc_view.PDBfile(annotFromStructure,
279 localSecondaryStruct, serviceSecondaryStruct, source);
281 ((StructureFile) alignFile).setDbRefType(Type.PDB);
285 alignFile = format.getReader(source);
288 return buildAlignmentFromFile();
290 } catch (Exception e)
293 System.err.println("Failed to read alignment using the '" + format
294 + "' reader.\n" + e);
296 if (e.getMessage() != null
297 && e.getMessage().startsWith(INVALID_CHARACTERS))
299 throw new FileFormatException(e.getMessage());
302 // Finally test if the user has pasted just the sequence, no id
303 if (type == DataSourceType.PASTE)
307 // Possible sequence is just residues with no label
308 alignFile = new FastaFile(">UNKNOWN\n" + inFile,
309 DataSourceType.PASTE);
310 return buildAlignmentFromFile();
312 } catch (Exception ex)
314 if (ex.toString().startsWith(INVALID_CHARACTERS))
316 throw new IOException(e.getMessage());
319 ex.printStackTrace();
323 // If we get to this stage, the format was not supported
324 throw new FileFormatException(getSupportedFormats());
329 * boilerplate method to handle data from an AlignFile and construct a new
330 * alignment or import to an existing alignment
332 * @return AlignmentI instance ready to pass to a UI constructor
334 private AlignmentI buildAlignmentFromFile()
336 // Standard boilerplate for creating alignment from parser
337 // alignFile.configureForView(viewpanel);
339 AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
341 alignFile.addAnnotations(al);
343 alignFile.addGroups(al);
349 * create an alignment flatfile from a Jalview alignment view
354 * @param selectedOnly
355 * @return flatfile in a string
357 public String formatSequences(FileFormatI format, boolean jvsuffix,
358 AlignmentViewPanel ap, boolean selectedOnly)
361 AlignmentView selvew = ap.getAlignViewport()
362 .getAlignmentView(selectedOnly, false);
363 AlignmentI aselview = selvew
364 .getVisibleAlignment(ap.getAlignViewport().getGapCharacter());
365 List<AlignmentAnnotation> ala = (ap.getAlignViewport()
366 .getVisibleAlignmentAnnotation(selectedOnly));
369 for (AlignmentAnnotation aa : ala)
371 aselview.addAnnotation(aa);
375 return formatSequences(format, aselview, jvsuffix);
379 * Construct an output class for an alignment in a particular filetype TODO:
380 * allow caller to detect errors and warnings encountered when generating
384 * string name of alignment format
386 * the alignment to be written out
388 * passed to AlnFile class controls whether /START-END is added to
391 * @return alignment flat file contents
393 public String formatSequences(FileFormatI format, AlignmentI alignment,
398 AlignmentFileWriterI afile = format.getWriter(alignment);
400 afile.setNewlineString(newline);
401 afile.setExportSettings(exportSettings);
402 afile.configureForView(viewpanel);
404 // check whether we were given a specific alignment to export, rather than
405 // the one in the viewpanel
406 SequenceI[] seqs = null;
407 if (viewpanel == null || viewpanel.getAlignment() == null
408 || viewpanel.getAlignment() != alignment)
410 seqs = alignment.getSequencesArray();
414 seqs = viewpanel.getAlignment().getSequencesArray();
417 String afileresp = afile.print(seqs, jvsuffix);
418 if (afile.hasWarningMessage())
420 System.err.println("Warning raised when writing as " + format
421 + " : " + afile.getWarningMessage());
424 } catch (Exception e)
426 System.err.println("Failed to write alignment as a '"
427 + format.getName() + "' file\n");
435 * Determines the protocol (i.e DataSourceType.{FILE|PASTE|URL}) for the input
438 * BH 2018 allows File or String, and can return RELATIVE_URL
442 * @return the protocol for the input data
444 public static DataSourceType checkProtocol(Object dataObject)
446 if (dataObject instanceof File)
448 return DataSourceType.FILE;
451 String data = dataObject.toString();
452 DataSourceType protocol = DataSourceType.PASTE;
453 String ft = data.toLowerCase(Locale.ROOT).trim();
454 if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
455 || ft.indexOf("file:") == 0)
457 protocol = DataSourceType.URL;
459 else if (Platform.isJS())
461 protocol = DataSourceType.RELATIVE_URL;
463 else if (new File(data).exists())
465 protocol = DataSourceType.FILE;
474 public static void main(String[] args)
477 while (i < args.length)
479 File f = new File(args[i]);
484 System.out.println("Reading file: " + f);
485 AppletFormatAdapter afa = new AppletFormatAdapter();
486 Runtime r = Runtime.getRuntime();
488 long memf = -r.totalMemory() + r.freeMemory();
489 long t1 = -System.currentTimeMillis();
490 AlignmentI al = afa.readFile(args[i], DataSourceType.FILE,
491 new IdentifyFile().identify(args[i],
492 DataSourceType.FILE));
493 t1 += System.currentTimeMillis();
495 memf += r.totalMemory() - r.freeMemory();
498 System.out.println("Alignment contains " + al.getHeight()
499 + " sequences and " + al.getWidth() + " columns.");
502 System.out.println(new AppletFormatAdapter()
503 .formatSequences(FileFormat.Fasta, al, true));
504 } catch (Exception e)
507 "Couln't format the alignment for output as a FASTA file.");
508 e.printStackTrace(System.err);
513 System.out.println("Couldn't read alignment");
515 System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
517 "Difference between free memory now and before is "
518 + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
519 } catch (Exception e)
521 System.err.println("Exception when dealing with " + i
522 + "'th argument: " + args[i] + "\n" + e);
527 System.err.println("Ignoring argument '" + args[i] + "' (" + i
528 + "'th)- not a readable file.");
535 * try to discover how to access the given file as a valid datasource that
536 * will be identified as the given type.
540 * @return protocol that yields the data parsable as the given type
542 public static DataSourceType resolveProtocol(String file,
545 return resolveProtocol(file, format, false);
548 public static DataSourceType resolveProtocol(String file,
549 FileFormatI format, boolean debug)
551 // TODO: test thoroughly!
552 DataSourceType protocol = null;
555 System.out.println("resolving datasource started with:\n>>file\n"
556 + file + ">>endfile");
559 // This might throw a security exception in certain browsers
560 // Netscape Communicator for instance.
564 InputStream is = System.getSecurityManager().getClass()
565 .getResourceAsStream("/" + file);
573 System.err.println("Resource '" + file + "' was "
574 + (rtn ? "" : "not") + " located by classloader.");
578 protocol = DataSourceType.CLASSLOADER;
581 } catch (Exception ex)
584 .println("Exception checking resources: " + file + " " + ex);
587 if (file.indexOf("://") > -1)
589 protocol = DataSourceType.URL;
593 // skipping codebase prepend check.
594 protocol = DataSourceType.FILE;
602 "Trying to get contents of resource as " + protocol + ":");
604 fp = new FileParse(file, protocol);
613 System.out.println("Successful.");
616 } catch (Exception e)
620 System.err.println("Exception when accessing content: " + e);
628 System.out.println("Accessing as paste.");
630 protocol = DataSourceType.PASTE;
634 fp = new FileParse(file, protocol);
639 } catch (Exception e)
641 System.err.println("Failed to access content as paste!");
658 FileFormatI idformat = new IdentifyFile().identify(file, protocol);
659 if (idformat == null)
663 System.out.println("Format not identified. Inaccessible file.");
669 System.out.println("Format identified as " + idformat
670 + "and expected as " + format);
672 if (idformat.equals(format))
676 System.out.println("Protocol identified as " + protocol);
685 .println("File deemed not accessible via " + protocol);
690 } catch (Exception e)
694 System.err.println("File deemed not accessible via " + protocol);
702 public AlignmentFileReaderI getAlignFile()