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 (alphanumeric or underscores only) for retrieval of features for all alignments.\n"
90 +"\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
91 +"\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 inSession = desktop.vamsasImport(new File(vamsasImport));
225 } catch (Exception e)
227 System.err.println("Exeption when importing "+vamsasImport+" as a vamsas document.");
231 System.err.println("Failed to import "+vamsasImport+" as a vamsas document.");
233 System.out.println("Imported Successfully into new session "+desktop.getVamsasApplication().getCurrentSession());
236 if (vamsasSession!=null) {
237 if (vamsasImport!=null) {
238 // close the newly imported session and import the Jalview specific remnants into the new session later on.
239 desktop.vamsasStop_actionPerformed(null);
241 // now join the new session
243 if (desktop.joinVamsasSession(vamsasSession)) {
244 System.out.println("Successfully joined vamsas session "+vamsasSession);
246 System.err.println("WARNING: Failed to join vamsas session "+vamsasSession);
248 } catch (Exception e)
250 System.err.println("ERROR: Failed to join vamsas session "+vamsasSession);
253 if (vamsasImport!=null) {
254 // the Jalview specific remnants can now be imported into the new session at the user's leisure.
255 Cache.log.info("Skipping Push for import of data into existing vamsas session."); // TODO: enable this when debugged
256 // desktop.getVamsasApplication().push_update();
260 // Finally, deal with the remaining input data.
263 System.out.println("Opening file: " + file);
265 if (!file.startsWith("http://"))
267 if (!(new java.io.File(file)).exists())
269 System.out.println("Can't find " + file);
277 protocol = checkProtocol(file);
279 format = new jalview.io.IdentifyFile().Identify(file, protocol);
281 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
286 System.out.println("error");
290 data = aparser.getValue("colour");
293 data.replaceAll("%20", " ");
295 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
296 .getColour(af.getViewport().getAlignment(), data);
300 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
302 ucs.parseAppletParameter(data);
306 System.out.println("colour is " + data);
310 // Must maintain ability to use the groups flag
311 data = aparser.getValue("groups");
314 af.parseFeaturesFile(data, checkProtocol(data));
315 System.out.println("Added " + data);
317 data = aparser.getValue("features");
320 af.parseFeaturesFile(data, checkProtocol(data));
321 System.out.println("Added " + data);
324 data = aparser.getValue("annotations");
327 af.loadJalviewDataFile(data);
328 System.out.println("Added " + data);
330 // set or clear the sortbytree flag.
331 if (aparser.contains("sortbytree"))
333 af.getViewport().setSortByTree(true);
335 if (aparser.contains("nosortbytree"))
337 af.getViewport().setSortByTree(false);
339 data = aparser.getValue("tree");
342 jalview.io.NewickFile fin = null;
345 fin = new jalview.io.NewickFile(data, checkProtocol(data));
348 af.getViewport().setCurrentTree(
349 af.ShowNewickTree(fin, data).getTree());
350 System.out.println("Added tree " + data);
352 } catch (IOException ex)
354 System.err.println("Couldn't add tree " + data);
355 ex.printStackTrace(System.err);
358 getFeatures = checkDasArguments(aparser);
359 if (af != null && getFeatures != null)
361 startFeatureFetching(getFeatures);
362 // need to block until fetching is complete.
363 while (af.operationInProgress())
365 // wait around until fetching is finished.
369 } catch (Exception e)
375 if (groovyscript != null)
377 // Execute the groovy script after we've done all the rendering stuff
378 // and before any images or figures are generated.
379 if (jalview.bin.Cache.groovyJarsPresent())
381 System.out.println("Executing script " + groovyscript);
382 executeGroovyScript(groovyscript, desktop);
387 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
392 String imageName = "unnamed.png";
393 while (aparser.getSize() > 1)
395 format = aparser.nextValue();
396 file = aparser.nextValue();
398 if (format.equalsIgnoreCase("png"))
400 af.createPNG(new java.io.File(file));
401 imageName = (new java.io.File(file)).getName();
402 System.out.println("Creating PNG image: " + file);
405 else if (format.equalsIgnoreCase("imgMap"))
407 af.createImageMap(new java.io.File(file), imageName);
408 System.out.println("Creating image map: " + file);
411 else if (format.equalsIgnoreCase("eps"))
413 System.out.println("Creating EPS file: " + file);
414 af.createEPS(new java.io.File(file));
418 if (af.saveAlignment(file, format))
420 System.out.println("Written alignment in " + format
421 + " format to " + file);
425 System.out.println("Error writing file " + file + " in " + format
431 while (aparser.getSize() > 0)
433 System.out.println("Unknown arg: " + aparser.nextValue());
436 AlignFrame startUpAlframe = null;
437 // We'll only open the default file if the desktop is visible.
439 // ////////////////////
440 if (!headless && file == null && vamsasImport==null
441 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
443 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
444 "http://www.jalview.org/examples/exampleFile_2_3.jar");
448 if (file.indexOf("http:") > -1)
453 if (file.endsWith(".jar"))
459 format = new jalview.io.IdentifyFile().Identify(file, protocol);
462 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
464 getFeatures = checkDasArguments(aparser);
465 // extract groovy arguments before anything else.
467 // Once all loading is done. Retrieve features.
468 if (getFeatures != null)
470 if (startUpAlframe != null)
472 startFeatureFetching(getFeatures);
475 if (groovyscript != null)
477 if (jalview.bin.Cache.groovyJarsPresent())
479 System.out.println("Executing script " + groovyscript);
480 executeGroovyScript(groovyscript, desktop);
485 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
490 // Once all other stuff is done, execute any groovy scripts (in order)
494 * Locate the given string as a file and pass it to the groovy interpreter.
496 * @param groovyscript
497 * the script to execute
498 * @param jalviewContext
499 * the Jalview Desktop object passed in to the groovy binding
500 * as the 'Jalview' object.
502 private static void executeGroovyScript(String groovyscript,
503 Object jalviewContext)
505 if (jalviewContext == null)
508 .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
511 if (groovyscript.trim().equals("STDIN"))
513 // read from stdin into a tempfile and execute it
516 sfile = File.createTempFile("jalview", "groovy");
517 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
518 new FileOutputStream(sfile)));
519 BufferedReader br = new BufferedReader(
520 new java.io.InputStreamReader(System.in));
522 while ((line = br.readLine()) != null)
524 outfile.write(line + "\n");
530 } catch (Exception ex)
532 System.err.println("Failed to read from STDIN into tempfile "
533 + ((sfile == null) ? "(tempfile wasn't created)" : sfile
535 ex.printStackTrace();
541 sfile = new File(groovyscript);
545 System.err.println("File '" + groovyscript + "' does not exist.");
548 if (!sfile.canRead())
550 System.err.println("File '" + groovyscript + "' cannot be read.");
553 if (sfile.length() < 1)
555 System.err.println("File '" + groovyscript + "' is empty.");
558 boolean success = false;
562 * The following code performs the GroovyScriptEngine invocation using
563 * reflection, and is equivalent to this fragment from the embedding
564 * groovy documentation on the groovy site: <code> import
565 * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
567 * String[] roots = new String[] { "/my/groovy/script/path" };
568 * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding =
569 * new Binding(); binding.setVariable("input", "world");
570 * gse.run("hello.groovy", binding); </code>
572 ClassLoader cl = jalviewContext.getClass().getClassLoader();
573 Class gbindingc = cl.loadClass("groovy.lang.Binding");
574 Constructor gbcons = gbindingc.getConstructor(null);
575 Object gbinding = gbcons.newInstance(null);
576 java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
578 { String.class, Object.class });
579 setvar.invoke(gbinding, new Object[]
580 { "Jalview", jalviewContext });
581 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
582 Constructor gseccons = gsec.getConstructor(new Class[]
583 { URL[].class }); // String[].class });
584 Object gse = gseccons.newInstance(new Object[]
586 { sfile.toURL() } }); // .toString() } });
587 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
588 { String.class, gbindingc });
589 run.invoke(gse, new Object[]
590 { sfile.getName(), gbinding });
592 } catch (Exception e)
594 System.err.println("Exception Whilst trying to execute file " + sfile
595 + " as a groovy script.");
596 e.printStackTrace(System.err);
599 if (success && groovyscript.equals("STDIN"))
601 // delete temp file that we made - but only if it was successfully
608 * Check commandline for any das server definitions or any fetchfrom switches
610 * @return vector of DAS source nicknames to retrieve from
612 private static Vector checkDasArguments(ArgsParser aparser)
614 Vector source = null;
616 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
617 while ((data = aparser.getValue("dasserver")) != null)
619 String nickname = null;
621 boolean seq=false,feat=true;
622 int pos = data.indexOf('=');
623 // determine capabilities
626 nickname = data.substring(0, pos);
628 url = data.substring(pos + 1);
629 if (url != null && (url.startsWith("http:") || url.startsWith("sequence:http:")))
631 if (nickname == null)
635 if (locsources == null)
643 locsources = locsources + nickname + "|" + url;
645 .println("NOTE! dasserver parameter not yet really supported (got args of "
646 + nickname + "|" + url);
649 source = new Vector();
651 source.addElement(nickname);
653 } // loop until no more server entries are found.
654 if (locsources != null && locsources.indexOf('|') > -1)
656 Cache.log.debug("Setting local source list in properties file to:\n"
658 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
660 while ((data = aparser.getValue("fetchfrom")) != null)
662 System.out.println("adding source '" + data + "'");
665 source = new Vector();
667 source.addElement(data);
673 * start a feature fetcher for every alignment frame
677 private static void startFeatureFetching(final Vector dasSources)
679 AlignFrame afs[] = Desktop.getAlignframes();
680 if (afs == null || afs.length == 0)
684 for (int i = 0; i < afs.length; i++)
686 final AlignFrame af = afs[i];
687 SwingUtilities.invokeLater(new Runnable()
692 af.featureSettings_actionPerformed(null);
693 af.featureSettings.fetchDasFeatures(dasSources);
699 private static String checkProtocol(String file)
701 String protocol = jalview.io.FormatAdapter.FILE;
703 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
705 protocol = jalview.io.FormatAdapter.URL;
712 * Notes: this argParser does not distinguish between parameter switches,
713 * parameter values and argument text. If an argument happens to be identical to
714 * a parameter, it will be taken as such (even though it didn't have a '-'
717 * @author Andrew Waterhouse and JBP documented.
724 public ArgsParser(String[] args)
726 vargs = new Vector();
727 for (int i = 0; i < args.length; i++)
729 String arg = args[i].trim();
730 if (arg.charAt(0) == '-')
732 arg = arg.substring(1);
734 vargs.addElement(arg);
739 * check for and remove first occurence of arg+parameter in arglist.
742 * @return return the argument following the given arg if arg was in list.
744 public String getValue(String arg)
746 int index = vargs.indexOf(arg);
750 ret = vargs.elementAt(index + 1).toString();
751 vargs.removeElementAt(index);
752 vargs.removeElementAt(index);
758 * check for and remove first occurence of arg in arglist.
761 * @return true if arg was present in argslist.
763 public boolean contains(String arg)
765 if (vargs.contains(arg))
767 vargs.removeElement(arg);
776 public String nextValue()
778 return vargs.remove(0).toString();