2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
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",
86 System.setProperty("apple.laf.useScreenMenuBar", "true");
89 ArgsParser aparser = new ArgsParser(args);
90 boolean headless = false;
92 if (aparser.contains("help") || aparser.contains("h"))
95 .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
96 + "-nodisplay\tRun Jalview without User Interface.\n"
97 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
98 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
99 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
100 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
101 + "-features FILE\tUse the given file to mark features on the alignment.\n"
102 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
103 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
104 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
105 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
106 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
107 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
108 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
109 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
110 + "-png FILE\tCreate PNG image FILE from alignment.\n"
111 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
112 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
113 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
114 + "-noquestionnaire\tTurn off questionnaire check.\n"
115 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
116 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
118 // "-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)"
119 + "-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"
120 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
121 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
122 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
124 // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
125 // + "-vses vamsas-session\tJoin session with given URN\n"
126 + "-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"
127 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
130 Cache.loadProperties(aparser.getValue("props")); // must do this before
132 String defs = aparser.getValue("setprop");
135 int p = defs.indexOf('=');
138 System.err.println("Ignoring invalid setprop argument : " + defs);
142 System.out.println("Executing setprop argument: " + defs);
143 // DISABLED FOR SECURITY REASONS
144 // TODO: add a property to allow properties to be overriden by cli args
145 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
147 defs = aparser.getValue("setprop");
149 if (aparser.contains("nodisplay"))
151 System.setProperty("java.awt.headless", "true");
153 if (System.getProperty("java.awt.headless") != null
154 && System.getProperty("java.awt.headless").equals("true"))
162 } catch (java.lang.NoClassDefFoundError error)
164 error.printStackTrace();
166 .println("\nEssential logging libraries not found."
167 + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
171 Desktop desktop = null;
175 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
176 } catch (Exception ex)
182 desktop = new Desktop();
183 desktop.setInBatchMode(true); // indicate we are starting up
184 desktop.setVisible(true);
185 desktop.startServiceDiscovery();
186 if (!aparser.contains("nousagestats"))
188 startUsageStats(desktop);
190 if (!aparser.contains("noquestionnaire"))
192 String url = aparser.getValue("questionnaire");
195 // Start the desktop questionnaire prompter with the specified
197 Cache.log.debug("Starting questionnaire url at " + url);
198 desktop.checkForQuestionnaire(url);
202 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
204 // Start the desktop questionnaire prompter with the specified
207 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
209 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
210 Cache.log.debug("Starting questionnaire with default url: "
212 desktop.checkForQuestionnaire(defurl);
219 String file = null, protocol = null, format = null, data = null;
220 jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
221 Vector getFeatures = null; // vector of das source nicknames to fetch
224 String groovyscript = null; // script to execute after all loading is
225 // completed one way or another
226 // extract groovy argument and execute if necessary
227 groovyscript = aparser.getValue("groovy", true);
228 file = aparser.getValue("open", true);
230 if (file == null && desktop == null)
232 System.out.println("No files to open!");
235 String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
237 if (vamsasImport != null || vamsasSession != null)
239 if (desktop == null || headless)
242 .println("Headless vamsas sessions not yet supported. Sorry.");
245 // if we have a file, start a new session and import it.
246 boolean inSession = false;
247 if (vamsasImport != null)
251 String viprotocol = Jalview.checkProtocol(vamsasImport);
252 if (viprotocol == jalview.io.FormatAdapter.FILE)
254 inSession = desktop.vamsasImport(new File(vamsasImport));
256 else if (viprotocol == jalview.io.FormatAdapter.URL)
258 inSession = desktop.vamsasImport(new URL(vamsasImport));
261 } catch (Exception e)
263 System.err.println("Exeption when importing " + vamsasImport
264 + " as a vamsas document.");
269 System.err.println("Failed to import " + vamsasImport
270 + " as a vamsas document.");
274 System.out.println("Imported Successfully into new session "
275 + desktop.getVamsasApplication().getCurrentSession());
278 if (vamsasSession != null)
280 if (vamsasImport != null)
282 // close the newly imported session and import the Jalview specific
283 // remnants into the new session later on.
284 desktop.vamsasStop_actionPerformed(null);
286 // now join the new session
289 if (desktop.joinVamsasSession(vamsasSession))
291 System.out.println("Successfully joined vamsas session "
296 System.err.println("WARNING: Failed to join vamsas session "
299 } catch (Exception e)
301 System.err.println("ERROR: Failed to join vamsas session "
305 if (vamsasImport != null)
307 // the Jalview specific remnants can now be imported into the new
308 // session at the user's leisure.
310 .info("Skipping Push for import of data into existing vamsas session."); // TODO:
315 // desktop.getVamsasApplication().push_update();
319 // Finally, deal with the remaining input data.
322 System.out.println("Opening file: " + file);
324 if (!file.startsWith("http://"))
326 if (!(new java.io.File(file)).exists())
328 System.out.println("Can't find " + file);
336 protocol = checkProtocol(file);
338 format = new jalview.io.IdentifyFile().Identify(file, protocol);
340 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
344 System.out.println("error");
348 data = aparser.getValue("colour", true);
351 data.replaceAll("%20", " ");
353 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
354 .getColour(af.getViewport().getAlignment(), data);
358 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
360 ucs.parseAppletParameter(data);
364 System.out.println("colour is " + data);
368 // Must maintain ability to use the groups flag
369 data = aparser.getValue("groups", true);
372 af.parseFeaturesFile(data, checkProtocol(data));
373 System.out.println("Added " + data);
375 data = aparser.getValue("features", true);
378 af.parseFeaturesFile(data, checkProtocol(data));
379 System.out.println("Added " + data);
382 data = aparser.getValue("annotations", true);
385 af.loadJalviewDataFile(data);
386 System.out.println("Added " + data);
388 // set or clear the sortbytree flag.
389 if (aparser.contains("sortbytree"))
391 af.getViewport().setSortByTree(true);
393 if (aparser.contains("nosortbytree"))
395 af.getViewport().setSortByTree(false);
397 data = aparser.getValue("tree", true);
400 jalview.io.NewickFile fin = null;
403 fin = new jalview.io.NewickFile(data, checkProtocol(data));
406 af.getViewport().setCurrentTree(
407 af.ShowNewickTree(fin, data).getTree());
408 System.out.println("Added tree " + data);
410 } catch (IOException ex)
412 System.err.println("Couldn't add tree " + data);
413 ex.printStackTrace(System.err);
416 // TODO - load PDB structure(s) to alignment JAL-629
417 // (associate with identical sequence in alignment, or a specified
420 getFeatures = checkDasArguments(aparser);
421 if (af != null && getFeatures != null)
423 FeatureFetcher ff = startFeatureFetching(getFeatures);
425 while (!ff.allFinished() || af.operationInProgress())
427 // wait around until fetching is finished.
431 } catch (Exception e)
436 getFeatures = null; // have retrieved features - forget them now.
438 if (groovyscript != null)
440 // Execute the groovy script after we've done all the rendering stuff
441 // and before any images or figures are generated.
442 if (jalview.bin.Cache.groovyJarsPresent())
444 System.out.println("Executing script " + groovyscript);
445 executeGroovyScript(groovyscript, desktop);
450 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
455 String imageName = "unnamed.png";
456 while (aparser.getSize() > 1)
458 format = aparser.nextValue();
459 file = aparser.nextValue();
461 if (format.equalsIgnoreCase("png"))
463 af.createPNG(new java.io.File(file));
464 imageName = (new java.io.File(file)).getName();
465 System.out.println("Creating PNG image: " + file);
468 else if (format.equalsIgnoreCase("imgMap"))
470 af.createImageMap(new java.io.File(file), imageName);
471 System.out.println("Creating image map: " + file);
474 else if (format.equalsIgnoreCase("eps"))
476 System.out.println("Creating EPS file: " + file);
477 af.createEPS(new java.io.File(file));
481 if (af.saveAlignment(file, format))
483 System.out.println("Written alignment in " + format
484 + " format to " + file);
488 System.out.println("Error writing file " + file + " in " + format
494 while (aparser.getSize() > 0)
496 System.out.println("Unknown arg: " + aparser.nextValue());
499 AlignFrame startUpAlframe = null;
500 // We'll only open the default file if the desktop is visible.
502 // ////////////////////
503 if (!headless && file == null && vamsasImport == null
504 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
506 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
507 "http://www.jalview.org/examples/exampleFile_2_3.jar");
511 if (file.indexOf("http:") > -1)
516 if (file.endsWith(".jar"))
522 format = new jalview.io.IdentifyFile().Identify(file, protocol);
525 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
527 getFeatures = checkDasArguments(aparser);
528 // extract groovy arguments before anything else.
530 // If the user has specified features to be retrieved,
531 // or a groovy script to be executed, do them if they
532 // haven't been done already
533 // fetch features for the default alignment
534 if (getFeatures != null)
536 if (startUpAlframe != null)
538 startFeatureFetching(getFeatures);
541 // Once all other stuff is done, execute any groovy scripts (in order)
542 if (groovyscript != null)
544 if (jalview.bin.Cache.groovyJarsPresent())
546 System.out.println("Executing script " + groovyscript);
547 executeGroovyScript(groovyscript, desktop);
552 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
556 // and finally, turn off batch mode indicator - if the desktop still exists
559 desktop.setInBatchMode(false);
563 private static void startUsageStats(final Desktop desktop)
566 * start a User Config prompt asking if we can log usage statistics.
568 jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
571 "Jalview Usage Statistics",
572 "Do you want to help make Jalview better by enabling "
573 + "the collection of usage statistics with Google Analytics ?"
574 + "\n\n(you can enable or disable usage tracking in the preferences)",
580 .info("Initialising googletracker for usage stats.");
581 Cache.initGoogleTracker();
582 Cache.log.debug("Tracking enabled.");
588 Cache.log.info("Not enabling Google Tracking.");
591 SwingUtilities.invokeLater(prompter);
595 * Locate the given string as a file and pass it to the groovy interpreter.
597 * @param groovyscript
598 * the script to execute
599 * @param jalviewContext
600 * the Jalview Desktop object passed in to the groovy binding as the
603 private static void executeGroovyScript(String groovyscript,
604 Object jalviewContext)
606 if (jalviewContext == null)
609 .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
612 if (groovyscript.trim().equals("STDIN"))
614 // read from stdin into a tempfile and execute it
617 sfile = File.createTempFile("jalview", "groovy");
618 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
619 new FileOutputStream(sfile)));
620 BufferedReader br = new BufferedReader(
621 new java.io.InputStreamReader(System.in));
623 while ((line = br.readLine()) != null)
625 outfile.write(line + "\n");
631 } catch (Exception ex)
633 System.err.println("Failed to read from STDIN into tempfile "
634 + ((sfile == null) ? "(tempfile wasn't created)" : sfile
636 ex.printStackTrace();
642 sfile = new File(groovyscript);
646 System.err.println("File '" + groovyscript + "' does not exist.");
649 if (!sfile.canRead())
651 System.err.println("File '" + groovyscript + "' cannot be read.");
654 if (sfile.length() < 1)
656 System.err.println("File '" + groovyscript + "' is empty.");
659 boolean success = false;
663 * The following code performs the GroovyScriptEngine invocation using
664 * reflection, and is equivalent to this fragment from the embedding
665 * groovy documentation on the groovy site: <code> import
666 * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
668 * String[] roots = new String[] { "/my/groovy/script/path" };
669 * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
670 * = new Binding(); binding.setVariable("input", "world");
671 * gse.run("hello.groovy", binding); </code>
673 ClassLoader cl = jalviewContext.getClass().getClassLoader();
674 Class gbindingc = cl.loadClass("groovy.lang.Binding");
675 Constructor gbcons = gbindingc.getConstructor(null);
676 Object gbinding = gbcons.newInstance(null);
677 java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
679 { String.class, Object.class });
680 setvar.invoke(gbinding, new Object[]
681 { "Jalview", jalviewContext });
682 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
683 Constructor gseccons = gsec.getConstructor(new Class[]
684 { URL[].class }); // String[].class });
685 Object gse = gseccons.newInstance(new Object[]
687 { sfile.toURL() } }); // .toString() } });
688 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
689 { String.class, gbindingc });
690 run.invoke(gse, new Object[]
691 { sfile.getName(), gbinding });
693 } catch (Exception e)
695 System.err.println("Exception Whilst trying to execute file " + sfile
696 + " as a groovy script.");
697 e.printStackTrace(System.err);
700 if (success && groovyscript.equals("STDIN"))
702 // delete temp file that we made - but only if it was successfully
709 * Check commandline for any das server definitions or any fetchfrom switches
711 * @return vector of DAS source nicknames to retrieve from
713 private static Vector checkDasArguments(ArgsParser aparser)
715 Vector source = null;
717 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
718 while ((data = aparser.getValue("dasserver", true)) != null)
720 String nickname = null;
722 boolean seq = false, feat = true;
723 int pos = data.indexOf('=');
724 // determine capabilities
727 nickname = data.substring(0, pos);
729 url = data.substring(pos + 1);
731 && (url.startsWith("http:") || url
732 .startsWith("sequence:http:")))
734 if (nickname == null)
738 if (locsources == null)
746 locsources = locsources + nickname + "|" + url;
748 .println("NOTE! dasserver parameter not yet really supported (got args of "
749 + nickname + "|" + url);
752 source = new Vector();
754 source.addElement(nickname);
756 } // loop until no more server entries are found.
757 if (locsources != null && locsources.indexOf('|') > -1)
759 Cache.log.debug("Setting local source list in properties file to:\n"
761 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
763 while ((data = aparser.getValue("fetchfrom", true)) != null)
765 System.out.println("adding source '" + data + "'");
768 source = new Vector();
770 source.addElement(data);
776 * start a feature fetcher for every alignment frame
780 private static FeatureFetcher startFeatureFetching(final Vector dasSources)
782 FeatureFetcher ff = new FeatureFetcher();
783 AlignFrame afs[] = Desktop.getAlignframes();
784 if (afs == null || afs.length == 0)
788 for (int i = 0; i < afs.length; i++)
790 ff.addFetcher(afs[i], dasSources);
795 private static String checkProtocol(String file)
797 String protocol = jalview.io.FormatAdapter.FILE;
799 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
801 protocol = jalview.io.FormatAdapter.URL;
808 * Notes: this argParser does not distinguish between parameter switches,
809 * parameter values and argument text. If an argument happens to be identical to
810 * a parameter, it will be taken as such (even though it didn't have a '-'
813 * @author Andrew Waterhouse and JBP documented.
820 public ArgsParser(String[] args)
822 vargs = new Vector();
823 for (int i = 0; i < args.length; i++)
825 String arg = args[i].trim();
826 if (arg.charAt(0) == '-')
828 arg = arg.substring(1);
830 vargs.addElement(arg);
835 * check for and remove first occurence of arg+parameter in arglist.
838 * @return return the argument following the given arg if arg was in list.
840 public String getValue(String arg)
842 return getValue(arg, false);
845 public String getValue(String arg, boolean utf8decode)
847 int index = vargs.indexOf(arg);
848 String dc = null, ret = null;
851 ret = vargs.elementAt(index + 1).toString();
852 vargs.removeElementAt(index);
853 vargs.removeElementAt(index);
854 if (utf8decode && ret != null)
858 dc = URLDecoder.decode(ret, "UTF-8");
860 } catch (Exception e)
862 // TODO: log failure to decode
870 * check for and remove first occurence of arg in arglist.
873 * @return true if arg was present in argslist.
875 public boolean contains(String arg)
877 if (vargs.contains(arg))
879 vargs.removeElement(arg);
888 public String nextValue()
890 return vargs.remove(0).toString();
901 * keep track of feature fetching tasks.
909 * TODO: generalise to track all jalview events to orchestrate batch
913 private int queued = 0;
915 private int running = 0;
917 public FeatureFetcher()
922 public void addFetcher(final AlignFrame af, final Vector dasSources)
924 final long id = System.currentTimeMillis();
926 final FeatureFetcher us = this;
927 new Thread(new Runnable()
938 af.setProgressBar("DAS features being retrieved...", id);
939 af.featureSettings_actionPerformed(null);
940 af.featureSettings.fetchDasFeatures(dasSources, true);
941 af.setProgressBar(null, id);
950 public synchronized boolean allFinished()
952 return queued == 0 && running == 0;