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;
34 import jalview.io.AppletFormatAdapter;
37 * Main class for Jalview Application <br>
39 * start with java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview
48 * main class for Jalview application
51 * open <em>filename</em>
53 public static void main(String[] args)
55 System.out.println("Java version: "
56 + System.getProperty("java.version"));
57 System.out.println(System.getProperty("os.arch") + " "
58 + System.getProperty("os.name") + " "
59 + System.getProperty("os.version"));
61 ArgsParser aparser = new ArgsParser(args);
62 boolean headless = false;
64 if (aparser.contains("help") || aparser.contains("h"))
67 .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
68 + "-nodisplay\tRun Jalview without User Interface.\n"
69 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
70 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
71 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
72 + "-features FILE\tUse the given file to mark features on the alignment.\n"
73 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
74 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
75 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
76 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
77 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
78 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
79 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
80 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
81 + "-png FILE\tCreate PNG image FILE from alignment.\n"
82 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
83 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
84 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
85 + "-noquestionnaire\tTurn off questionnaire check.\n"
86 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
87 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
88 // + "-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)"
89 + "-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"
90 +"\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
91 +"\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
92 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
93 // + "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
94 // + "-vses vamsas-session\tJoin session with given URN\n"
95 + "-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"
96 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
99 Cache.loadProperties(aparser.getValue("props")); // must do this before
101 String defs = aparser.getValue("setprop");
104 int p = defs.indexOf('=');
107 System.err.println("Ignoring invalid setprop argument : "+defs);
109 System.out.println("Executing setprop argument: "+defs);
110 // DISABLED FOR SECURITY REASONS
111 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
113 defs = aparser.getValue("setprop");
115 if (aparser.contains("nodisplay"))
117 System.setProperty("java.awt.headless", "true");
119 if (System.getProperty("java.awt.headless") != null
120 && System.getProperty("java.awt.headless").equals("true"))
128 } catch (java.lang.NoClassDefFoundError error)
130 error.printStackTrace();
132 .println("\nEssential logging libraries not found."
133 + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
137 Desktop desktop = null;
141 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()
142 // UIManager.getCrossPlatformLookAndFeelClassName()
143 // "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"
144 // "javax.swing.plaf.metal.MetalLookAndFeel"
145 // "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"
146 // "com.sun.java.swing.plaf.motif.MotifLookAndFeel"
150 } catch (Exception ex)
155 desktop = new Desktop();
156 desktop.setVisible(true);
157 desktop.discoverer.start();
158 if (!aparser.contains("nousagestats") && Cache.getDefault("USAGESTATS", true)) {
159 Cache.log.info("Initialising googletracker for usage stats.");
160 Cache.initGoogleTracker();
161 Cache.log.debug("Tracking enabled.");
163 Cache.log.info("Not enabling Google Tracking.");
165 if (!aparser.contains("noquestionnaire"))
167 String url = aparser.getValue("questionnaire");
170 // Start the desktop questionnaire prompter with the specified
172 Cache.log.debug("Starting questionnaire url at " + url);
173 desktop.checkForQuestionnaire(url);
177 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
179 // Start the desktop questionnaire prompter with the specified
182 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
184 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
185 Cache.log.debug("Starting questionnaire with default url: "
187 desktop.checkForQuestionnaire(defurl);
194 String file = null, protocol = null, format = null, data = null;
195 jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
196 Vector getFeatures = null; // vector of das source nicknames to fetch
199 String groovyscript = null; // script to execute after all loading is
200 // completed one way or another
201 // extract groovy argument and execute if necessary
202 groovyscript = aparser.getValue("groovy");
203 file = aparser.getValue("open");
205 if (file == null && desktop == null)
207 System.out.println("No files to open!");
210 String vamsasImport=aparser.getValue("vdoc"),vamsasSession=aparser.getValue("vsess");
211 if (vamsasImport!=null || vamsasSession!=null)
213 if (desktop==null || headless)
215 System.out.println("Headless vamsas sessions not yet supported. Sorry.");
218 // if we have a file, start a new session and import it.
219 boolean inSession = false;
220 if (vamsasImport!=null)
223 String viprotocol = Jalview.checkProtocol(vamsasImport);
224 if (viprotocol == jalview.io.FormatAdapter.FILE) {
225 inSession = desktop.vamsasImport(new File(vamsasImport));
226 } else if (viprotocol == jalview.io.FormatAdapter.URL) {
227 inSession = desktop.vamsasImport(new URL(vamsasImport));
230 } catch (Exception e)
232 System.err.println("Exeption when importing "+vamsasImport+" as a vamsas document.");
236 System.err.println("Failed to import "+vamsasImport+" as a vamsas document.");
238 System.out.println("Imported Successfully into new session "+desktop.getVamsasApplication().getCurrentSession());
241 if (vamsasSession!=null) {
242 if (vamsasImport!=null) {
243 // close the newly imported session and import the Jalview specific remnants into the new session later on.
244 desktop.vamsasStop_actionPerformed(null);
246 // now join the new session
248 if (desktop.joinVamsasSession(vamsasSession)) {
249 System.out.println("Successfully joined vamsas session "+vamsasSession);
251 System.err.println("WARNING: Failed to join vamsas session "+vamsasSession);
253 } catch (Exception e)
255 System.err.println("ERROR: Failed to join vamsas session "+vamsasSession);
258 if (vamsasImport!=null) {
259 // the Jalview specific remnants can now be imported into the new session at the user's leisure.
260 Cache.log.info("Skipping Push for import of data into existing vamsas session."); // TODO: enable this when debugged
261 // desktop.getVamsasApplication().push_update();
265 // Finally, deal with the remaining input data.
268 System.out.println("Opening file: " + file);
270 if (!file.startsWith("http://"))
272 if (!(new java.io.File(file)).exists())
274 System.out.println("Can't find " + file);
282 protocol = checkProtocol(file);
284 format = new jalview.io.IdentifyFile().Identify(file, protocol);
286 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
291 System.out.println("error");
295 data = aparser.getValue("colour");
298 data.replaceAll("%20", " ");
300 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
301 .getColour(af.getViewport().getAlignment(), data);
305 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
307 ucs.parseAppletParameter(data);
311 System.out.println("colour is " + data);
315 // Must maintain ability to use the groups flag
316 data = aparser.getValue("groups");
319 af.parseFeaturesFile(data, checkProtocol(data));
320 System.out.println("Added " + data);
322 data = aparser.getValue("features");
325 af.parseFeaturesFile(data, checkProtocol(data));
326 System.out.println("Added " + data);
329 data = aparser.getValue("annotations");
332 af.loadJalviewDataFile(data);
333 System.out.println("Added " + data);
335 // set or clear the sortbytree flag.
336 if (aparser.contains("sortbytree"))
338 af.getViewport().setSortByTree(true);
340 if (aparser.contains("nosortbytree"))
342 af.getViewport().setSortByTree(false);
344 data = aparser.getValue("tree");
347 jalview.io.NewickFile fin = null;
350 fin = new jalview.io.NewickFile(data, checkProtocol(data));
353 af.getViewport().setCurrentTree(
354 af.ShowNewickTree(fin, data).getTree());
355 System.out.println("Added tree " + data);
357 } catch (IOException ex)
359 System.err.println("Couldn't add tree " + data);
360 ex.printStackTrace(System.err);
363 getFeatures = checkDasArguments(aparser);
364 if (af != null && getFeatures != null)
366 startFeatureFetching(getFeatures);
367 // need to block until fetching is complete.
368 while (af.operationInProgress())
370 // wait around until fetching is finished.
374 } catch (Exception e)
380 if (groovyscript != null)
382 // Execute the groovy script after we've done all the rendering stuff
383 // and before any images or figures are generated.
384 if (jalview.bin.Cache.groovyJarsPresent())
386 System.out.println("Executing script " + groovyscript);
387 executeGroovyScript(groovyscript, desktop);
392 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
397 String imageName = "unnamed.png";
398 while (aparser.getSize() > 1)
400 format = aparser.nextValue();
401 file = aparser.nextValue();
403 if (format.equalsIgnoreCase("png"))
405 af.createPNG(new java.io.File(file));
406 imageName = (new java.io.File(file)).getName();
407 System.out.println("Creating PNG image: " + file);
410 else if (format.equalsIgnoreCase("imgMap"))
412 af.createImageMap(new java.io.File(file), imageName);
413 System.out.println("Creating image map: " + file);
416 else if (format.equalsIgnoreCase("eps"))
418 System.out.println("Creating EPS file: " + file);
419 af.createEPS(new java.io.File(file));
423 if (af.saveAlignment(file, format))
425 System.out.println("Written alignment in " + format
426 + " format to " + file);
430 System.out.println("Error writing file " + file + " in " + format
436 while (aparser.getSize() > 0)
438 System.out.println("Unknown arg: " + aparser.nextValue());
441 AlignFrame startUpAlframe = null;
442 // We'll only open the default file if the desktop is visible.
444 // ////////////////////
445 if (!headless && file == null && vamsasImport==null
446 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
448 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
449 "http://www.jalview.org/examples/exampleFile_2_3.jar");
453 if (file.indexOf("http:") > -1)
458 if (file.endsWith(".jar"))
464 format = new jalview.io.IdentifyFile().Identify(file, protocol);
467 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
469 getFeatures = checkDasArguments(aparser);
470 // extract groovy arguments before anything else.
472 // Once all loading is done. Retrieve features.
473 if (getFeatures != null)
475 if (startUpAlframe != null)
477 startFeatureFetching(getFeatures);
480 if (groovyscript != null)
482 if (jalview.bin.Cache.groovyJarsPresent())
484 System.out.println("Executing script " + groovyscript);
485 executeGroovyScript(groovyscript, desktop);
490 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
495 // Once all other stuff is done, execute any groovy scripts (in order)
499 * Locate the given string as a file and pass it to the groovy interpreter.
501 * @param groovyscript
502 * the script to execute
503 * @param jalviewContext
504 * the Jalview Desktop object passed in to the groovy binding
505 * as the 'Jalview' object.
507 private static void executeGroovyScript(String groovyscript,
508 Object jalviewContext)
510 if (jalviewContext == null)
513 .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
516 if (groovyscript.trim().equals("STDIN"))
518 // read from stdin into a tempfile and execute it
521 sfile = File.createTempFile("jalview", "groovy");
522 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
523 new FileOutputStream(sfile)));
524 BufferedReader br = new BufferedReader(
525 new java.io.InputStreamReader(System.in));
527 while ((line = br.readLine()) != null)
529 outfile.write(line + "\n");
535 } catch (Exception ex)
537 System.err.println("Failed to read from STDIN into tempfile "
538 + ((sfile == null) ? "(tempfile wasn't created)" : sfile
540 ex.printStackTrace();
546 sfile = new File(groovyscript);
550 System.err.println("File '" + groovyscript + "' does not exist.");
553 if (!sfile.canRead())
555 System.err.println("File '" + groovyscript + "' cannot be read.");
558 if (sfile.length() < 1)
560 System.err.println("File '" + groovyscript + "' is empty.");
563 boolean success = false;
567 * The following code performs the GroovyScriptEngine invocation using
568 * reflection, and is equivalent to this fragment from the embedding
569 * groovy documentation on the groovy site: <code> import
570 * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
572 * String[] roots = new String[] { "/my/groovy/script/path" };
573 * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding =
574 * new Binding(); binding.setVariable("input", "world");
575 * gse.run("hello.groovy", binding); </code>
577 ClassLoader cl = jalviewContext.getClass().getClassLoader();
578 Class gbindingc = cl.loadClass("groovy.lang.Binding");
579 Constructor gbcons = gbindingc.getConstructor(null);
580 Object gbinding = gbcons.newInstance(null);
581 java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
583 { String.class, Object.class });
584 setvar.invoke(gbinding, new Object[]
585 { "Jalview", jalviewContext });
586 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
587 Constructor gseccons = gsec.getConstructor(new Class[]
588 { URL[].class }); // String[].class });
589 Object gse = gseccons.newInstance(new Object[]
591 { sfile.toURL() } }); // .toString() } });
592 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
593 { String.class, gbindingc });
594 run.invoke(gse, new Object[]
595 { sfile.getName(), gbinding });
597 } catch (Exception e)
599 System.err.println("Exception Whilst trying to execute file " + sfile
600 + " as a groovy script.");
601 e.printStackTrace(System.err);
604 if (success && groovyscript.equals("STDIN"))
606 // delete temp file that we made - but only if it was successfully
613 * Check commandline for any das server definitions or any fetchfrom switches
615 * @return vector of DAS source nicknames to retrieve from
617 private static Vector checkDasArguments(ArgsParser aparser)
619 Vector source = null;
621 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
622 while ((data = aparser.getValue("dasserver")) != null)
624 String nickname = null;
626 boolean seq=false,feat=true;
627 int pos = data.indexOf('=');
628 // determine capabilities
631 nickname = data.substring(0, pos);
633 url = data.substring(pos + 1);
634 if (url != null && (url.startsWith("http:") || url.startsWith("sequence:http:")))
636 if (nickname == null)
640 if (locsources == null)
648 locsources = locsources + nickname + "|" + url;
650 .println("NOTE! dasserver parameter not yet really supported (got args of "
651 + nickname + "|" + url);
654 source = new Vector();
656 source.addElement(nickname);
658 } // loop until no more server entries are found.
659 if (locsources != null && locsources.indexOf('|') > -1)
661 Cache.log.debug("Setting local source list in properties file to:\n"
663 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
665 while ((data = aparser.getValue("fetchfrom")) != null)
667 System.out.println("adding source '" + data + "'");
670 source = new Vector();
672 source.addElement(data);
678 * start a feature fetcher for every alignment frame
682 private static void startFeatureFetching(final Vector dasSources)
684 AlignFrame afs[] = Desktop.getAlignframes();
685 if (afs == null || afs.length == 0)
689 for (int i = 0; i < afs.length; i++)
691 final AlignFrame af = afs[i];
692 SwingUtilities.invokeLater(new Runnable()
697 af.featureSettings_actionPerformed(null);
698 af.featureSettings.fetchDasFeatures(dasSources);
704 private static String checkProtocol(String file)
706 String protocol = jalview.io.FormatAdapter.FILE;
708 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
710 protocol = jalview.io.FormatAdapter.URL;
717 * Notes: this argParser does not distinguish between parameter switches,
718 * parameter values and argument text. If an argument happens to be identical to
719 * a parameter, it will be taken as such (even though it didn't have a '-'
722 * @author Andrew Waterhouse and JBP documented.
729 public ArgsParser(String[] args)
731 vargs = new Vector();
732 for (int i = 0; i < args.length; i++)
734 String arg = args[i].trim();
735 if (arg.charAt(0) == '-')
737 arg = arg.substring(1);
739 vargs.addElement(arg);
744 * check for and remove first occurence of arg+parameter in arglist.
747 * @return return the argument following the given arg if arg was in list.
749 public String getValue(String arg)
751 int index = vargs.indexOf(arg);
755 ret = vargs.elementAt(index + 1).toString();
756 vargs.removeElementAt(index);
757 vargs.removeElementAt(index);
763 * check for and remove first occurence of arg in arglist.
766 * @return true if arg was present in argslist.
768 public boolean contains(String arg)
770 if (vargs.contains(arg))
772 vargs.removeElement(arg);
781 public String nextValue()
783 return vargs.remove(0).toString();