2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, 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;
28 import java.net.URLDecoder;
29 import java.security.AllPermission;
30 import java.security.CodeSource;
31 import java.security.PermissionCollection;
32 import java.security.Permissions;
33 import java.security.Policy;
39 import jalview.util.Platform;
42 * Main class for Jalview Application <br>
44 * start with java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview
53 // grab all the rights we can the JVM
54 Policy.setPolicy(new Policy()
56 public PermissionCollection getPermissions(CodeSource codesource)
58 Permissions perms = new Permissions();
59 perms.add(new AllPermission());
70 * main class for Jalview application
73 * open <em>filename</em>
75 public static void main(String[] args)
77 System.out.println("Java version: "
78 + System.getProperty("java.version"));
79 System.out.println(System.getProperty("os.arch") + " "
80 + System.getProperty("os.name") + " "
81 + System.getProperty("os.version"));
82 if (new Platform().isAMac())
84 System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Jalview");
85 System.setProperty("apple.laf.useScreenMenuBar", "true");
88 ArgsParser aparser = new ArgsParser(args);
89 boolean headless = false;
91 if (aparser.contains("help") || aparser.contains("h"))
94 .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
95 + "-nodisplay\tRun Jalview without User Interface.\n"
96 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
97 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
98 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
99 + "-features FILE\tUse the given file to mark features on the alignment.\n"
100 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
101 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
102 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
103 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
104 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
105 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
106 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
107 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
108 + "-png FILE\tCreate PNG image FILE from alignment.\n"
109 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
110 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
111 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
112 + "-noquestionnaire\tTurn off questionnaire check.\n"
113 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
114 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
116 // "-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)"
117 + "-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"
118 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
119 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
120 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
122 // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
123 // + "-vses vamsas-session\tJoin session with given URN\n"
124 + "-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"
125 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
128 Cache.loadProperties(aparser.getValue("props")); // must do this before
130 String defs = aparser.getValue("setprop");
133 int p = defs.indexOf('=');
136 System.err.println("Ignoring invalid setprop argument : " + defs);
140 System.out.println("Executing setprop argument: " + defs);
141 // DISABLED FOR SECURITY REASONS
142 // TODO: add a property to allow properties to be overriden by cli args
143 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
145 defs = aparser.getValue("setprop");
147 if (aparser.contains("nodisplay"))
149 System.setProperty("java.awt.headless", "true");
151 if (System.getProperty("java.awt.headless") != null
152 && System.getProperty("java.awt.headless").equals("true"))
160 } catch (java.lang.NoClassDefFoundError error)
162 error.printStackTrace();
164 .println("\nEssential logging libraries not found."
165 + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
169 Desktop desktop = null;
173 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
174 } catch (Exception ex)
180 desktop = new Desktop();
181 desktop.setVisible(true);
182 desktop.startServiceDiscovery();
183 if (!aparser.contains("nousagestats"))
185 startUsageStats(desktop);
187 if (!aparser.contains("noquestionnaire"))
189 String url = aparser.getValue("questionnaire");
192 // Start the desktop questionnaire prompter with the specified
194 Cache.log.debug("Starting questionnaire url at " + url);
195 desktop.checkForQuestionnaire(url);
199 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
201 // Start the desktop questionnaire prompter with the specified
204 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
206 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
207 Cache.log.debug("Starting questionnaire with default url: "
209 desktop.checkForQuestionnaire(defurl);
216 String file = null, protocol = null, format = null, data = null;
217 jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
218 Vector getFeatures = null; // vector of das source nicknames to fetch
221 String groovyscript = null; // script to execute after all loading is
222 // completed one way or another
223 // extract groovy argument and execute if necessary
224 groovyscript = aparser.getValue("groovy", true);
225 file = aparser.getValue("open", true);
227 if (file == null && desktop == null)
229 System.out.println("No files to open!");
232 String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
234 if (vamsasImport != null || vamsasSession != null)
236 if (desktop == null || headless)
239 .println("Headless vamsas sessions not yet supported. Sorry.");
242 // if we have a file, start a new session and import it.
243 boolean inSession = false;
244 if (vamsasImport != null)
248 String viprotocol = Jalview.checkProtocol(vamsasImport);
249 if (viprotocol == jalview.io.FormatAdapter.FILE)
251 inSession = desktop.vamsasImport(new File(vamsasImport));
253 else if (viprotocol == jalview.io.FormatAdapter.URL)
255 inSession = desktop.vamsasImport(new URL(vamsasImport));
258 } catch (Exception e)
260 System.err.println("Exeption when importing " + vamsasImport
261 + " as a vamsas document.");
266 System.err.println("Failed to import " + vamsasImport
267 + " as a vamsas document.");
271 System.out.println("Imported Successfully into new session "
272 + desktop.getVamsasApplication().getCurrentSession());
275 if (vamsasSession != null)
277 if (vamsasImport != null)
279 // close the newly imported session and import the Jalview specific
280 // remnants into the new session later on.
281 desktop.vamsasStop_actionPerformed(null);
283 // now join the new session
286 if (desktop.joinVamsasSession(vamsasSession))
288 System.out.println("Successfully joined vamsas session "
293 System.err.println("WARNING: Failed to join vamsas session "
296 } catch (Exception e)
298 System.err.println("ERROR: Failed to join vamsas session "
302 if (vamsasImport != null)
304 // the Jalview specific remnants can now be imported into the new
305 // session at the user's leisure.
307 .info("Skipping Push for import of data into existing vamsas session."); // TODO:
312 // desktop.getVamsasApplication().push_update();
316 // Finally, deal with the remaining input data.
319 System.out.println("Opening file: " + file);
321 if (!file.startsWith("http://"))
323 if (!(new java.io.File(file)).exists())
325 System.out.println("Can't find " + file);
333 protocol = checkProtocol(file);
335 format = new jalview.io.IdentifyFile().Identify(file, protocol);
337 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
341 System.out.println("error");
345 data = aparser.getValue("colour", true);
348 data.replaceAll("%20", " ");
350 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
351 .getColour(af.getViewport().getAlignment(), data);
355 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
357 ucs.parseAppletParameter(data);
361 System.out.println("colour is " + data);
365 // Must maintain ability to use the groups flag
366 data = aparser.getValue("groups", true);
369 af.parseFeaturesFile(data, checkProtocol(data));
370 System.out.println("Added " + data);
372 data = aparser.getValue("features", true);
375 af.parseFeaturesFile(data, checkProtocol(data));
376 System.out.println("Added " + data);
379 data = aparser.getValue("annotations", true);
382 af.loadJalviewDataFile(data);
383 System.out.println("Added " + data);
385 // set or clear the sortbytree flag.
386 if (aparser.contains("sortbytree"))
388 af.getViewport().setSortByTree(true);
390 if (aparser.contains("nosortbytree"))
392 af.getViewport().setSortByTree(false);
394 data = aparser.getValue("tree", true);
397 jalview.io.NewickFile fin = null;
400 fin = new jalview.io.NewickFile(data, checkProtocol(data));
403 af.getViewport().setCurrentTree(
404 af.ShowNewickTree(fin, data).getTree());
405 System.out.println("Added tree " + data);
407 } catch (IOException ex)
409 System.err.println("Couldn't add tree " + data);
410 ex.printStackTrace(System.err);
413 // todo - load PDB structure to alignment
414 // (associate with identical sequence in alignment, or a specified
417 getFeatures = checkDasArguments(aparser);
418 if (af != null && getFeatures != null)
420 FeatureFetcher ff = startFeatureFetching(getFeatures);
422 while (!ff.allFinished() || af.operationInProgress())
424 // wait around until fetching is finished.
428 } catch (Exception e)
433 getFeatures = null; // have retrieved features - forget them now.
435 if (groovyscript != null)
437 // Execute the groovy script after we've done all the rendering stuff
438 // and before any images or figures are generated.
439 if (jalview.bin.Cache.groovyJarsPresent())
441 System.out.println("Executing script " + groovyscript);
442 executeGroovyScript(groovyscript, desktop);
447 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
452 String imageName = "unnamed.png";
453 while (aparser.getSize() > 1)
455 format = aparser.nextValue();
456 file = aparser.nextValue();
458 if (format.equalsIgnoreCase("png"))
460 af.createPNG(new java.io.File(file));
461 imageName = (new java.io.File(file)).getName();
462 System.out.println("Creating PNG image: " + file);
465 else if (format.equalsIgnoreCase("imgMap"))
467 af.createImageMap(new java.io.File(file), imageName);
468 System.out.println("Creating image map: " + file);
471 else if (format.equalsIgnoreCase("eps"))
473 System.out.println("Creating EPS file: " + file);
474 af.createEPS(new java.io.File(file));
478 if (af.saveAlignment(file, format))
480 System.out.println("Written alignment in " + format
481 + " format to " + file);
485 System.out.println("Error writing file " + file + " in " + format
491 while (aparser.getSize() > 0)
493 System.out.println("Unknown arg: " + aparser.nextValue());
496 AlignFrame startUpAlframe = null;
497 // We'll only open the default file if the desktop is visible.
499 // ////////////////////
500 if (!headless && file == null && vamsasImport == null
501 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
503 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
504 "http://www.jalview.org/examples/exampleFile_2_3.jar");
508 if (file.indexOf("http:") > -1)
513 if (file.endsWith(".jar"))
519 format = new jalview.io.IdentifyFile().Identify(file, protocol);
522 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
524 getFeatures = checkDasArguments(aparser);
525 // extract groovy arguments before anything else.
527 // If the user has specified features to be retrieved,
528 // or a groovy script to be executed, do them if they
529 // haven't been done already
530 // fetch features for the default alignment
531 if (getFeatures != null)
533 if (startUpAlframe != null)
535 startFeatureFetching(getFeatures);
538 // execute a groovy script.
539 if (groovyscript != null)
541 if (jalview.bin.Cache.groovyJarsPresent())
543 System.out.println("Executing script " + groovyscript);
544 executeGroovyScript(groovyscript, desktop);
549 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
554 // Once all other stuff is done, execute any groovy scripts (in order)
557 private static void startUsageStats(final Desktop desktop)
560 * start a User Config prompt asking if we can log usage statistics.
562 jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
565 "Jalview Usage Statistics",
566 "Do you want to help make Jalview better by enabling "
567 + "the collection of usage statistics with Google Analytics ?"
568 + "\n\n(you can enable or disable usage tracking in the preferences)",
574 .info("Initialising googletracker for usage stats.");
575 Cache.initGoogleTracker();
576 Cache.log.debug("Tracking enabled.");
582 Cache.log.info("Not enabling Google Tracking.");
585 SwingUtilities.invokeLater(prompter);
589 * Locate the given string as a file and pass it to the groovy interpreter.
591 * @param groovyscript
592 * the script to execute
593 * @param jalviewContext
594 * the Jalview Desktop object passed in to the groovy binding as the
597 private static void executeGroovyScript(String groovyscript,
598 Object jalviewContext)
600 if (jalviewContext == null)
603 .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
606 if (groovyscript.trim().equals("STDIN"))
608 // read from stdin into a tempfile and execute it
611 sfile = File.createTempFile("jalview", "groovy");
612 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
613 new FileOutputStream(sfile)));
614 BufferedReader br = new BufferedReader(
615 new java.io.InputStreamReader(System.in));
617 while ((line = br.readLine()) != null)
619 outfile.write(line + "\n");
625 } catch (Exception ex)
627 System.err.println("Failed to read from STDIN into tempfile "
628 + ((sfile == null) ? "(tempfile wasn't created)" : sfile
630 ex.printStackTrace();
636 sfile = new File(groovyscript);
640 System.err.println("File '" + groovyscript + "' does not exist.");
643 if (!sfile.canRead())
645 System.err.println("File '" + groovyscript + "' cannot be read.");
648 if (sfile.length() < 1)
650 System.err.println("File '" + groovyscript + "' is empty.");
653 boolean success = false;
657 * The following code performs the GroovyScriptEngine invocation using
658 * reflection, and is equivalent to this fragment from the embedding
659 * groovy documentation on the groovy site: <code> import
660 * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
662 * String[] roots = new String[] { "/my/groovy/script/path" };
663 * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
664 * = new Binding(); binding.setVariable("input", "world");
665 * gse.run("hello.groovy", binding); </code>
667 ClassLoader cl = jalviewContext.getClass().getClassLoader();
668 Class gbindingc = cl.loadClass("groovy.lang.Binding");
669 Constructor gbcons = gbindingc.getConstructor(null);
670 Object gbinding = gbcons.newInstance(null);
671 java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
673 { String.class, Object.class });
674 setvar.invoke(gbinding, new Object[]
675 { "Jalview", jalviewContext });
676 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
677 Constructor gseccons = gsec.getConstructor(new Class[]
678 { URL[].class }); // String[].class });
679 Object gse = gseccons.newInstance(new Object[]
681 { sfile.toURL() } }); // .toString() } });
682 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
683 { String.class, gbindingc });
684 run.invoke(gse, new Object[]
685 { sfile.getName(), gbinding });
687 } catch (Exception e)
689 System.err.println("Exception Whilst trying to execute file " + sfile
690 + " as a groovy script.");
691 e.printStackTrace(System.err);
694 if (success && groovyscript.equals("STDIN"))
696 // delete temp file that we made - but only if it was successfully
703 * Check commandline for any das server definitions or any fetchfrom switches
705 * @return vector of DAS source nicknames to retrieve from
707 private static Vector checkDasArguments(ArgsParser aparser)
709 Vector source = null;
711 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
712 while ((data = aparser.getValue("dasserver", true)) != null)
714 String nickname = null;
716 boolean seq = false, feat = true;
717 int pos = data.indexOf('=');
718 // determine capabilities
721 nickname = data.substring(0, pos);
723 url = data.substring(pos + 1);
725 && (url.startsWith("http:") || url
726 .startsWith("sequence:http:")))
728 if (nickname == null)
732 if (locsources == null)
740 locsources = locsources + nickname + "|" + url;
742 .println("NOTE! dasserver parameter not yet really supported (got args of "
743 + nickname + "|" + url);
746 source = new Vector();
748 source.addElement(nickname);
750 } // loop until no more server entries are found.
751 if (locsources != null && locsources.indexOf('|') > -1)
753 Cache.log.debug("Setting local source list in properties file to:\n"
755 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
757 while ((data = aparser.getValue("fetchfrom", true)) != null)
759 System.out.println("adding source '" + data + "'");
762 source = new Vector();
764 source.addElement(data);
770 * start a feature fetcher for every alignment frame
774 private static FeatureFetcher startFeatureFetching(final Vector dasSources)
776 FeatureFetcher ff = new FeatureFetcher();
777 AlignFrame afs[] = Desktop.getAlignframes();
778 if (afs == null || afs.length == 0)
782 for (int i = 0; i < afs.length; i++)
784 ff.addFetcher(afs[i], dasSources);
789 private static String checkProtocol(String file)
791 String protocol = jalview.io.FormatAdapter.FILE;
793 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
795 protocol = jalview.io.FormatAdapter.URL;
802 * Notes: this argParser does not distinguish between parameter switches,
803 * parameter values and argument text. If an argument happens to be identical to
804 * a parameter, it will be taken as such (even though it didn't have a '-'
807 * @author Andrew Waterhouse and JBP documented.
814 public ArgsParser(String[] args)
816 vargs = new Vector();
817 for (int i = 0; i < args.length; i++)
819 String arg = args[i].trim();
820 if (arg.charAt(0) == '-')
822 arg = arg.substring(1);
824 vargs.addElement(arg);
829 * check for and remove first occurence of arg+parameter in arglist.
832 * @return return the argument following the given arg if arg was in list.
834 public String getValue(String arg)
836 return getValue(arg, false);
839 public String getValue(String arg, boolean utf8decode)
841 int index = vargs.indexOf(arg);
842 String dc = null, ret = null;
845 ret = vargs.elementAt(index + 1).toString();
846 vargs.removeElementAt(index);
847 vargs.removeElementAt(index);
848 if (utf8decode && ret != null)
852 dc = URLDecoder.decode(ret, "UTF-8");
854 } catch (Exception e)
856 // TODO: log failure to decode
864 * check for and remove first occurence of arg in arglist.
867 * @return true if arg was present in argslist.
869 public boolean contains(String arg)
871 if (vargs.contains(arg))
873 vargs.removeElement(arg);
882 public String nextValue()
884 return vargs.remove(0).toString();
895 * keep track of feature fetching tasks.
903 * TODO: generalise to track all jalview events to orchestrate batch
907 private int queued = 0;
909 private int running = 0;
911 public FeatureFetcher()
916 public void addFetcher(final AlignFrame af, final Vector dasSources)
918 final long id = System.currentTimeMillis();
920 final FeatureFetcher us = this;
921 new Thread(new Runnable()
932 af.setProgressBar("DAS features being retrieved...", id);
933 af.featureSettings_actionPerformed(null);
934 af.featureSettings.fetchDasFeatures(dasSources, true);
935 af.setProgressBar(null, id);
944 public synchronized boolean allFinished()
946 return queued == 0 && running == 0;