3 import jalview.api.JalviewApp;
4 import jalview.api.StructureSelectionManagerProvider;
5 import jalview.datamodel.PDBEntry;
6 import jalview.datamodel.Sequence;
7 import jalview.datamodel.SequenceI;
8 import jalview.io.AnnotationFile;
9 import jalview.io.DataSourceType;
10 import jalview.io.JPredFile;
11 import jalview.io.JnetAnnotationMaker;
12 import jalview.io.NewickFile;
13 import jalview.structure.StructureSelectionManager;
14 import jalview.util.HttpUtils;
15 import jalview.util.MessageManager;
18 import java.util.ArrayList;
19 import java.util.List;
20 import java.util.StringTokenizer;
21 import java.util.Vector;
24 * A class to load parameters for either JalviewLite or Jalview
29 public class JalviewAppLoader
32 private JalviewApp app; // Jalview or JalviewJS or JalviewLite
34 private boolean debug;
36 private String separator;
38 public JalviewAppLoader(boolean debug)
43 public void load(JalviewApp app)
48 String sep = app.getParameter("separator");
57 throw new Error(MessageManager
58 .getString("error.invalid_separator_parameter"));
72 * Load PDBFiles if any specified by parameter(s). Returns true if loaded,
78 protected boolean loadPdbFiles()
80 boolean result = false;
82 * <param name="alignpdbfiles" value="false/true"/> Undocumented for 2.6 -
86 boolean doAlign = app.getDefaultParameter("alignpdbfiles", false);
87 app.setAlignPdbStructures(doAlign);
89 * <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B
92 * <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
94 * <param name="PDBfile3" value="1q0o Q45135_9MICO">
97 // Accumulate pdbs here if they are heading for the same view (if
98 // alignPdbStructures is true)
99 Vector<Object[]> pdbs = new Vector<>();
100 // create a lazy matcher if we're asked to
101 jalview.analysis.SequenceIdMatcher matcher = (app
102 .getDefaultParameter("relaxedidmatch", false))
103 ? new jalview.analysis.SequenceIdMatcher(
104 app.getViewport().getAlignment()
105 .getSequencesArray())
108 int pdbFileCount = 0;
112 if (pdbFileCount > 0)
114 param = app.getParameter("PDBFILE" + pdbFileCount);
118 param = app.getParameter("PDBFILE");
123 PDBEntry pdb = new PDBEntry();
126 SequenceI[] seqs = null;
127 String[] chains = null;
129 StringTokenizer st = new StringTokenizer(param, " ");
131 if (st.countTokens() < 2)
133 String sequence = app.getParameter("PDBSEQ");
134 if (sequence != null)
136 seqs = new SequenceI[] { matcher == null
137 ? (Sequence) app.getViewport().getAlignment()
139 : matcher.findIdMatch(sequence) };
145 param = st.nextToken();
146 List<SequenceI> tmp = new ArrayList<>();
147 List<String> tmp2 = new ArrayList<>();
149 while (st.hasMoreTokens())
151 seqstring = st.nextToken();
152 StringTokenizer st2 = new StringTokenizer(seqstring, "=");
153 if (st2.countTokens() > 1)
156 tmp2.add(st2.nextToken());
157 seqstring = st2.nextToken();
159 tmp.add(matcher == null
160 ? (Sequence) app.getViewport().getAlignment()
162 : matcher.findIdMatch(seqstring));
165 seqs = tmp.toArray(new SequenceI[tmp.size()]);
166 if (tmp2.size() == tmp.size())
168 chains = tmp2.toArray(new String[tmp2.size()]);
173 DataSourceType protocol = resolveFileProtocol(app, ret);
174 // TODO check JAL-357 for files in a jar (CLASSLOADER)
179 for (int i = 0; i < seqs.length; i++)
183 ((Sequence) seqs[i]).addPDBId(pdb);
184 StructureSelectionManager
185 .getStructureSelectionManager(
186 (StructureSelectionManagerProvider) app)
187 .registerPDBEntry(pdb);
193 // this may not really be a problem but we give a warning
196 "Warning: Possible input parsing error: Null sequence for attachment of PDB (sequence "
204 pdbs.addElement(new Object[] { pdb, seqs, chains, protocol });
208 app.newStructureView(pdb, seqs, chains, protocol);
214 } while (param != null || pdbFileCount < 10);
217 SequenceI[][] seqs = new SequenceI[pdbs.size()][];
218 PDBEntry[] pdb = new PDBEntry[pdbs.size()];
219 String[][] chains = new String[pdbs.size()][];
220 String[] protocols = new String[pdbs.size()];
221 for (int pdbsi = 0, pdbsiSize = pdbs
222 .size(); pdbsi < pdbsiSize; pdbsi++)
224 Object[] o = pdbs.elementAt(pdbsi);
225 pdb[pdbsi] = (PDBEntry) o[0];
226 seqs[pdbsi] = (SequenceI[]) o[1];
227 chains[pdbsi] = (String[]) o[2];
228 protocols[pdbsi] = (String) o[3];
230 app.alignedStructureView(pdb, seqs, chains, protocols);
237 * Load in a Jnetfile if specified by parameter. Returns true if loaded, else
243 protected boolean loadJnetFile()
245 boolean result = false;
246 String param = app.getParameter("jnetfile");
249 // jnet became jpred around 2016
250 param = app.getParameter("jpredfile");
257 DataSourceType protocol = resolveFileProtocol(app,
259 JPredFile predictions = new JPredFile(ret[0], protocol);
260 JnetAnnotationMaker.add_annotation(predictions,
261 app.getViewport().getAlignment(), 0, false);
262 // false == do not add sequence profile from concise output
263 app.getViewport().getAlignment().setupJPredAlignment();
264 app.updateForAnnotations();
266 } catch (Exception ex)
268 ex.printStackTrace();
275 * Load annotations if specified by parameter. Returns true if loaded, else
281 protected boolean loadAnnotations()
283 boolean result = false;
284 String param = app.getParameter("annotations");
288 DataSourceType protocol = resolveFileProtocol(app,
291 if (new AnnotationFile().annotateAlignmentView(app.getViewport(),
294 app.updateForAnnotations();
300 .println("Annotations were not added from annotation file '"
308 * Load features file and view settings as specified by parameters. Returns
309 * true if features were loaded, else false.
314 protected boolean loadFeatures()
316 boolean result = false;
317 // ///////////////////////////
318 // modify display of features
319 // we do this before any features have been loaded, ensuring any hidden
320 // groups are hidden when features first displayed
322 // hide specific groups
324 String param = app.getParameter("hidefeaturegroups");
327 app.setFeatureGroupState(
328 separatorListToArray(param, separator), false);
329 // app.setFeatureGroupStateOn(newAlignFrame, param, false);
331 // show specific groups
332 param = app.getParameter("showfeaturegroups");
335 app.setFeatureGroupState(separatorListToArray(param, separator),
337 // app.setFeatureGroupStateOn(newAlignFrame, param, true);
339 // and now load features
340 param = app.getParameter("features");
344 DataSourceType protocol = resolveFileProtocol(app,
347 result = app.parseFeaturesFile(ret[0], protocol);
350 param = app.getParameter("showFeatureSettings");
351 if (param != null && param.equalsIgnoreCase("true"))
353 app.newFeatureSettings();
359 * Load a score file if specified by parameter. Returns true if file was
360 * loaded, else false.
364 protected boolean loadScoreFile()
366 boolean result = false;
367 String sScoreFile = app.getParameter("scoreFile");
368 if (sScoreFile != null && !"".equals(sScoreFile))
375 "Attempting to load T-COFFEE score file from the scoreFile parameter");
377 result = app.loadScoreFile(sScoreFile);
381 "Failed to parse T-COFFEE parameter as a valid score file ('"
382 + sScoreFile + "')");
384 } catch (Exception e)
386 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
387 sScoreFile, e.getMessage());
393 String[] ret = new String[1];
395 * Load a tree for the alignment if specified by parameter. Returns true if a
396 * tree was loaded, else false.
401 protected boolean loadTree()
403 boolean result = false;
404 String treeFile = app.getParameter("tree");
405 if (treeFile == null)
407 treeFile = app.getParameter("treeFile");
410 if (treeFile != null)
415 NewickFile fin = new NewickFile(treeFile,
416 resolveFileProtocol(app, ret));
419 if (fin.getTree() != null)
421 app.loadTree(fin, ret[0]);
425 System.out.println("Successfully imported tree.");
432 System.out.println("Tree parameter did not resolve to a valid tree.");
435 } catch (Exception ex)
437 ex.printStackTrace();
444 * form a complete URL given a path to a resource and a reference location on
448 * - an absolute path on the same server as localref or a document
449 * located relative to localref
451 * - a URL on the same server as url
452 * @return a complete URL for the resource located by url
454 public static String resolveUrlForLocalOrAbsolute(String targetPath,
457 String resolvedPath = "";
458 if (targetPath.startsWith("/"))
460 String codebase = localref.toString();
461 String localfile = localref.getFile();
462 resolvedPath = codebase.substring(0,
463 codebase.length() - localfile.length()) + targetPath;
468 * get URL path and strip off any trailing file e.g.
469 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
470 * www.jalview.org/examples/
472 String urlPath = localref.toString();
473 String directoryPath = urlPath;
474 int lastSeparator = directoryPath.lastIndexOf("/");
475 if (lastSeparator > 0)
477 directoryPath = directoryPath.substring(0, lastSeparator + 1);
480 if (targetPath.startsWith("/"))
483 * construct absolute URL to a file on the server - this is not allowed?
485 // String localfile = localref.getFile();
486 // resolvedPath = urlPath.substring(0,
487 // urlPath.length() - localfile.length())
489 resolvedPath = directoryPath + targetPath.substring(1);
493 resolvedPath = directoryPath + targetPath;
495 if (JalviewLite.debug)
498 "resolveUrlForLocalOrAbsolute returning " + resolvedPath);
504 * parse the string into a list
508 * @return elements separated by separator
510 public static String[] separatorListToArray(String list, String separator)
512 // TODO use StringUtils version (slightly different...)
513 int seplen = separator.length();
514 if (list == null || list.equals("") || list.equals(separator))
518 Vector<String> jv = new Vector<>();
520 while ((pos = list.indexOf(separator, cp)) > cp)
522 jv.addElement(list.substring(cp, pos));
525 if (cp < list.length())
527 String c = list.substring(cp);
528 if (!c.equals(separator))
535 String[] v = new String[jv.size()];
536 for (int i = 0; i < v.length; i++)
538 v[i] = jv.elementAt(i);
540 jv.removeAllElements();
543 // System.err.println("Array from '" + separator
544 // + "' separated List:\n" + v.length);
545 // for (int i = 0; i < v.length; i++)
547 // System.err.println("item " + i + " '" + v[i] + "'");
554 // System.err.println(
555 // "Empty Array from '" + separator + "' separated List");
560 public static DataSourceType resolveFileProtocol(JalviewApp app,
563 String path = retPath[0];
567 if (path.startsWith("PASTE"))
569 retPath[0] = path.substring(5);
570 return DataSourceType.PASTE;
576 if (path.indexOf("://") >= 0)
578 return DataSourceType.URL;
582 * try relative to document root
584 URL documentBase = app.getDocumentBase();
585 String withDocBase = resolveUrlForLocalOrAbsolute(path,
587 if (HttpUtils.isValidUrl(withDocBase))
591 // System.err.println("Prepended document base '" + documentBase
592 // + "' to make: '" + withDocBase + "'");
594 retPath[0] = withDocBase;
595 return DataSourceType.URL;
599 * try relative to codebase (if different to document base)
601 URL codeBase = app.getCodeBase();
602 String withCodeBase = resolveUrlForLocalOrAbsolute(path,
604 if (!withCodeBase.equals(withDocBase)
605 && HttpUtils.isValidUrl(withCodeBase))
609 // System.err.println("Prepended codebase '" + codeBase
610 // + "' to make: '" + withCodeBase + "'");
612 retPath[0] = withCodeBase;
613 return DataSourceType.URL;
617 * try locating by classloader; try this last so files in the directory
618 * are resolved using document base
620 if (inArchive(app.getClass(), path))
622 return DataSourceType.CLASSLOADER;
628 * Discovers whether the given file is in the Applet Archive
634 private static boolean inArchive(Class<?> c, String f)
636 // This might throw a security exception in certain browsers
637 // Netscape Communicator for instance.
640 boolean rtn = (c.getResourceAsStream("/" + f) != null);
643 // System.err.println("Resource '" + f + "' was "
644 // + (rtn ? "" : "not ") + "located by classloader.");
647 } catch (Exception ex)
649 System.out.println("Exception checking resources: " + f + " " + ex);
654 public void callInitCallback()
656 String initjscallback = app.getParameter("oninit");
657 if (initjscallback == null)
661 initjscallback = initjscallback.trim();
662 if (initjscallback.length() > 0)
669 * read sequence1...sequenceN as a raw alignment
674 public String getPastedSequence(JalviewApp jalviewApp) {
675 StringBuffer data = new StringBuffer("PASTE");
678 while ((file = app.getParameter("sequence" + i)) != null)
680 data.append(file.toString() + "\n");
683 if (data.length() > 5)
685 file = data.toString();