2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3 * Copyright (C) 2014 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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 import java.io.BufferedReader;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.OutputStreamWriter;
26 import java.io.PrintWriter;
27 import java.lang.reflect.Constructor;
30 import java.net.URLDecoder;
31 import java.security.AllPermission;
32 import java.security.CodeSource;
33 import java.security.PermissionCollection;
34 import java.security.Permissions;
35 import java.security.Policy;
41 import jalview.util.Platform;
44 * Main class for Jalview Application <br>
46 * start with java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview
55 // grab all the rights we can the JVM
56 Policy.setPolicy(new Policy()
58 public PermissionCollection getPermissions(CodeSource codesource)
60 Permissions perms = new Permissions();
61 perms.add(new AllPermission());
72 * main class for Jalview application
75 * open <em>filename</em>
77 public static void main(String[] args)
79 System.out.println("Java version: "
80 + System.getProperty("java.version"));
81 System.out.println(System.getProperty("os.arch") + " "
82 + System.getProperty("os.name") + " "
83 + System.getProperty("os.version"));
84 if (new Platform().isAMac())
86 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
88 System.setProperty("apple.laf.useScreenMenuBar", "true");
91 ArgsParser aparser = new ArgsParser(args);
92 boolean headless = false;
94 if (aparser.contains("help") || aparser.contains("h"))
97 .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
98 + "-nodisplay\tRun Jalview without User Interface.\n"
99 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
100 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
101 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
102 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
103 + "-features FILE\tUse the given file to mark features on the alignment.\n"
104 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
105 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
106 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
107 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
108 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
109 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
110 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
111 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
112 + "-png FILE\tCreate PNG image FILE from alignment.\n"
113 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
114 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
115 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
116 + "-noquestionnaire\tTurn off questionnaire check.\n"
117 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
118 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
120 // "-setprop PROPERTY=VALUE\tSet the given Jalview property, after all other properties files have been read\n\t (quote the 'PROPERTY=VALUE' pair to ensure spaces are passed in correctly)"
121 + "-dasserver nickname=URL\tAdd and enable a das server with given nickname\n\t\t\t(alphanumeric or underscores only) for retrieval of features for all alignments.\n"
122 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
123 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
124 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
126 // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
127 // + "-vses vamsas-session\tJoin session with given URN\n"
128 + "-groovy FILE\tExecute groovy script in FILE, after all other arguments have been processed (if FILE is the text 'STDIN' then the file will be read from STDIN)\n"
129 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
132 if (aparser.contains("nodisplay") || aparser.contains("nogui") || aparser.contains("headless"))
134 System.setProperty("java.awt.headless", "true");
137 Cache.loadProperties(aparser.getValue("props")); // must do this before
139 String defs = aparser.getValue("setprop");
142 int p = defs.indexOf('=');
145 System.err.println("Ignoring invalid setprop argument : " + defs);
149 System.out.println("Executing setprop argument: " + defs);
150 // DISABLED FOR SECURITY REASONS
151 // TODO: add a property to allow properties to be overriden by cli args
152 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
154 defs = aparser.getValue("setprop");
156 if (System.getProperty("java.awt.headless") != null
157 && System.getProperty("java.awt.headless").equals("true"))
161 System.setProperty("http.agent", "Jalview Desktop/"+Cache.getDefault("VERSION", "Unknown"));
165 } catch (java.lang.NoClassDefFoundError error)
167 error.printStackTrace();
169 .println("\nEssential logging libraries not found."
170 + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
174 Desktop desktop = null;
178 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
179 } catch (Exception ex)
185 desktop = new Desktop();
186 desktop.setInBatchMode(true); // indicate we are starting up
187 desktop.setVisible(true);
188 desktop.startServiceDiscovery();
189 if (!aparser.contains("nousagestats"))
191 startUsageStats(desktop);
193 if (!aparser.contains("noquestionnaire"))
195 String url = aparser.getValue("questionnaire");
198 // Start the desktop questionnaire prompter with the specified
200 Cache.log.debug("Starting questionnaire url at " + url);
201 desktop.checkForQuestionnaire(url);
205 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
207 // Start the desktop questionnaire prompter with the specified
210 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
212 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
213 Cache.log.debug("Starting questionnaire with default url: "
215 desktop.checkForQuestionnaire(defurl);
220 desktop.checkForNews();
223 String file = null, protocol = null, format = null, data = null;
224 jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
225 Vector getFeatures = null; // vector of das source nicknames to fetch
228 String groovyscript = null; // script to execute after all loading is
229 // completed one way or another
230 // extract groovy argument and execute if necessary
231 groovyscript = aparser.getValue("groovy", true);
232 file = aparser.getValue("open", true);
234 if (file == null && desktop == null)
236 System.out.println("No files to open!");
239 String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
241 if (vamsasImport != null || vamsasSession != null)
243 if (desktop == null || headless)
246 .println("Headless vamsas sessions not yet supported. Sorry.");
249 // if we have a file, start a new session and import it.
250 boolean inSession = false;
251 if (vamsasImport != null)
255 String viprotocol = jalview.io.AppletFormatAdapter
256 .checkProtocol(vamsasImport);
257 if (viprotocol == jalview.io.FormatAdapter.FILE)
259 inSession = desktop.vamsasImport(new File(vamsasImport));
261 else if (viprotocol == jalview.io.FormatAdapter.URL)
263 inSession = desktop.vamsasImport(new URL(vamsasImport));
266 } catch (Exception e)
268 System.err.println("Exeption when importing " + vamsasImport
269 + " as a vamsas document.");
274 System.err.println("Failed to import " + vamsasImport
275 + " as a vamsas document.");
279 System.out.println("Imported Successfully into new session "
280 + desktop.getVamsasApplication().getCurrentSession());
283 if (vamsasSession != null)
285 if (vamsasImport != null)
287 // close the newly imported session and import the Jalview specific
288 // remnants into the new session later on.
289 desktop.vamsasStop_actionPerformed(null);
291 // now join the new session
294 if (desktop.joinVamsasSession(vamsasSession))
296 System.out.println("Successfully joined vamsas session "
301 System.err.println("WARNING: Failed to join vamsas session "
304 } catch (Exception e)
306 System.err.println("ERROR: Failed to join vamsas session "
310 if (vamsasImport != null)
312 // the Jalview specific remnants can now be imported into the new
313 // session at the user's leisure.
315 .info("Skipping Push for import of data into existing vamsas session."); // TODO:
320 // desktop.getVamsasApplication().push_update();
325 // Finally, deal with the remaining input data.
330 desktop.setProgressBar("Processing commandline arguments...",
331 progress = System.currentTimeMillis());
333 System.out.println("Opening file: " + file);
335 if (!file.startsWith("http://"))
337 if (!(new java.io.File(file)).exists())
339 System.out.println("Can't find " + file);
347 protocol = jalview.io.AppletFormatAdapter.checkProtocol(file);
349 format = new jalview.io.IdentifyFile().Identify(file, protocol);
351 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
355 System.out.println("error");
360 data = aparser.getValue("colour", true);
363 data.replaceAll("%20", " ");
365 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
366 .getColour(af.getViewport().getAlignment(), data);
370 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
372 ucs.parseAppletParameter(data);
376 System.out.println("colour is " + data);
380 // Must maintain ability to use the groups flag
381 data = aparser.getValue("groups", true);
384 af.parseFeaturesFile(data,
385 jalview.io.AppletFormatAdapter.checkProtocol(data));
386 System.out.println("Added " + data);
388 data = aparser.getValue("features", true);
391 af.parseFeaturesFile(data,
392 jalview.io.AppletFormatAdapter.checkProtocol(data));
393 System.out.println("Added " + data);
396 data = aparser.getValue("annotations", true);
399 af.loadJalviewDataFile(data, null, null, null);
400 System.out.println("Added " + data);
402 // set or clear the sortbytree flag.
403 if (aparser.contains("sortbytree"))
405 af.getViewport().setSortByTree(true);
407 if (aparser.contains("nosortbytree"))
409 af.getViewport().setSortByTree(false);
411 data = aparser.getValue("tree", true);
414 jalview.io.NewickFile fin = null;
417 fin = new jalview.io.NewickFile(data,
418 jalview.io.AppletFormatAdapter.checkProtocol(data));
421 af.getViewport().setCurrentTree(
422 af.ShowNewickTree(fin, data).getTree());
423 System.out.println("Added tree " + data);
425 } catch (IOException ex)
427 System.err.println("Couldn't add tree " + data);
428 ex.printStackTrace(System.err);
431 // TODO - load PDB structure(s) to alignment JAL-629
432 // (associate with identical sequence in alignment, or a specified
435 getFeatures = checkDasArguments(aparser);
436 if (af != null && getFeatures != null)
438 FeatureFetcher ff = startFeatureFetching(getFeatures);
440 while (!ff.allFinished() || af.operationInProgress())
442 // wait around until fetching is finished.
446 } catch (Exception e)
451 getFeatures = null; // have retrieved features - forget them now.
453 if (groovyscript != null)
455 // Execute the groovy script after we've done all the rendering stuff
456 // and before any images or figures are generated.
457 if (jalview.bin.Cache.groovyJarsPresent())
459 System.out.println("Executing script " + groovyscript);
460 executeGroovyScript(groovyscript, new Object[]
466 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
471 String imageName = "unnamed.png";
472 while (aparser.getSize() > 1)
474 format = aparser.nextValue();
475 file = aparser.nextValue();
477 if (format.equalsIgnoreCase("png"))
479 af.createPNG(new java.io.File(file));
480 imageName = (new java.io.File(file)).getName();
481 System.out.println("Creating PNG image: " + file);
484 else if (format.equalsIgnoreCase("imgMap"))
486 af.createImageMap(new java.io.File(file), imageName);
487 System.out.println("Creating image map: " + file);
490 else if (format.equalsIgnoreCase("eps"))
492 System.out.println("Creating EPS file: " + file);
493 af.createEPS(new java.io.File(file));
497 if (af.saveAlignment(file, format))
499 System.out.println("Written alignment in " + format
500 + " format to " + file);
504 System.out.println("Error writing file " + file + " in "
505 + format + " format!!");
510 while (aparser.getSize() > 0)
512 System.out.println("Unknown arg: " + aparser.nextValue());
516 AlignFrame startUpAlframe = null;
517 // We'll only open the default file if the desktop is visible.
519 // ////////////////////
520 if (!headless && file == null && vamsasImport == null
521 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
523 file = jalview.bin.Cache.getDefault(
525 jalview.bin.Cache.getDefault("www.jalview.org",
526 "http://www.jalview.org")
527 + "/examples/exampleFile_2_7.jar");
528 if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar"))
530 // hardwire upgrade of the startup file
531 file.replace("_2_3.jar", "_2_7.jar");
532 // and remove the stale setting
533 jalview.bin.Cache.removeProperty("STARTUP_FILE");
538 if (file.indexOf("http:") > -1)
543 if (file.endsWith(".jar"))
549 format = new jalview.io.IdentifyFile().Identify(file, protocol);
552 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
554 getFeatures = checkDasArguments(aparser);
555 // extract groovy arguments before anything else.
557 // If the user has specified features to be retrieved,
558 // or a groovy script to be executed, do them if they
559 // haven't been done already
560 // fetch features for the default alignment
561 if (getFeatures != null)
563 if (startUpAlframe != null)
565 startFeatureFetching(getFeatures);
568 // Once all other stuff is done, execute any groovy scripts (in order)
569 if (groovyscript != null)
571 if (jalview.bin.Cache.groovyJarsPresent())
573 System.out.println("Executing script " + groovyscript);
574 executeGroovyScript(groovyscript, new Object[]
575 { desktop, startUpAlframe });
580 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
584 // and finally, turn off batch mode indicator - if the desktop still exists
589 desktop.setProgressBar(null, progress);
591 desktop.setInBatchMode(false);
595 private static void startUsageStats(final Desktop desktop)
598 * start a User Config prompt asking if we can log usage statistics.
600 jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
603 "Jalview Usage Statistics",
604 "Do you want to help make Jalview better by enabling "
605 + "the collection of usage statistics with Google Analytics ?"
606 + "\n\n(you can enable or disable usage tracking in the preferences)",
612 .info("Initialising googletracker for usage stats.");
613 Cache.initGoogleTracker();
614 Cache.log.debug("Tracking enabled.");
620 Cache.log.info("Not enabling Google Tracking.");
623 desktop.addDialogThread(prompter);
627 * Locate the given string as a file and pass it to the groovy interpreter.
629 * @param groovyscript
630 * the script to execute
631 * @param jalviewContext
632 * the Jalview Desktop object passed in to the groovy binding as the
635 private static void executeGroovyScript(String groovyscript,
636 Object[] jalviewContext)
638 if (jalviewContext == null)
641 .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
644 * for scripts contained in files
651 if (groovyscript.trim().equals("STDIN"))
653 // read from stdin into a tempfile and execute it
656 tfile = File.createTempFile("jalview", "groovy");
657 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
658 new FileOutputStream(tfile)));
659 BufferedReader br = new BufferedReader(
660 new java.io.InputStreamReader(System.in));
662 while ((line = br.readLine()) != null)
664 outfile.write(line + "\n");
670 } catch (Exception ex)
672 System.err.println("Failed to read from STDIN into tempfile "
673 + ((tfile == null) ? "(tempfile wasn't created)" : tfile
675 ex.printStackTrace();
680 sfile = tfile.toURI().toURL();
681 } catch (Exception x)
684 .println("Unexpected Malformed URL Exception for temporary file created from STDIN: "
694 sfile = new URI(groovyscript).toURL();
695 } catch (Exception x)
697 tfile = new File(groovyscript);
700 System.err.println("File '" + groovyscript + "' does not exist.");
703 if (!tfile.canRead())
705 System.err.println("File '" + groovyscript + "' cannot be read.");
708 if (tfile.length() < 1)
710 System.err.println("File '" + groovyscript + "' is empty.");
715 sfile = tfile.getAbsoluteFile().toURI().toURL();
716 } catch (Exception ex)
718 System.err.println("Failed to create a file URL for "
719 + tfile.getAbsoluteFile());
724 boolean success = false;
728 * The following code performs the GroovyScriptEngine invocation using
729 * reflection, and is equivalent to this fragment from the embedding
730 * groovy documentation on the groovy site: <code> import
731 * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
733 * String[] roots = new String[] { "/my/groovy/script/path" };
734 * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
735 * = new Binding(); binding.setVariable("input", "world");
736 * gse.run("hello.groovy", binding); </code>
740 int blen = ((jalviewContext[0] == null) ? 0 : 1)
741 + ((jalviewContext[1] == null) ? 0 : 1);
742 String cnames[] = new String[]
743 { "Jalview", "currentAlFrame" };
744 bspec = new Class[blen * 2];
745 binding = new Object[blen * 2];
747 ClassLoader cl = null;
748 Map vbinding = new Hashtable();
749 for (int jc = 0; jc < jalviewContext.length; jc++)
751 if (jalviewContext[jc] != null)
755 cl = jalviewContext[jc].getClass().getClassLoader();
757 bspec[blen * 2] = String.class;
758 bspec[blen * 2 + 1] = Object.class;
759 binding[blen * 2] = cnames[jc];
760 binding[blen * 2 + 1] = jalviewContext[jc];
761 vbinding.put(cnames[jc], jalviewContext[jc]);
765 Class gbindingc = cl.loadClass("groovy.lang.Binding");
770 gbcons = gbindingc.getConstructor(Map.class);
771 gbinding = gbcons.newInstance(vbinding);
772 } catch (NoSuchMethodException x)
774 // old style binding config - using series of string/object values to
776 gbcons = gbindingc.getConstructor(null);
777 gbinding = gbcons.newInstance(null);
778 java.lang.reflect.Method setvar = gbindingc.getMethod(
779 "setVariable", bspec);
780 setvar.invoke(gbinding, binding);
783 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
784 Constructor gseccons = gsec.getConstructor(new Class[]
785 { URL[].class }); // String[].class });
786 Object gse = gseccons.newInstance(new Object[]
788 { sfile } }); // .toString() } });
789 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
790 { String.class, gbindingc });
791 run.invoke(gse, new Object[]
792 { sfile.toString(), gbinding });
794 } catch (Exception e)
796 System.err.println("Exception Whilst trying to execute file " + sfile
797 + " as a groovy script.");
798 e.printStackTrace(System.err);
801 if (success && groovyscript.equals("STDIN"))
803 // delete temp file that we made - but only if it was successfully
810 * Check commandline for any das server definitions or any fetchfrom switches
812 * @return vector of DAS source nicknames to retrieve from
814 private static Vector checkDasArguments(ArgsParser aparser)
816 Vector source = null;
818 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
819 while ((data = aparser.getValue("dasserver", true)) != null)
821 String nickname = null;
823 boolean seq = false, feat = true;
824 int pos = data.indexOf('=');
825 // determine capabilities
828 nickname = data.substring(0, pos);
830 url = data.substring(pos + 1);
832 && (url.startsWith("http:") || url
833 .startsWith("sequence:http:")))
835 if (nickname == null)
839 if (locsources == null)
847 locsources = locsources + nickname + "|" + url;
849 .println("NOTE! dasserver parameter not yet really supported (got args of "
850 + nickname + "|" + url);
853 source = new Vector();
855 source.addElement(nickname);
857 } // loop until no more server entries are found.
858 if (locsources != null && locsources.indexOf('|') > -1)
860 Cache.log.debug("Setting local source list in properties file to:\n"
862 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
864 while ((data = aparser.getValue("fetchfrom", true)) != null)
866 System.out.println("adding source '" + data + "'");
869 source = new Vector();
871 source.addElement(data);
877 * start a feature fetcher for every alignment frame
881 private static FeatureFetcher startFeatureFetching(final Vector dasSources)
883 FeatureFetcher ff = new FeatureFetcher();
884 AlignFrame afs[] = Desktop.getAlignframes();
885 if (afs == null || afs.length == 0)
889 for (int i = 0; i < afs.length; i++)
891 ff.addFetcher(afs[i], dasSources);
898 * Notes: this argParser does not distinguish between parameter switches,
899 * parameter values and argument text. If an argument happens to be identical to
900 * a parameter, it will be taken as such (even though it didn't have a '-'
903 * @author Andrew Waterhouse and JBP documented.
910 public ArgsParser(String[] args)
912 vargs = new Vector();
913 for (int i = 0; i < args.length; i++)
915 String arg = args[i].trim();
916 if (arg.charAt(0) == '-')
918 arg = arg.substring(1);
920 vargs.addElement(arg);
925 * check for and remove first occurence of arg+parameter in arglist.
928 * @return return the argument following the given arg if arg was in list.
930 public String getValue(String arg)
932 return getValue(arg, false);
935 public String getValue(String arg, boolean utf8decode)
937 int index = vargs.indexOf(arg);
938 String dc = null, ret = null;
941 ret = vargs.elementAt(index + 1).toString();
942 vargs.removeElementAt(index);
943 vargs.removeElementAt(index);
944 if (utf8decode && ret != null)
948 dc = URLDecoder.decode(ret, "UTF-8");
950 } catch (Exception e)
952 // TODO: log failure to decode
960 * check for and remove first occurence of arg in arglist.
963 * @return true if arg was present in argslist.
965 public boolean contains(String arg)
967 if (vargs.contains(arg))
969 vargs.removeElement(arg);
978 public String nextValue()
980 return vargs.remove(0).toString();
991 * keep track of feature fetching tasks.
999 * TODO: generalise to track all jalview events to orchestrate batch
1000 * processing events.
1003 private int queued = 0;
1005 private int running = 0;
1007 public FeatureFetcher()
1012 public void addFetcher(final AlignFrame af, final Vector dasSources)
1014 final long id = System.currentTimeMillis();
1016 final FeatureFetcher us = this;
1017 new Thread(new Runnable()
1028 af.setProgressBar("DAS features being retrieved...", id);
1029 af.featureSettings_actionPerformed(null);
1030 af.featureSettings.fetchDasFeatures(dasSources, true);
1031 af.setProgressBar(null, id);
1040 public synchronized boolean allFinished()
1042 return queued == 0 && running == 0;