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;
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();
321 // Finally, deal with the remaining input data.
324 System.out.println("Opening file: " + file);
326 if (!file.startsWith("http://"))
328 if (!(new java.io.File(file)).exists())
330 System.out.println("Can't find " + file);
339 desktop.setProgressBar("Processing commandline arguments...", Jalview.class.hashCode());
342 protocol = jalview.io.AppletFormatAdapter.checkProtocol(file);
344 format = new jalview.io.IdentifyFile().Identify(file, protocol);
346 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
350 System.out.println("error");
354 data = aparser.getValue("colour", true);
357 data.replaceAll("%20", " ");
359 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
360 .getColour(af.getViewport().getAlignment(), data);
364 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
366 ucs.parseAppletParameter(data);
370 System.out.println("colour is " + data);
374 // Must maintain ability to use the groups flag
375 data = aparser.getValue("groups", true);
378 af.parseFeaturesFile(data, jalview.io.AppletFormatAdapter.checkProtocol(data));
379 System.out.println("Added " + data);
381 data = aparser.getValue("features", true);
384 af.parseFeaturesFile(data, jalview.io.AppletFormatAdapter.checkProtocol(data));
385 System.out.println("Added " + data);
388 data = aparser.getValue("annotations", true);
391 af.loadJalviewDataFile(data, null, null, null);
392 System.out.println("Added " + data);
394 // set or clear the sortbytree flag.
395 if (aparser.contains("sortbytree"))
397 af.getViewport().setSortByTree(true);
399 if (aparser.contains("nosortbytree"))
401 af.getViewport().setSortByTree(false);
403 data = aparser.getValue("tree", true);
406 jalview.io.NewickFile fin = null;
409 fin = new jalview.io.NewickFile(data, jalview.io.AppletFormatAdapter.checkProtocol(data));
412 af.getViewport().setCurrentTree(
413 af.ShowNewickTree(fin, data).getTree());
414 System.out.println("Added tree " + data);
416 } catch (IOException ex)
418 System.err.println("Couldn't add tree " + data);
419 ex.printStackTrace(System.err);
422 // TODO - load PDB structure(s) to alignment JAL-629
423 // (associate with identical sequence in alignment, or a specified
426 getFeatures = checkDasArguments(aparser);
427 if (af != null && getFeatures != null)
429 FeatureFetcher ff = startFeatureFetching(getFeatures);
431 while (!ff.allFinished() || af.operationInProgress())
433 // wait around until fetching is finished.
437 } catch (Exception e)
442 getFeatures = null; // have retrieved features - forget them now.
444 if (groovyscript != null)
446 // Execute the groovy script after we've done all the rendering stuff
447 // and before any images or figures are generated.
448 if (jalview.bin.Cache.groovyJarsPresent())
450 System.out.println("Executing script " + groovyscript);
451 executeGroovyScript(groovyscript, new Object[] {desktop,af});
456 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
461 String imageName = "unnamed.png";
462 while (aparser.getSize() > 1)
464 format = aparser.nextValue();
465 file = aparser.nextValue();
467 if (format.equalsIgnoreCase("png"))
469 af.createPNG(new java.io.File(file));
470 imageName = (new java.io.File(file)).getName();
471 System.out.println("Creating PNG image: " + file);
474 else if (format.equalsIgnoreCase("imgMap"))
476 af.createImageMap(new java.io.File(file), imageName);
477 System.out.println("Creating image map: " + file);
480 else if (format.equalsIgnoreCase("eps"))
482 System.out.println("Creating EPS file: " + file);
483 af.createEPS(new java.io.File(file));
487 if (af.saveAlignment(file, format))
489 System.out.println("Written alignment in " + format
490 + " format to " + file);
494 System.out.println("Error writing file " + file + " in " + format
500 while (aparser.getSize() > 0)
502 System.out.println("Unknown arg: " + aparser.nextValue());
505 AlignFrame startUpAlframe = null;
506 // We'll only open the default file if the desktop is visible.
508 // ////////////////////
509 if (!headless && file == null && vamsasImport == null
510 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
512 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
513 jalview.bin.Cache.getDefault("www.jalview.org", "http://www.jalview.org")+"/examples/exampleFile_2_3.jar");
517 if (file.indexOf("http:") > -1)
522 if (file.endsWith(".jar"))
528 format = new jalview.io.IdentifyFile().Identify(file, protocol);
531 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
533 getFeatures = checkDasArguments(aparser);
534 // extract groovy arguments before anything else.
536 // If the user has specified features to be retrieved,
537 // or a groovy script to be executed, do them if they
538 // haven't been done already
539 // fetch features for the default alignment
540 if (getFeatures != null)
542 if (startUpAlframe != null)
544 startFeatureFetching(getFeatures);
547 // Once all other stuff is done, execute any groovy scripts (in order)
548 if (groovyscript != null)
550 if (jalview.bin.Cache.groovyJarsPresent())
552 System.out.println("Executing script " + groovyscript);
553 executeGroovyScript(groovyscript, new Object[] { desktop, startUpAlframe});
558 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
562 // and finally, turn off batch mode indicator - if the desktop still exists
565 desktop.setProgressBar(null, Jalview.class.hashCode());
566 desktop.setInBatchMode(false);
570 private static void startUsageStats(final Desktop desktop)
573 * start a User Config prompt asking if we can log usage statistics.
575 jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
578 "Jalview Usage Statistics",
579 "Do you want to help make Jalview better by enabling "
580 + "the collection of usage statistics with Google Analytics ?"
581 + "\n\n(you can enable or disable usage tracking in the preferences)",
587 .info("Initialising googletracker for usage stats.");
588 Cache.initGoogleTracker();
589 Cache.log.debug("Tracking enabled.");
595 Cache.log.info("Not enabling Google Tracking.");
598 SwingUtilities.invokeLater(prompter);
602 * Locate the given string as a file and pass it to the groovy interpreter.
604 * @param groovyscript
605 * the script to execute
606 * @param jalviewContext
607 * the Jalview Desktop object passed in to the groovy binding as the
610 private static void executeGroovyScript(String groovyscript,
611 Object[] jalviewContext)
613 if (jalviewContext == null)
616 .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
619 * for scripts contained in files
626 if (groovyscript.trim().equals("STDIN"))
628 // read from stdin into a tempfile and execute it
631 tfile = File.createTempFile("jalview", "groovy");
632 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
633 new FileOutputStream(tfile)));
634 BufferedReader br = new BufferedReader(
635 new java.io.InputStreamReader(System.in));
637 while ((line = br.readLine()) != null)
639 outfile.write(line + "\n");
645 } catch (Exception ex)
647 System.err.println("Failed to read from STDIN into tempfile "
648 + ((tfile == null) ? "(tempfile wasn't created)" : tfile
650 ex.printStackTrace();
654 sfile = tfile.toURI().toURL();
655 } catch (Exception x)
657 System.err.println("Unexpected Malformed URL Exception for temporary file created from STDIN: "+tfile.toURI());
666 sfile = new URI(groovyscript).toURL();
667 } catch (Exception x)
669 tfile = new File(groovyscript);
672 System.err.println("File '" + groovyscript + "' does not exist.");
675 if (!tfile.canRead())
677 System.err.println("File '" + groovyscript + "' cannot be read.");
680 if (tfile.length() < 1)
682 System.err.println("File '" + groovyscript + "' is empty.");
686 sfile = tfile.getAbsoluteFile().toURI().toURL();
687 } catch (Exception ex)
689 System.err.println("Failed to create a file URL for "+tfile.getAbsoluteFile());
694 boolean success = false;
698 * The following code performs the GroovyScriptEngine invocation using
699 * reflection, and is equivalent to this fragment from the embedding
700 * groovy documentation on the groovy site: <code> import
701 * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
703 * String[] roots = new String[] { "/my/groovy/script/path" };
704 * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
705 * = new Binding(); binding.setVariable("input", "world");
706 * gse.run("hello.groovy", binding); </code>
710 int blen = ((jalviewContext[0] == null) ? 0 : 1)
711 + ((jalviewContext[1] == null) ? 0 : 1);
712 String cnames[] = new String[]
713 { "Jalview", "currentAlFrame" };
714 bspec = new Class[blen * 2];
715 binding = new Object[blen * 2];
717 ClassLoader cl = null;
718 Map vbinding = new Hashtable();
719 for (int jc = 0; jc < jalviewContext.length; jc++)
721 if (jalviewContext[jc] != null)
725 cl = jalviewContext[jc].getClass().getClassLoader();
727 bspec[blen * 2] = String.class;
728 bspec[blen * 2 + 1] = Object.class;
729 binding[blen * 2] = cnames[jc];
730 binding[blen * 2 + 1] = jalviewContext[jc];
731 vbinding.put(cnames[jc], jalviewContext[jc]);
735 Class gbindingc = cl.loadClass("groovy.lang.Binding");
740 gbcons = gbindingc.getConstructor(Map.class);
741 gbinding = gbcons.newInstance(vbinding);
742 } catch (NoSuchMethodException x)
744 // old style binding config - using series of string/object values to
746 gbcons = gbindingc.getConstructor(null);
747 gbinding = gbcons.newInstance(null);
748 java.lang.reflect.Method setvar = gbindingc.getMethod(
749 "setVariable", bspec);
750 setvar.invoke(gbinding, binding);
753 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
754 Constructor gseccons = gsec.getConstructor(new Class[]
755 { URL[].class }); // String[].class });
756 Object gse = gseccons.newInstance(new Object[]
758 { sfile } }); // .toString() } });
759 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
760 { String.class, gbindingc });
761 run.invoke(gse, new Object[]
762 { sfile.toString(), gbinding });
764 } catch (Exception e)
766 System.err.println("Exception Whilst trying to execute file " + sfile
767 + " as a groovy script.");
768 e.printStackTrace(System.err);
771 if (success && groovyscript.equals("STDIN"))
773 // delete temp file that we made - but only if it was successfully
780 * Check commandline for any das server definitions or any fetchfrom switches
782 * @return vector of DAS source nicknames to retrieve from
784 private static Vector checkDasArguments(ArgsParser aparser)
786 Vector source = null;
788 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
789 while ((data = aparser.getValue("dasserver", true)) != null)
791 String nickname = null;
793 boolean seq = false, feat = true;
794 int pos = data.indexOf('=');
795 // determine capabilities
798 nickname = data.substring(0, pos);
800 url = data.substring(pos + 1);
802 && (url.startsWith("http:") || url
803 .startsWith("sequence:http:")))
805 if (nickname == null)
809 if (locsources == null)
817 locsources = locsources + nickname + "|" + url;
819 .println("NOTE! dasserver parameter not yet really supported (got args of "
820 + nickname + "|" + url);
823 source = new Vector();
825 source.addElement(nickname);
827 } // loop until no more server entries are found.
828 if (locsources != null && locsources.indexOf('|') > -1)
830 Cache.log.debug("Setting local source list in properties file to:\n"
832 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
834 while ((data = aparser.getValue("fetchfrom", true)) != null)
836 System.out.println("adding source '" + data + "'");
839 source = new Vector();
841 source.addElement(data);
847 * start a feature fetcher for every alignment frame
851 private static FeatureFetcher startFeatureFetching(final Vector dasSources)
853 FeatureFetcher ff = new FeatureFetcher();
854 AlignFrame afs[] = Desktop.getAlignframes();
855 if (afs == null || afs.length == 0)
859 for (int i = 0; i < afs.length; i++)
861 ff.addFetcher(afs[i], dasSources);
868 * Notes: this argParser does not distinguish between parameter switches,
869 * parameter values and argument text. If an argument happens to be identical to
870 * a parameter, it will be taken as such (even though it didn't have a '-'
873 * @author Andrew Waterhouse and JBP documented.
880 public ArgsParser(String[] args)
882 vargs = new Vector();
883 for (int i = 0; i < args.length; i++)
885 String arg = args[i].trim();
886 if (arg.charAt(0) == '-')
888 arg = arg.substring(1);
890 vargs.addElement(arg);
895 * check for and remove first occurence of arg+parameter in arglist.
898 * @return return the argument following the given arg if arg was in list.
900 public String getValue(String arg)
902 return getValue(arg, false);
905 public String getValue(String arg, boolean utf8decode)
907 int index = vargs.indexOf(arg);
908 String dc = null, ret = null;
911 ret = vargs.elementAt(index + 1).toString();
912 vargs.removeElementAt(index);
913 vargs.removeElementAt(index);
914 if (utf8decode && ret != null)
918 dc = URLDecoder.decode(ret, "UTF-8");
920 } catch (Exception e)
922 // TODO: log failure to decode
930 * check for and remove first occurence of arg in arglist.
933 * @return true if arg was present in argslist.
935 public boolean contains(String arg)
937 if (vargs.contains(arg))
939 vargs.removeElement(arg);
948 public String nextValue()
950 return vargs.remove(0).toString();
961 * keep track of feature fetching tasks.
969 * TODO: generalise to track all jalview events to orchestrate batch
973 private int queued = 0;
975 private int running = 0;
977 public FeatureFetcher()
982 public void addFetcher(final AlignFrame af, final Vector dasSources)
984 final long id = System.currentTimeMillis();
986 final FeatureFetcher us = this;
987 new Thread(new Runnable()
998 af.setProgressBar("DAS features being retrieved...", id);
999 af.featureSettings_actionPerformed(null);
1000 af.featureSettings.fetchDasFeatures(dasSources, true);
1001 af.setProgressBar(null, id);
1010 public synchronized boolean allFinished()
1012 return queued == 0 && running == 0;