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, ret);
258 JPredFile predictions = new JPredFile(ret[0], protocol);
259 JnetAnnotationMaker.add_annotation(predictions,
260 app.getViewport().getAlignment(), 0, false);
261 // false == do not add sequence profile from concise output
262 app.getViewport().getAlignment().setupJPredAlignment();
263 app.updateForAnnotations();
265 } catch (Exception ex)
267 ex.printStackTrace();
274 * Load annotations if specified by parameter. Returns true if loaded, else
280 protected boolean loadAnnotations()
282 boolean result = false;
283 String param = app.getParameter("annotations");
287 DataSourceType protocol = resolveFileProtocol(app, ret);
289 if (new AnnotationFile().annotateAlignmentView(app.getViewport(),
292 app.updateForAnnotations();
298 .println("Annotations were not added from annotation file '"
306 * Load features file and view settings as specified by parameters. Returns
307 * true if features were loaded, else false.
312 protected boolean loadFeatures()
314 boolean result = false;
315 // ///////////////////////////
316 // modify display of features
317 // we do this before any features have been loaded, ensuring any hidden
318 // groups are hidden when features first displayed
320 // hide specific groups
322 String param = app.getParameter("hidefeaturegroups");
325 app.setFeatureGroupState(separatorListToArray(param, separator),
327 // app.setFeatureGroupStateOn(newAlignFrame, param, false);
329 // show specific groups
330 param = app.getParameter("showfeaturegroups");
333 app.setFeatureGroupState(separatorListToArray(param, separator),
335 // app.setFeatureGroupStateOn(newAlignFrame, param, true);
337 // and now load features
338 param = app.getParameter("features");
342 DataSourceType protocol = resolveFileProtocol(app, ret);
344 result = app.parseFeaturesFile(ret[0], protocol);
347 param = app.getParameter("showFeatureSettings");
348 if (param != null && param.equalsIgnoreCase("true"))
350 app.newFeatureSettings();
356 * Load a score file if specified by parameter. Returns true if file was
357 * loaded, else false.
361 protected boolean loadScoreFile()
363 boolean result = false;
364 String sScoreFile = app.getParameter("scoreFile");
365 if (sScoreFile != null && !"".equals(sScoreFile))
372 "Attempting to load T-COFFEE score file from the scoreFile parameter");
374 result = app.loadScoreFile(sScoreFile);
378 "Failed to parse T-COFFEE parameter as a valid score file ('"
379 + sScoreFile + "')");
381 } catch (Exception e)
383 System.err.printf("Cannot read score file: '%s'. Cause: %s \n",
384 sScoreFile, e.getMessage());
390 String[] ret = new String[1];
393 * Load a tree for the alignment if specified by parameter. Returns true if a
394 * tree was loaded, else false.
399 protected boolean loadTree()
401 boolean result = false;
402 String treeFile = app.getParameter("tree");
403 if (treeFile == null)
405 treeFile = app.getParameter("treeFile");
408 if (treeFile != null)
413 NewickFile fin = new NewickFile(treeFile,
414 resolveFileProtocol(app, ret));
417 if (fin.getTree() != null)
419 app.loadTree(fin, ret[0]);
423 System.out.println("Successfully imported tree.");
431 "Tree parameter did not resolve to a valid tree.");
434 } catch (Exception ex)
436 ex.printStackTrace();
443 * form a complete URL given a path to a resource and a reference location on
447 * - an absolute path on the same server as localref or a document
448 * located relative to localref
450 * - a URL on the same server as url
451 * @return a complete URL for the resource located by url
453 public static String resolveUrlForLocalOrAbsolute(String targetPath,
456 String resolvedPath = "";
457 if (targetPath.startsWith("/"))
459 String codebase = localref.toString();
460 String localfile = localref.getFile();
461 resolvedPath = codebase.substring(0,
462 codebase.length() - localfile.length()) + targetPath;
467 * get URL path and strip off any trailing file e.g.
468 * www.jalview.org/examples/index.html#applets?a=b is trimmed to
469 * www.jalview.org/examples/
471 String urlPath = localref.toString();
472 String directoryPath = urlPath;
473 int lastSeparator = directoryPath.lastIndexOf("/");
474 if (lastSeparator > 0)
476 directoryPath = directoryPath.substring(0, lastSeparator + 1);
479 if (targetPath.startsWith("/"))
482 * construct absolute URL to a file on the server - this is not allowed?
484 // String localfile = localref.getFile();
485 // resolvedPath = urlPath.substring(0,
486 // urlPath.length() - localfile.length())
488 resolvedPath = directoryPath + targetPath.substring(1);
492 resolvedPath = directoryPath + targetPath;
494 if (JalviewLite.debug)
497 "resolveUrlForLocalOrAbsolute returning " + resolvedPath);
503 * parse the string into a list
507 * @return elements separated by separator
509 public static String[] separatorListToArray(String list, String separator)
511 // TODO use StringUtils version (slightly different...)
512 int seplen = separator.length();
513 if (list == null || list.equals("") || list.equals(separator))
517 Vector<String> jv = new Vector<>();
519 while ((pos = list.indexOf(separator, cp)) > cp)
521 jv.addElement(list.substring(cp, pos));
524 if (cp < list.length())
526 String c = list.substring(cp);
527 if (!c.equals(separator))
534 String[] v = new String[jv.size()];
535 for (int i = 0; i < v.length; i++)
537 v[i] = jv.elementAt(i);
539 jv.removeAllElements();
542 // System.err.println("Array from '" + separator
543 // + "' separated List:\n" + v.length);
544 // for (int i = 0; i < v.length; i++)
546 // System.err.println("item " + i + " '" + v[i] + "'");
553 // System.err.println(
554 // "Empty Array from '" + separator + "' separated List");
559 public static DataSourceType resolveFileProtocol(JalviewApp app,
562 String path = retPath[0];
566 if (path.startsWith("PASTE"))
568 retPath[0] = path.substring(5);
569 return DataSourceType.PASTE;
575 if (path.indexOf("://") >= 0)
577 return DataSourceType.URL;
581 * try relative to document root
583 URL documentBase = app.getDocumentBase();
584 String withDocBase = resolveUrlForLocalOrAbsolute(path, documentBase);
585 if (HttpUtils.isValidUrl(withDocBase))
589 // System.err.println("Prepended document base '" + documentBase
590 // + "' to make: '" + withDocBase + "'");
592 retPath[0] = withDocBase;
593 return DataSourceType.URL;
597 * try relative to codebase (if different to document base)
599 URL codeBase = app.getCodeBase();
600 String withCodeBase = resolveUrlForLocalOrAbsolute(path, codeBase);
601 if (!withCodeBase.equals(withDocBase)
602 && HttpUtils.isValidUrl(withCodeBase))
606 // System.err.println("Prepended codebase '" + codeBase
607 // + "' to make: '" + withCodeBase + "'");
609 retPath[0] = withCodeBase;
610 return DataSourceType.URL;
614 * try locating by classloader; try this last so files in the directory
615 * are resolved using document base
617 if (inArchive(app.getClass(), path))
619 return DataSourceType.CLASSLOADER;
625 * Discovers whether the given file is in the Applet Archive
631 private static boolean inArchive(Class<?> c, String f)
633 // This might throw a security exception in certain browsers
634 // Netscape Communicator for instance.
637 boolean rtn = (c.getResourceAsStream("/" + f) != null);
640 // System.err.println("Resource '" + f + "' was "
641 // + (rtn ? "" : "not ") + "located by classloader.");
644 } catch (Exception ex)
646 System.out.println("Exception checking resources: " + f + " " + ex);
651 public void callInitCallback()
653 String initjscallback = app.getParameter("oninit");
654 if (initjscallback == null)
658 initjscallback = initjscallback.trim();
659 if (initjscallback.length() > 0)
666 * read sequence1...sequenceN as a raw alignment
671 public String getPastedSequence(JalviewApp jalviewApp)
673 StringBuffer data = new StringBuffer("PASTE");
676 while ((file = app.getParameter("sequence" + i)) != null)
678 data.append(file.toString() + "\n");
681 if (data.length() > 5)
683 file = data.toString();
689 * concatenate the list with separator
693 * @return concatenated string
695 public static String arrayToSeparatorList(String[] list, String separator)
697 // TODO use StringUtils version
698 StringBuffer v = new StringBuffer();
699 if (list != null && list.length > 0)
701 for (int i = 0, iSize = list.length; i < iSize; i++)
715 // .println("Returning '" + separator + "' separated List:\n");
716 // System.err.println(v);
722 // System.err.println(
723 // "Returning empty '" + separator + "' separated List\n");
725 return "" + separator;
728 public String arrayToSeparatorList(String[] array)
730 return arrayToSeparatorList(array, separator);