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 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
98 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
99 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
100 + "-features FILE\tUse the given file to mark features on the alignment.\n"
101 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
102 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
103 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
104 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
105 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
106 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
107 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
108 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
109 + "-png FILE\tCreate PNG image FILE from alignment.\n"
110 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
111 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
112 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
113 + "-noquestionnaire\tTurn off questionnaire check.\n"
114 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
115 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
117 // "-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)"
118 + "-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"
119 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
120 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
121 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
123 // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
124 // + "-vses vamsas-session\tJoin session with given URN\n"
125 + "-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"
126 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
129 Cache.loadProperties(aparser.getValue("props")); // must do this before
131 String defs = aparser.getValue("setprop");
134 int p = defs.indexOf('=');
137 System.err.println("Ignoring invalid setprop argument : " + defs);
141 System.out.println("Executing setprop argument: " + defs);
142 // DISABLED FOR SECURITY REASONS
143 // TODO: add a property to allow properties to be overriden by cli args
144 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
146 defs = aparser.getValue("setprop");
148 if (aparser.contains("nodisplay"))
150 System.setProperty("java.awt.headless", "true");
152 if (System.getProperty("java.awt.headless") != null
153 && System.getProperty("java.awt.headless").equals("true"))
161 } catch (java.lang.NoClassDefFoundError error)
163 error.printStackTrace();
165 .println("\nEssential logging libraries not found."
166 + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
170 Desktop desktop = null;
174 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
175 } catch (Exception ex)
181 desktop = new Desktop();
182 desktop.setInBatchMode(true); // indicate we are starting up
183 desktop.setVisible(true);
184 desktop.startServiceDiscovery();
185 if (!aparser.contains("nousagestats"))
187 startUsageStats(desktop);
189 if (!aparser.contains("noquestionnaire"))
191 String url = aparser.getValue("questionnaire");
194 // Start the desktop questionnaire prompter with the specified
196 Cache.log.debug("Starting questionnaire url at " + url);
197 desktop.checkForQuestionnaire(url);
201 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
203 // Start the desktop questionnaire prompter with the specified
206 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
208 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
209 Cache.log.debug("Starting questionnaire with default url: "
211 desktop.checkForQuestionnaire(defurl);
218 String file = null, protocol = null, format = null, data = null;
219 jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
220 Vector getFeatures = null; // vector of das source nicknames to fetch
223 String groovyscript = null; // script to execute after all loading is
224 // completed one way or another
225 // extract groovy argument and execute if necessary
226 groovyscript = aparser.getValue("groovy", true);
227 file = aparser.getValue("open", true);
229 if (file == null && desktop == null)
231 System.out.println("No files to open!");
234 String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
236 if (vamsasImport != null || vamsasSession != null)
238 if (desktop == null || headless)
241 .println("Headless vamsas sessions not yet supported. Sorry.");
244 // if we have a file, start a new session and import it.
245 boolean inSession = false;
246 if (vamsasImport != null)
250 String viprotocol = Jalview.checkProtocol(vamsasImport);
251 if (viprotocol == jalview.io.FormatAdapter.FILE)
253 inSession = desktop.vamsasImport(new File(vamsasImport));
255 else if (viprotocol == jalview.io.FormatAdapter.URL)
257 inSession = desktop.vamsasImport(new URL(vamsasImport));
260 } catch (Exception e)
262 System.err.println("Exeption when importing " + vamsasImport
263 + " as a vamsas document.");
268 System.err.println("Failed to import " + vamsasImport
269 + " as a vamsas document.");
273 System.out.println("Imported Successfully into new session "
274 + desktop.getVamsasApplication().getCurrentSession());
277 if (vamsasSession != null)
279 if (vamsasImport != null)
281 // close the newly imported session and import the Jalview specific
282 // remnants into the new session later on.
283 desktop.vamsasStop_actionPerformed(null);
285 // now join the new session
288 if (desktop.joinVamsasSession(vamsasSession))
290 System.out.println("Successfully joined vamsas session "
295 System.err.println("WARNING: Failed to join vamsas session "
298 } catch (Exception e)
300 System.err.println("ERROR: Failed to join vamsas session "
304 if (vamsasImport != null)
306 // the Jalview specific remnants can now be imported into the new
307 // session at the user's leisure.
309 .info("Skipping Push for import of data into existing vamsas session."); // TODO:
314 // desktop.getVamsasApplication().push_update();
318 // Finally, deal with the remaining input data.
321 System.out.println("Opening file: " + file);
323 if (!file.startsWith("http://"))
325 if (!(new java.io.File(file)).exists())
327 System.out.println("Can't find " + file);
335 protocol = checkProtocol(file);
337 format = new jalview.io.IdentifyFile().Identify(file, protocol);
339 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
343 System.out.println("error");
347 data = aparser.getValue("colour", true);
350 data.replaceAll("%20", " ");
352 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
353 .getColour(af.getViewport().getAlignment(), data);
357 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
359 ucs.parseAppletParameter(data);
363 System.out.println("colour is " + data);
367 // Must maintain ability to use the groups flag
368 data = aparser.getValue("groups", true);
371 af.parseFeaturesFile(data, checkProtocol(data));
372 System.out.println("Added " + data);
374 data = aparser.getValue("features", true);
377 af.parseFeaturesFile(data, checkProtocol(data));
378 System.out.println("Added " + data);
381 data = aparser.getValue("annotations", true);
384 af.loadJalviewDataFile(data);
385 System.out.println("Added " + data);
387 // set or clear the sortbytree flag.
388 if (aparser.contains("sortbytree"))
390 af.getViewport().setSortByTree(true);
392 if (aparser.contains("nosortbytree"))
394 af.getViewport().setSortByTree(false);
396 data = aparser.getValue("tree", true);
399 jalview.io.NewickFile fin = null;
402 fin = new jalview.io.NewickFile(data, checkProtocol(data));
405 af.getViewport().setCurrentTree(
406 af.ShowNewickTree(fin, data).getTree());
407 System.out.println("Added tree " + data);
409 } catch (IOException ex)
411 System.err.println("Couldn't add tree " + data);
412 ex.printStackTrace(System.err);
415 // todo - load PDB structure to alignment
416 // (associate with identical sequence in alignment, or a specified
419 getFeatures = checkDasArguments(aparser);
420 if (af != null && getFeatures != null)
422 FeatureFetcher ff = startFeatureFetching(getFeatures);
424 while (!ff.allFinished() || af.operationInProgress())
426 // wait around until fetching is finished.
430 } catch (Exception e)
435 getFeatures = null; // have retrieved features - forget them now.
437 if (groovyscript != null)
439 // Execute the groovy script after we've done all the rendering stuff
440 // and before any images or figures are generated.
441 if (jalview.bin.Cache.groovyJarsPresent())
443 System.out.println("Executing script " + groovyscript);
444 executeGroovyScript(groovyscript, desktop);
449 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
454 String imageName = "unnamed.png";
455 while (aparser.getSize() > 1)
457 format = aparser.nextValue();
458 file = aparser.nextValue();
460 if (format.equalsIgnoreCase("png"))
462 af.createPNG(new java.io.File(file));
463 imageName = (new java.io.File(file)).getName();
464 System.out.println("Creating PNG image: " + file);
467 else if (format.equalsIgnoreCase("imgMap"))
469 af.createImageMap(new java.io.File(file), imageName);
470 System.out.println("Creating image map: " + file);
473 else if (format.equalsIgnoreCase("eps"))
475 System.out.println("Creating EPS file: " + file);
476 af.createEPS(new java.io.File(file));
480 if (af.saveAlignment(file, format))
482 System.out.println("Written alignment in " + format
483 + " format to " + file);
487 System.out.println("Error writing file " + file + " in " + format
493 while (aparser.getSize() > 0)
495 System.out.println("Unknown arg: " + aparser.nextValue());
498 AlignFrame startUpAlframe = null;
499 // We'll only open the default file if the desktop is visible.
501 // ////////////////////
502 if (!headless && file == null && vamsasImport == null
503 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
505 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
506 "http://www.jalview.org/examples/exampleFile_2_3.jar");
510 if (file.indexOf("http:") > -1)
515 if (file.endsWith(".jar"))
521 format = new jalview.io.IdentifyFile().Identify(file, protocol);
524 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
526 getFeatures = checkDasArguments(aparser);
527 // extract groovy arguments before anything else.
529 // If the user has specified features to be retrieved,
530 // or a groovy script to be executed, do them if they
531 // haven't been done already
532 // fetch features for the default alignment
533 if (getFeatures != null)
535 if (startUpAlframe != null)
537 startFeatureFetching(getFeatures);
540 // Once all other stuff is done, execute any groovy scripts (in order)
541 if (groovyscript != null)
543 if (jalview.bin.Cache.groovyJarsPresent())
545 System.out.println("Executing script " + groovyscript);
546 executeGroovyScript(groovyscript, desktop);
551 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
555 // and finally, turn off batch mode indicator - if the desktop still exists
558 desktop.setInBatchMode(false);
562 private static void startUsageStats(final Desktop desktop)
565 * start a User Config prompt asking if we can log usage statistics.
567 jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
570 "Jalview Usage Statistics",
571 "Do you want to help make Jalview better by enabling "
572 + "the collection of usage statistics with Google Analytics ?"
573 + "\n\n(you can enable or disable usage tracking in the preferences)",
579 .info("Initialising googletracker for usage stats.");
580 Cache.initGoogleTracker();
581 Cache.log.debug("Tracking enabled.");
587 Cache.log.info("Not enabling Google Tracking.");
590 SwingUtilities.invokeLater(prompter);
594 * Locate the given string as a file and pass it to the groovy interpreter.
596 * @param groovyscript
597 * the script to execute
598 * @param jalviewContext
599 * the Jalview Desktop object passed in to the groovy binding as the
602 private static void executeGroovyScript(String groovyscript,
603 Object jalviewContext)
605 if (jalviewContext == null)
608 .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
611 if (groovyscript.trim().equals("STDIN"))
613 // read from stdin into a tempfile and execute it
616 sfile = File.createTempFile("jalview", "groovy");
617 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
618 new FileOutputStream(sfile)));
619 BufferedReader br = new BufferedReader(
620 new java.io.InputStreamReader(System.in));
622 while ((line = br.readLine()) != null)
624 outfile.write(line + "\n");
630 } catch (Exception ex)
632 System.err.println("Failed to read from STDIN into tempfile "
633 + ((sfile == null) ? "(tempfile wasn't created)" : sfile
635 ex.printStackTrace();
641 sfile = new File(groovyscript);
645 System.err.println("File '" + groovyscript + "' does not exist.");
648 if (!sfile.canRead())
650 System.err.println("File '" + groovyscript + "' cannot be read.");
653 if (sfile.length() < 1)
655 System.err.println("File '" + groovyscript + "' is empty.");
658 boolean success = false;
662 * The following code performs the GroovyScriptEngine invocation using
663 * reflection, and is equivalent to this fragment from the embedding
664 * groovy documentation on the groovy site: <code> import
665 * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
667 * String[] roots = new String[] { "/my/groovy/script/path" };
668 * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
669 * = new Binding(); binding.setVariable("input", "world");
670 * gse.run("hello.groovy", binding); </code>
672 ClassLoader cl = jalviewContext.getClass().getClassLoader();
673 Class gbindingc = cl.loadClass("groovy.lang.Binding");
674 Constructor gbcons = gbindingc.getConstructor(null);
675 Object gbinding = gbcons.newInstance(null);
676 java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
678 { String.class, Object.class });
679 setvar.invoke(gbinding, new Object[]
680 { "Jalview", jalviewContext });
681 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
682 Constructor gseccons = gsec.getConstructor(new Class[]
683 { URL[].class }); // String[].class });
684 Object gse = gseccons.newInstance(new Object[]
686 { sfile.toURL() } }); // .toString() } });
687 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
688 { String.class, gbindingc });
689 run.invoke(gse, new Object[]
690 { sfile.getName(), gbinding });
692 } catch (Exception e)
694 System.err.println("Exception Whilst trying to execute file " + sfile
695 + " as a groovy script.");
696 e.printStackTrace(System.err);
699 if (success && groovyscript.equals("STDIN"))
701 // delete temp file that we made - but only if it was successfully
708 * Check commandline for any das server definitions or any fetchfrom switches
710 * @return vector of DAS source nicknames to retrieve from
712 private static Vector checkDasArguments(ArgsParser aparser)
714 Vector source = null;
716 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
717 while ((data = aparser.getValue("dasserver", true)) != null)
719 String nickname = null;
721 boolean seq = false, feat = true;
722 int pos = data.indexOf('=');
723 // determine capabilities
726 nickname = data.substring(0, pos);
728 url = data.substring(pos + 1);
730 && (url.startsWith("http:") || url
731 .startsWith("sequence:http:")))
733 if (nickname == null)
737 if (locsources == null)
745 locsources = locsources + nickname + "|" + url;
747 .println("NOTE! dasserver parameter not yet really supported (got args of "
748 + nickname + "|" + url);
751 source = new Vector();
753 source.addElement(nickname);
755 } // loop until no more server entries are found.
756 if (locsources != null && locsources.indexOf('|') > -1)
758 Cache.log.debug("Setting local source list in properties file to:\n"
760 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
762 while ((data = aparser.getValue("fetchfrom", true)) != null)
764 System.out.println("adding source '" + data + "'");
767 source = new Vector();
769 source.addElement(data);
775 * start a feature fetcher for every alignment frame
779 private static FeatureFetcher startFeatureFetching(final Vector dasSources)
781 FeatureFetcher ff = new FeatureFetcher();
782 AlignFrame afs[] = Desktop.getAlignframes();
783 if (afs == null || afs.length == 0)
787 for (int i = 0; i < afs.length; i++)
789 ff.addFetcher(afs[i], dasSources);
794 private static String checkProtocol(String file)
796 String protocol = jalview.io.FormatAdapter.FILE;
798 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
800 protocol = jalview.io.FormatAdapter.URL;
807 * Notes: this argParser does not distinguish between parameter switches,
808 * parameter values and argument text. If an argument happens to be identical to
809 * a parameter, it will be taken as such (even though it didn't have a '-'
812 * @author Andrew Waterhouse and JBP documented.
819 public ArgsParser(String[] args)
821 vargs = new Vector();
822 for (int i = 0; i < args.length; i++)
824 String arg = args[i].trim();
825 if (arg.charAt(0) == '-')
827 arg = arg.substring(1);
829 vargs.addElement(arg);
834 * check for and remove first occurence of arg+parameter in arglist.
837 * @return return the argument following the given arg if arg was in list.
839 public String getValue(String arg)
841 return getValue(arg, false);
844 public String getValue(String arg, boolean utf8decode)
846 int index = vargs.indexOf(arg);
847 String dc = null, ret = null;
850 ret = vargs.elementAt(index + 1).toString();
851 vargs.removeElementAt(index);
852 vargs.removeElementAt(index);
853 if (utf8decode && ret != null)
857 dc = URLDecoder.decode(ret, "UTF-8");
859 } catch (Exception e)
861 // TODO: log failure to decode
869 * check for and remove first occurence of arg in arglist.
872 * @return true if arg was present in argslist.
874 public boolean contains(String arg)
876 if (vargs.contains(arg))
878 vargs.removeElement(arg);
887 public String nextValue()
889 return vargs.remove(0).toString();
900 * keep track of feature fetching tasks.
908 * TODO: generalise to track all jalview events to orchestrate batch
912 private int queued = 0;
914 private int running = 0;
916 public FeatureFetcher()
921 public void addFetcher(final AlignFrame af, final Vector dasSources)
923 final long id = System.currentTimeMillis();
925 final FeatureFetcher us = this;
926 new Thread(new Runnable()
937 af.setProgressBar("DAS features being retrieved...", id);
938 af.featureSettings_actionPerformed(null);
939 af.featureSettings.fetchDasFeatures(dasSources, true);
940 af.setProgressBar(null, id);
949 public synchronized boolean allFinished()
951 return queued == 0 && running == 0;