2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
21 import java.io.BufferedReader;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.OutputStreamWriter;
26 import java.io.PrintWriter;
27 import java.lang.reflect.Constructor;
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.io.AppletFormatAdapter;
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"));
83 ArgsParser aparser = new ArgsParser(args);
84 boolean headless = false;
86 if (aparser.contains("help") || aparser.contains("h"))
89 .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
90 + "-nodisplay\tRun Jalview without User Interface.\n"
91 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
92 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
93 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
94 + "-features FILE\tUse the given file to mark features on the alignment.\n"
95 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
96 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
97 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
98 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
99 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
100 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
101 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
102 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
103 + "-png FILE\tCreate PNG image FILE from alignment.\n"
104 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
105 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
106 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
107 + "-noquestionnaire\tTurn off questionnaire check.\n"
108 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
109 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
111 // "-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)"
112 + "-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"
113 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
114 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
115 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
117 // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
118 // + "-vses vamsas-session\tJoin session with given URN\n"
119 + "-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"
120 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
123 Cache.loadProperties(aparser.getValue("props")); // must do this before
125 String defs = aparser.getValue("setprop");
128 int p = defs.indexOf('=');
131 System.err.println("Ignoring invalid setprop argument : " + defs);
135 System.out.println("Executing setprop argument: " + defs);
136 // DISABLED FOR SECURITY REASONS
137 // TODO: add a property to allow properties to be overriden by cli args
138 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
140 defs = aparser.getValue("setprop");
142 if (aparser.contains("nodisplay"))
144 System.setProperty("java.awt.headless", "true");
146 if (System.getProperty("java.awt.headless") != null
147 && System.getProperty("java.awt.headless").equals("true"))
155 } catch (java.lang.NoClassDefFoundError error)
157 error.printStackTrace();
159 .println("\nEssential logging libraries not found."
160 + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
164 Desktop desktop = null;
168 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()
169 // UIManager.getCrossPlatformLookAndFeelClassName()
170 // "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"
171 // "javax.swing.plaf.metal.MetalLookAndFeel"
172 // "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"
173 // "com.sun.java.swing.plaf.motif.MotifLookAndFeel"
176 } catch (Exception ex)
181 desktop = new Desktop();
182 desktop.setVisible(true);
183 desktop.discoverer.start();
184 if (!aparser.contains("nousagestats"))
186 startUsageStats(desktop);
188 if (!aparser.contains("noquestionnaire"))
190 String url = aparser.getValue("questionnaire");
193 // Start the desktop questionnaire prompter with the specified
195 Cache.log.debug("Starting questionnaire url at " + url);
196 desktop.checkForQuestionnaire(url);
200 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
202 // Start the desktop questionnaire prompter with the specified
205 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
207 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
208 Cache.log.debug("Starting questionnaire with default url: "
210 desktop.checkForQuestionnaire(defurl);
217 String file = null, protocol = null, format = null, data = null;
218 jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
219 Vector getFeatures = null; // vector of das source nicknames to fetch
222 String groovyscript = null; // script to execute after all loading is
223 // completed one way or another
224 // extract groovy argument and execute if necessary
225 groovyscript = aparser.getValue("groovy");
226 file = aparser.getValue("open");
228 if (file == null && desktop == null)
230 System.out.println("No files to open!");
233 String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
235 if (vamsasImport != null || vamsasSession != null)
237 if (desktop == null || headless)
240 .println("Headless vamsas sessions not yet supported. Sorry.");
243 // if we have a file, start a new session and import it.
244 boolean inSession = false;
245 if (vamsasImport != null)
249 String viprotocol = Jalview.checkProtocol(vamsasImport);
250 if (viprotocol == jalview.io.FormatAdapter.FILE)
252 inSession = desktop.vamsasImport(new File(vamsasImport));
254 else if (viprotocol == jalview.io.FormatAdapter.URL)
256 inSession = desktop.vamsasImport(new URL(vamsasImport));
259 } catch (Exception e)
261 System.err.println("Exeption when importing " + vamsasImport
262 + " as a vamsas document.");
267 System.err.println("Failed to import " + vamsasImport
268 + " as a vamsas document.");
272 System.out.println("Imported Successfully into new session "
273 + desktop.getVamsasApplication().getCurrentSession());
276 if (vamsasSession != null)
278 if (vamsasImport != null)
280 // close the newly imported session and import the Jalview specific
281 // remnants into the new session later on.
282 desktop.vamsasStop_actionPerformed(null);
284 // now join the new session
287 if (desktop.joinVamsasSession(vamsasSession))
289 System.out.println("Successfully joined vamsas session "
294 System.err.println("WARNING: Failed to join vamsas session "
297 } catch (Exception e)
299 System.err.println("ERROR: Failed to join vamsas session "
303 if (vamsasImport != null)
305 // the Jalview specific remnants can now be imported into the new
306 // session at the user's leisure.
308 .info("Skipping Push for import of data into existing vamsas session."); // TODO:
313 // desktop.getVamsasApplication().push_update();
317 // Finally, deal with the remaining input data.
320 System.out.println("Opening file: " + file);
322 if (!file.startsWith("http://"))
324 if (!(new java.io.File(file)).exists())
326 System.out.println("Can't find " + file);
334 protocol = checkProtocol(file);
336 format = new jalview.io.IdentifyFile().Identify(file, protocol);
338 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
342 System.out.println("error");
346 data = aparser.getValue("colour");
349 data.replaceAll("%20", " ");
351 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
352 .getColour(af.getViewport().getAlignment(), data);
356 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
358 ucs.parseAppletParameter(data);
362 System.out.println("colour is " + data);
366 // Must maintain ability to use the groups flag
367 data = aparser.getValue("groups");
370 af.parseFeaturesFile(data, checkProtocol(data));
371 System.out.println("Added " + data);
373 data = aparser.getValue("features");
376 af.parseFeaturesFile(data, checkProtocol(data));
377 System.out.println("Added " + data);
380 data = aparser.getValue("annotations");
383 af.loadJalviewDataFile(data);
384 System.out.println("Added " + data);
386 // set or clear the sortbytree flag.
387 if (aparser.contains("sortbytree"))
389 af.getViewport().setSortByTree(true);
391 if (aparser.contains("nosortbytree"))
393 af.getViewport().setSortByTree(false);
395 data = aparser.getValue("tree");
398 jalview.io.NewickFile fin = null;
401 fin = new jalview.io.NewickFile(data, checkProtocol(data));
404 af.getViewport().setCurrentTree(
405 af.ShowNewickTree(fin, data).getTree());
406 System.out.println("Added tree " + data);
408 } catch (IOException ex)
410 System.err.println("Couldn't add tree " + data);
411 ex.printStackTrace(System.err);
414 getFeatures = checkDasArguments(aparser);
415 if (af != null && getFeatures != null)
417 startFeatureFetching(getFeatures);
418 // need to block until fetching is complete.
419 while (af.operationInProgress())
421 // wait around until fetching is finished.
425 } catch (Exception e)
431 if (groovyscript != null)
433 // Execute the groovy script after we've done all the rendering stuff
434 // and before any images or figures are generated.
435 if (jalview.bin.Cache.groovyJarsPresent())
437 System.out.println("Executing script " + groovyscript);
438 executeGroovyScript(groovyscript, desktop);
443 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
448 String imageName = "unnamed.png";
449 while (aparser.getSize() > 1)
451 format = aparser.nextValue();
452 file = aparser.nextValue();
454 if (format.equalsIgnoreCase("png"))
456 af.createPNG(new java.io.File(file));
457 imageName = (new java.io.File(file)).getName();
458 System.out.println("Creating PNG image: " + file);
461 else if (format.equalsIgnoreCase("imgMap"))
463 af.createImageMap(new java.io.File(file), imageName);
464 System.out.println("Creating image map: " + file);
467 else if (format.equalsIgnoreCase("eps"))
469 System.out.println("Creating EPS file: " + file);
470 af.createEPS(new java.io.File(file));
474 if (af.saveAlignment(file, format))
476 System.out.println("Written alignment in " + format
477 + " format to " + file);
481 System.out.println("Error writing file " + file + " in " + format
487 while (aparser.getSize() > 0)
489 System.out.println("Unknown arg: " + aparser.nextValue());
492 AlignFrame startUpAlframe = null;
493 // We'll only open the default file if the desktop is visible.
495 // ////////////////////
496 if (!headless && file == null && vamsasImport == null
497 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
499 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
500 "http://www.jalview.org/examples/exampleFile_2_3.jar");
504 if (file.indexOf("http:") > -1)
509 if (file.endsWith(".jar"))
515 format = new jalview.io.IdentifyFile().Identify(file, protocol);
518 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
520 getFeatures = checkDasArguments(aparser);
521 // extract groovy arguments before anything else.
523 // Once all loading is done. Retrieve features.
524 if (getFeatures != null)
526 if (startUpAlframe != null)
528 startFeatureFetching(getFeatures);
531 if (groovyscript != null)
533 if (jalview.bin.Cache.groovyJarsPresent())
535 System.out.println("Executing script " + groovyscript);
536 executeGroovyScript(groovyscript, desktop);
541 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
546 // Once all other stuff is done, execute any groovy scripts (in order)
549 private static void startUsageStats(final Desktop desktop)
552 * start a User Config prompt asking if we can log usage statistics.
554 jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
557 "Jalview Usage Statistics",
558 "Do you want to help make Jalview better by enabling "
559 +"the collection of usage statistics with Google Analytics ?"
560 +"\n\n(you can enable or disable usage tracking in the preferences)",
566 .info("Initialising googletracker for usage stats.");
567 Cache.initGoogleTracker();
568 Cache.log.debug("Tracking enabled.");
574 Cache.log.info("Not enabling Google Tracking.");
577 SwingUtilities.invokeLater(prompter);
581 * Locate the given string as a file and pass it to the groovy interpreter.
583 * @param groovyscript
584 * the script to execute
585 * @param jalviewContext
586 * the Jalview Desktop object passed in to the groovy binding as the
589 private static void executeGroovyScript(String groovyscript,
590 Object jalviewContext)
592 if (jalviewContext == null)
595 .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
598 if (groovyscript.trim().equals("STDIN"))
600 // read from stdin into a tempfile and execute it
603 sfile = File.createTempFile("jalview", "groovy");
604 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
605 new FileOutputStream(sfile)));
606 BufferedReader br = new BufferedReader(
607 new java.io.InputStreamReader(System.in));
609 while ((line = br.readLine()) != null)
611 outfile.write(line + "\n");
617 } catch (Exception ex)
619 System.err.println("Failed to read from STDIN into tempfile "
620 + ((sfile == null) ? "(tempfile wasn't created)" : sfile
622 ex.printStackTrace();
628 sfile = new File(groovyscript);
632 System.err.println("File '" + groovyscript + "' does not exist.");
635 if (!sfile.canRead())
637 System.err.println("File '" + groovyscript + "' cannot be read.");
640 if (sfile.length() < 1)
642 System.err.println("File '" + groovyscript + "' is empty.");
645 boolean success = false;
649 * The following code performs the GroovyScriptEngine invocation using
650 * reflection, and is equivalent to this fragment from the embedding
651 * groovy documentation on the groovy site: <code> import
652 * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
654 * String[] roots = new String[] { "/my/groovy/script/path" };
655 * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
656 * = new Binding(); binding.setVariable("input", "world");
657 * gse.run("hello.groovy", binding); </code>
659 ClassLoader cl = jalviewContext.getClass().getClassLoader();
660 Class gbindingc = cl.loadClass("groovy.lang.Binding");
661 Constructor gbcons = gbindingc.getConstructor(null);
662 Object gbinding = gbcons.newInstance(null);
663 java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
665 { String.class, Object.class });
666 setvar.invoke(gbinding, new Object[]
667 { "Jalview", jalviewContext });
668 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
669 Constructor gseccons = gsec.getConstructor(new Class[]
670 { URL[].class }); // String[].class });
671 Object gse = gseccons.newInstance(new Object[]
673 { sfile.toURL() } }); // .toString() } });
674 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
675 { String.class, gbindingc });
676 run.invoke(gse, new Object[]
677 { sfile.getName(), gbinding });
679 } catch (Exception e)
681 System.err.println("Exception Whilst trying to execute file " + sfile
682 + " as a groovy script.");
683 e.printStackTrace(System.err);
686 if (success && groovyscript.equals("STDIN"))
688 // delete temp file that we made - but only if it was successfully
695 * Check commandline for any das server definitions or any fetchfrom switches
697 * @return vector of DAS source nicknames to retrieve from
699 private static Vector checkDasArguments(ArgsParser aparser)
701 Vector source = null;
703 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
704 while ((data = aparser.getValue("dasserver")) != null)
706 String nickname = null;
708 boolean seq = false, feat = true;
709 int pos = data.indexOf('=');
710 // determine capabilities
713 nickname = data.substring(0, pos);
715 url = data.substring(pos + 1);
717 && (url.startsWith("http:") || url
718 .startsWith("sequence:http:")))
720 if (nickname == null)
724 if (locsources == null)
732 locsources = locsources + nickname + "|" + url;
734 .println("NOTE! dasserver parameter not yet really supported (got args of "
735 + nickname + "|" + url);
738 source = new Vector();
740 source.addElement(nickname);
742 } // loop until no more server entries are found.
743 if (locsources != null && locsources.indexOf('|') > -1)
745 Cache.log.debug("Setting local source list in properties file to:\n"
747 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
749 while ((data = aparser.getValue("fetchfrom")) != null)
751 System.out.println("adding source '" + data + "'");
754 source = new Vector();
756 source.addElement(data);
762 * start a feature fetcher for every alignment frame
766 private static void startFeatureFetching(final Vector dasSources)
768 AlignFrame afs[] = Desktop.getAlignframes();
769 if (afs == null || afs.length == 0)
773 for (int i = 0; i < afs.length; i++)
775 final AlignFrame af = afs[i];
776 SwingUtilities.invokeLater(new Runnable()
781 af.featureSettings_actionPerformed(null);
782 af.featureSettings.fetchDasFeatures(dasSources);
788 private static String checkProtocol(String file)
790 String protocol = jalview.io.FormatAdapter.FILE;
792 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
794 protocol = jalview.io.FormatAdapter.URL;
801 * Notes: this argParser does not distinguish between parameter switches,
802 * parameter values and argument text. If an argument happens to be identical to
803 * a parameter, it will be taken as such (even though it didn't have a '-'
806 * @author Andrew Waterhouse and JBP documented.
813 public ArgsParser(String[] args)
815 vargs = new Vector();
816 for (int i = 0; i < args.length; i++)
818 String arg = args[i].trim();
819 if (arg.charAt(0) == '-')
821 arg = arg.substring(1);
823 vargs.addElement(arg);
828 * check for and remove first occurence of arg+parameter in arglist.
831 * @return return the argument following the given arg if arg was in list.
833 public String getValue(String arg)
835 int index = vargs.indexOf(arg);
839 ret = vargs.elementAt(index + 1).toString();
840 vargs.removeElementAt(index);
841 vargs.removeElementAt(index);
847 * check for and remove first occurence of arg in arglist.
850 * @return true if arg was present in argslist.
852 public boolean contains(String arg)
854 if (vargs.contains(arg))
856 vargs.removeElement(arg);
865 public String nextValue()
867 return vargs.remove(0).toString();