2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3 * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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/>.
20 import java.io.BufferedReader;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStreamWriter;
25 import java.io.PrintWriter;
26 import java.lang.reflect.Constructor;
27 import java.net.MalformedURLException;
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 Cache.loadProperties(aparser.getValue("props")); // must do this before
134 String defs = aparser.getValue("setprop");
137 int p = defs.indexOf('=');
140 System.err.println("Ignoring invalid setprop argument : " + defs);
144 System.out.println("Executing setprop argument: " + defs);
145 // DISABLED FOR SECURITY REASONS
146 // TODO: add a property to allow properties to be overriden by cli args
147 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
149 defs = aparser.getValue("setprop");
151 if (aparser.contains("nodisplay"))
153 System.setProperty("java.awt.headless", "true");
155 if (System.getProperty("java.awt.headless") != null
156 && System.getProperty("java.awt.headless").equals("true"))
164 } catch (java.lang.NoClassDefFoundError error)
166 error.printStackTrace();
168 .println("\nEssential logging libraries not found."
169 + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
173 Desktop desktop = null;
177 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
178 } catch (Exception ex)
184 desktop = new Desktop();
185 desktop.setInBatchMode(true); // indicate we are starting up
186 desktop.setVisible(true);
187 desktop.startServiceDiscovery();
188 if (!aparser.contains("nousagestats"))
190 startUsageStats(desktop);
192 if (!aparser.contains("noquestionnaire"))
194 String url = aparser.getValue("questionnaire");
197 // Start the desktop questionnaire prompter with the specified
199 Cache.log.debug("Starting questionnaire url at " + url);
200 desktop.checkForQuestionnaire(url);
204 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
206 // Start the desktop questionnaire prompter with the specified
209 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
211 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
212 Cache.log.debug("Starting questionnaire with default url: "
214 desktop.checkForQuestionnaire(defurl);
221 String file = null, protocol = null, format = null, data = null;
222 jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
223 Vector getFeatures = null; // vector of das source nicknames to fetch
226 String groovyscript = null; // script to execute after all loading is
227 // completed one way or another
228 // extract groovy argument and execute if necessary
229 groovyscript = aparser.getValue("groovy", true);
230 file = aparser.getValue("open", true);
232 if (file == null && desktop == null)
234 System.out.println("No files to open!");
237 String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
239 if (vamsasImport != null || vamsasSession != null)
241 if (desktop == null || headless)
244 .println("Headless vamsas sessions not yet supported. Sorry.");
247 // if we have a file, start a new session and import it.
248 boolean inSession = false;
249 if (vamsasImport != null)
253 String viprotocol = jalview.io.AppletFormatAdapter.checkProtocol(vamsasImport);
254 if (viprotocol == jalview.io.FormatAdapter.FILE)
256 inSession = desktop.vamsasImport(new File(vamsasImport));
258 else if (viprotocol == jalview.io.FormatAdapter.URL)
260 inSession = desktop.vamsasImport(new URL(vamsasImport));
263 } catch (Exception e)
265 System.err.println("Exeption when importing " + vamsasImport
266 + " as a vamsas document.");
271 System.err.println("Failed to import " + vamsasImport
272 + " as a vamsas document.");
276 System.out.println("Imported Successfully into new session "
277 + desktop.getVamsasApplication().getCurrentSession());
280 if (vamsasSession != null)
282 if (vamsasImport != null)
284 // close the newly imported session and import the Jalview specific
285 // remnants into the new session later on.
286 desktop.vamsasStop_actionPerformed(null);
288 // now join the new session
291 if (desktop.joinVamsasSession(vamsasSession))
293 System.out.println("Successfully joined vamsas session "
298 System.err.println("WARNING: Failed to join vamsas session "
301 } catch (Exception e)
303 System.err.println("ERROR: Failed to join vamsas session "
307 if (vamsasImport != null)
309 // the Jalview specific remnants can now be imported into the new
310 // session at the user's leisure.
312 .info("Skipping Push for import of data into existing vamsas session."); // TODO:
317 // desktop.getVamsasApplication().push_update();
322 // Finally, deal with the remaining input data.
327 desktop.setProgressBar("Processing commandline arguments...", progress=System.currentTimeMillis());
329 System.out.println("Opening file: " + file);
331 if (!file.startsWith("http://"))
333 if (!(new java.io.File(file)).exists())
335 System.out.println("Can't find " + file);
343 protocol = jalview.io.AppletFormatAdapter.checkProtocol(file);
345 format = new jalview.io.IdentifyFile().Identify(file, protocol);
347 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
351 System.out.println("error");
355 data = aparser.getValue("colour", true);
358 data.replaceAll("%20", " ");
360 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
361 .getColour(af.getViewport().getAlignment(), data);
365 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
367 ucs.parseAppletParameter(data);
371 System.out.println("colour is " + data);
375 // Must maintain ability to use the groups flag
376 data = aparser.getValue("groups", true);
379 af.parseFeaturesFile(data, jalview.io.AppletFormatAdapter.checkProtocol(data));
380 System.out.println("Added " + data);
382 data = aparser.getValue("features", true);
385 af.parseFeaturesFile(data, jalview.io.AppletFormatAdapter.checkProtocol(data));
386 System.out.println("Added " + data);
389 data = aparser.getValue("annotations", true);
392 af.loadJalviewDataFile(data, null, null, null);
393 System.out.println("Added " + data);
395 // set or clear the sortbytree flag.
396 if (aparser.contains("sortbytree"))
398 af.getViewport().setSortByTree(true);
400 if (aparser.contains("nosortbytree"))
402 af.getViewport().setSortByTree(false);
404 data = aparser.getValue("tree", true);
407 jalview.io.NewickFile fin = null;
410 fin = new jalview.io.NewickFile(data, jalview.io.AppletFormatAdapter.checkProtocol(data));
413 af.getViewport().setCurrentTree(
414 af.ShowNewickTree(fin, data).getTree());
415 System.out.println("Added tree " + data);
417 } catch (IOException ex)
419 System.err.println("Couldn't add tree " + data);
420 ex.printStackTrace(System.err);
423 // TODO - load PDB structure(s) to alignment JAL-629
424 // (associate with identical sequence in alignment, or a specified
427 getFeatures = checkDasArguments(aparser);
428 if (af != null && getFeatures != null)
430 FeatureFetcher ff = startFeatureFetching(getFeatures);
432 while (!ff.allFinished() || af.operationInProgress())
434 // wait around until fetching is finished.
438 } catch (Exception e)
443 getFeatures = null; // have retrieved features - forget them now.
445 if (groovyscript != null)
447 // Execute the groovy script after we've done all the rendering stuff
448 // and before any images or figures are generated.
449 if (jalview.bin.Cache.groovyJarsPresent())
451 System.out.println("Executing script " + groovyscript);
452 executeGroovyScript(groovyscript, new Object[] {desktop,af});
457 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
462 String imageName = "unnamed.png";
463 while (aparser.getSize() > 1)
465 format = aparser.nextValue();
466 file = aparser.nextValue();
468 if (format.equalsIgnoreCase("png"))
470 af.createPNG(new java.io.File(file));
471 imageName = (new java.io.File(file)).getName();
472 System.out.println("Creating PNG image: " + file);
475 else if (format.equalsIgnoreCase("imgMap"))
477 af.createImageMap(new java.io.File(file), imageName);
478 System.out.println("Creating image map: " + file);
481 else if (format.equalsIgnoreCase("eps"))
483 System.out.println("Creating EPS file: " + file);
484 af.createEPS(new java.io.File(file));
488 if (af.saveAlignment(file, format))
490 System.out.println("Written alignment in " + format
491 + " format to " + file);
495 System.out.println("Error writing file " + file + " in " + format
501 while (aparser.getSize() > 0)
503 System.out.println("Unknown arg: " + aparser.nextValue());
506 AlignFrame startUpAlframe = null;
507 // We'll only open the default file if the desktop is visible.
509 // ////////////////////
510 if (!headless && file == null && vamsasImport == null
511 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
513 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
514 jalview.bin.Cache.getDefault("www.jalview.org", "http://www.jalview.org")+"/examples/exampleFile_2_7.jar");
515 if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar"))
517 // hardwire upgrade of the startup file
518 file.replace("_2_3.jar","_2_7.jar");
519 // and remove the stale setting
520 jalview.bin.Cache.removeProperty("STARTUP_FILE");
525 if (file.indexOf("http:") > -1)
530 if (file.endsWith(".jar"))
536 format = new jalview.io.IdentifyFile().Identify(file, protocol);
539 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
541 getFeatures = checkDasArguments(aparser);
542 // extract groovy arguments before anything else.
544 // If the user has specified features to be retrieved,
545 // or a groovy script to be executed, do them if they
546 // haven't been done already
547 // fetch features for the default alignment
548 if (getFeatures != null)
550 if (startUpAlframe != null)
552 startFeatureFetching(getFeatures);
555 // Once all other stuff is done, execute any groovy scripts (in order)
556 if (groovyscript != null)
558 if (jalview.bin.Cache.groovyJarsPresent())
560 System.out.println("Executing script " + groovyscript);
561 executeGroovyScript(groovyscript, new Object[] { desktop, startUpAlframe});
566 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
570 // and finally, turn off batch mode indicator - if the desktop still exists
574 desktop.setProgressBar(null, progress);
576 desktop.setInBatchMode(false);
580 private static void startUsageStats(final Desktop desktop)
583 * start a User Config prompt asking if we can log usage statistics.
585 jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
588 "Jalview Usage Statistics",
589 "Do you want to help make Jalview better by enabling "
590 + "the collection of usage statistics with Google Analytics ?"
591 + "\n\n(you can enable or disable usage tracking in the preferences)",
597 .info("Initialising googletracker for usage stats.");
598 Cache.initGoogleTracker();
599 Cache.log.debug("Tracking enabled.");
605 Cache.log.info("Not enabling Google Tracking.");
608 SwingUtilities.invokeLater(prompter);
612 * Locate the given string as a file and pass it to the groovy interpreter.
614 * @param groovyscript
615 * the script to execute
616 * @param jalviewContext
617 * the Jalview Desktop object passed in to the groovy binding as the
620 private static void executeGroovyScript(String groovyscript,
621 Object[] jalviewContext)
623 if (jalviewContext == null)
626 .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
629 * for scripts contained in files
636 if (groovyscript.trim().equals("STDIN"))
638 // read from stdin into a tempfile and execute it
641 tfile = File.createTempFile("jalview", "groovy");
642 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
643 new FileOutputStream(tfile)));
644 BufferedReader br = new BufferedReader(
645 new java.io.InputStreamReader(System.in));
647 while ((line = br.readLine()) != null)
649 outfile.write(line + "\n");
655 } catch (Exception ex)
657 System.err.println("Failed to read from STDIN into tempfile "
658 + ((tfile == null) ? "(tempfile wasn't created)" : tfile
660 ex.printStackTrace();
664 sfile = tfile.toURI().toURL();
665 } catch (Exception x)
667 System.err.println("Unexpected Malformed URL Exception for temporary file created from STDIN: "+tfile.toURI());
676 sfile = new URI(groovyscript).toURL();
677 } catch (Exception x)
679 tfile = new File(groovyscript);
682 System.err.println("File '" + groovyscript + "' does not exist.");
685 if (!tfile.canRead())
687 System.err.println("File '" + groovyscript + "' cannot be read.");
690 if (tfile.length() < 1)
692 System.err.println("File '" + groovyscript + "' is empty.");
696 sfile = tfile.getAbsoluteFile().toURI().toURL();
697 } catch (Exception ex)
699 System.err.println("Failed to create a file URL for "+tfile.getAbsoluteFile());
704 boolean success = false;
708 * The following code performs the GroovyScriptEngine invocation using
709 * reflection, and is equivalent to this fragment from the embedding
710 * groovy documentation on the groovy site: <code> import
711 * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
713 * String[] roots = new String[] { "/my/groovy/script/path" };
714 * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
715 * = new Binding(); binding.setVariable("input", "world");
716 * gse.run("hello.groovy", binding); </code>
720 int blen = ((jalviewContext[0] == null) ? 0 : 1)
721 + ((jalviewContext[1] == null) ? 0 : 1);
722 String cnames[] = new String[]
723 { "Jalview", "currentAlFrame" };
724 bspec = new Class[blen * 2];
725 binding = new Object[blen * 2];
727 ClassLoader cl = null;
728 Map vbinding = new Hashtable();
729 for (int jc = 0; jc < jalviewContext.length; jc++)
731 if (jalviewContext[jc] != null)
735 cl = jalviewContext[jc].getClass().getClassLoader();
737 bspec[blen * 2] = String.class;
738 bspec[blen * 2 + 1] = Object.class;
739 binding[blen * 2] = cnames[jc];
740 binding[blen * 2 + 1] = jalviewContext[jc];
741 vbinding.put(cnames[jc], jalviewContext[jc]);
745 Class gbindingc = cl.loadClass("groovy.lang.Binding");
750 gbcons = gbindingc.getConstructor(Map.class);
751 gbinding = gbcons.newInstance(vbinding);
752 } catch (NoSuchMethodException x)
754 // old style binding config - using series of string/object values to
756 gbcons = gbindingc.getConstructor(null);
757 gbinding = gbcons.newInstance(null);
758 java.lang.reflect.Method setvar = gbindingc.getMethod(
759 "setVariable", bspec);
760 setvar.invoke(gbinding, binding);
763 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
764 Constructor gseccons = gsec.getConstructor(new Class[]
765 { URL[].class }); // String[].class });
766 Object gse = gseccons.newInstance(new Object[]
768 { sfile } }); // .toString() } });
769 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
770 { String.class, gbindingc });
771 run.invoke(gse, new Object[]
772 { sfile.toString(), gbinding });
774 } catch (Exception e)
776 System.err.println("Exception Whilst trying to execute file " + sfile
777 + " as a groovy script.");
778 e.printStackTrace(System.err);
781 if (success && groovyscript.equals("STDIN"))
783 // delete temp file that we made - but only if it was successfully
790 * Check commandline for any das server definitions or any fetchfrom switches
792 * @return vector of DAS source nicknames to retrieve from
794 private static Vector checkDasArguments(ArgsParser aparser)
796 Vector source = null;
798 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
799 while ((data = aparser.getValue("dasserver", true)) != null)
801 String nickname = null;
803 boolean seq = false, feat = true;
804 int pos = data.indexOf('=');
805 // determine capabilities
808 nickname = data.substring(0, pos);
810 url = data.substring(pos + 1);
812 && (url.startsWith("http:") || url
813 .startsWith("sequence:http:")))
815 if (nickname == null)
819 if (locsources == null)
827 locsources = locsources + nickname + "|" + url;
829 .println("NOTE! dasserver parameter not yet really supported (got args of "
830 + nickname + "|" + url);
833 source = new Vector();
835 source.addElement(nickname);
837 } // loop until no more server entries are found.
838 if (locsources != null && locsources.indexOf('|') > -1)
840 Cache.log.debug("Setting local source list in properties file to:\n"
842 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
844 while ((data = aparser.getValue("fetchfrom", true)) != null)
846 System.out.println("adding source '" + data + "'");
849 source = new Vector();
851 source.addElement(data);
857 * start a feature fetcher for every alignment frame
861 private static FeatureFetcher startFeatureFetching(final Vector dasSources)
863 FeatureFetcher ff = new FeatureFetcher();
864 AlignFrame afs[] = Desktop.getAlignframes();
865 if (afs == null || afs.length == 0)
869 for (int i = 0; i < afs.length; i++)
871 ff.addFetcher(afs[i], dasSources);
878 * Notes: this argParser does not distinguish between parameter switches,
879 * parameter values and argument text. If an argument happens to be identical to
880 * a parameter, it will be taken as such (even though it didn't have a '-'
883 * @author Andrew Waterhouse and JBP documented.
890 public ArgsParser(String[] args)
892 vargs = new Vector();
893 for (int i = 0; i < args.length; i++)
895 String arg = args[i].trim();
896 if (arg.charAt(0) == '-')
898 arg = arg.substring(1);
900 vargs.addElement(arg);
905 * check for and remove first occurence of arg+parameter in arglist.
908 * @return return the argument following the given arg if arg was in list.
910 public String getValue(String arg)
912 return getValue(arg, false);
915 public String getValue(String arg, boolean utf8decode)
917 int index = vargs.indexOf(arg);
918 String dc = null, ret = null;
921 ret = vargs.elementAt(index + 1).toString();
922 vargs.removeElementAt(index);
923 vargs.removeElementAt(index);
924 if (utf8decode && ret != null)
928 dc = URLDecoder.decode(ret, "UTF-8");
930 } catch (Exception e)
932 // TODO: log failure to decode
940 * check for and remove first occurence of arg in arglist.
943 * @return true if arg was present in argslist.
945 public boolean contains(String arg)
947 if (vargs.contains(arg))
949 vargs.removeElement(arg);
958 public String nextValue()
960 return vargs.remove(0).toString();
971 * keep track of feature fetching tasks.
979 * TODO: generalise to track all jalview events to orchestrate batch
983 private int queued = 0;
985 private int running = 0;
987 public FeatureFetcher()
992 public void addFetcher(final AlignFrame af, final Vector dasSources)
994 final long id = System.currentTimeMillis();
996 final FeatureFetcher us = this;
997 new Thread(new Runnable()
1008 af.setProgressBar("DAS features being retrieved...", id);
1009 af.featureSettings_actionPerformed(null);
1010 af.featureSettings.fetchDasFeatures(dasSources, true);
1011 af.setProgressBar(null, id);
1020 public synchronized boolean allFinished()
1022 return queued == 0 && running == 0;