2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4.0.b2)
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 + "-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"
88 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
89 + "-groovy FILE\tExecute groovy script in FILE, after all other arguments have been processed\n\t\t(if FILE is the text 'STDIN' then the file will be read from STDIN)\n"
90 + "\n\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
94 Cache.loadProperties(aparser.getValue("props")); // must do this before
97 if (aparser.contains("nodisplay"))
99 System.setProperty("java.awt.headless", "true");
101 if (System.getProperty("java.awt.headless") != null
102 && System.getProperty("java.awt.headless").equals("true"))
110 } catch (java.lang.NoClassDefFoundError error)
112 error.printStackTrace();
114 .println("\nEssential logging libraries not found."
115 + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
119 Desktop desktop = null;
123 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()
124 // UIManager.getCrossPlatformLookAndFeelClassName()
125 // "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"
126 // "javax.swing.plaf.metal.MetalLookAndFeel"
127 // "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"
128 // "com.sun.java.swing.plaf.motif.MotifLookAndFeel"
131 } catch (Exception ex)
136 desktop = new Desktop();
137 desktop.setVisible(true);
138 desktop.discoverer.start();
139 if (!aparser.contains("nousagestats")) {
140 startUsageStats(desktop);
142 if (!aparser.contains("noquestionnaire"))
144 String url = aparser.getValue("questionnaire");
147 // Start the desktop questionnaire prompter with the specified
149 Cache.log.debug("Starting questionnaire url at " + url);
150 desktop.checkForQuestionnaire(url);
154 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
156 // Start the desktop questionnaire prompter with the specified
159 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
161 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
162 Cache.log.debug("Starting questionnaire with default url: "
164 desktop.checkForQuestionnaire(defurl);
171 String file = null, protocol = null, format = null, data = null;
172 jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
173 Vector getFeatures = null; // vector of das source nicknames to fetch
176 String groovyscript = null; // script to execute after all loading is
177 // completed one way or another
178 // extract groovy argument and execute if necessary
179 groovyscript = aparser.getValue("groovy");
180 file = aparser.getValue("open");
182 if (file == null && desktop == null)
184 System.out.println("No files to open!");
190 System.out.println("Opening file: " + file);
192 if (!file.startsWith("http://"))
194 if (!(new java.io.File(file)).exists())
196 System.out.println("Can't find " + file);
204 protocol = checkProtocol(file);
206 format = new jalview.io.IdentifyFile().Identify(file, protocol);
208 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
213 System.out.println("error");
217 data = aparser.getValue("colour");
220 data.replaceAll("%20", " ");
222 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
223 .getColour(af.getViewport().getAlignment(), data);
227 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
229 ucs.parseAppletParameter(data);
233 System.out.println("colour is " + data);
237 // Must maintain ability to use the groups flag
238 data = aparser.getValue("groups");
241 af.parseFeaturesFile(data, checkProtocol(data));
242 System.out.println("Added " + data);
244 data = aparser.getValue("features");
247 af.parseFeaturesFile(data, checkProtocol(data));
248 System.out.println("Added " + data);
251 data = aparser.getValue("annotations");
254 af.loadJalviewDataFile(data);
255 System.out.println("Added " + data);
257 data = aparser.getValue("tree");
260 jalview.io.NewickFile fin = null;
263 fin = new jalview.io.NewickFile(data, checkProtocol(data));
266 af.getViewport().setCurrentTree(
267 af.ShowNewickTree(fin, data).getTree());
268 System.out.println("Added tree " + data);
270 } catch (IOException ex)
272 System.err.println("Couldn't add tree " + data);
273 ex.printStackTrace(System.err);
276 getFeatures = checkDasArguments(aparser);
277 if (af != null && getFeatures != null)
279 startFeatureFetching(getFeatures);
280 // need to block until fetching is complete.
281 while (af.operationInProgress())
283 // wait around until fetching is finished.
287 } catch (Exception e)
293 if (groovyscript != null)
295 // Execute the groovy script after we've done all the rendering stuff
296 // and before any images or figures are generated.
297 if (jalview.bin.Cache.groovyJarsPresent())
299 System.out.println("Executing script " + groovyscript);
300 executeGroovyScript(groovyscript, desktop);
305 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
310 String imageName = "unnamed.png";
311 while (aparser.getSize() > 1)
313 format = aparser.nextValue();
314 file = aparser.nextValue();
316 if (format.equalsIgnoreCase("png"))
318 af.createPNG(new java.io.File(file));
319 imageName = (new java.io.File(file)).getName();
320 System.out.println("Creating PNG image: " + file);
323 else if (format.equalsIgnoreCase("imgMap"))
325 af.createImageMap(new java.io.File(file), imageName);
326 System.out.println("Creating image map: " + file);
329 else if (format.equalsIgnoreCase("eps"))
331 System.out.println("Creating EPS file: " + file);
332 af.createEPS(new java.io.File(file));
336 if (af.saveAlignment(file, format))
338 System.out.println("Written alignment in " + format
339 + " format to " + file);
343 System.out.println("Error writing file " + file + " in " + format
349 while (aparser.getSize() > 0)
351 System.out.println("Unknown arg: " + aparser.nextValue());
354 AlignFrame startUpAlframe = null;
355 // We'll only open the default file if the desktop is visible.
357 // ////////////////////
358 if (!headless && file == null
359 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
361 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
362 "http://www.jalview.org/examples/exampleFile_2_3.jar");
366 if (file.indexOf("http:") > -1)
371 if (file.endsWith(".jar"))
377 format = new jalview.io.IdentifyFile().Identify(file, protocol);
380 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
382 getFeatures = checkDasArguments(aparser);
383 // extract groovy arguments before anything else.
385 // Once all loading is done. Retrieve features.
386 if (getFeatures != null)
388 if (startUpAlframe != null)
390 startFeatureFetching(getFeatures);
393 if (groovyscript != null)
395 if (jalview.bin.Cache.groovyJarsPresent())
397 System.out.println("Executing script " + groovyscript);
398 executeGroovyScript(groovyscript, desktop);
403 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
408 // Once all other stuff is done, execute any groovy scripts (in order)
411 private static void startUsageStats(final Desktop desktop)
414 * start a User Config prompt asking if we can log usage statistics.
416 jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(desktop.desktop,"USAGESTATS", "Jalview Usage Statistics", "Jalview uses Google Analytics to report usage statistics.\nDo you want to enable this ?\n\n(if you press cancel, you will be asked again next time)",
420 Cache.log.info("Initialising googletracker for usage stats.");
421 Cache.initGoogleTracker();
422 Cache.log.debug("Tracking enabled.");
427 Cache.log.info("Not enabling Google Tracking.");
430 SwingUtilities.invokeLater(prompter);
434 * Locate the given string as a file and pass it to the groovy interpreter.
436 * @param groovyscript
437 * the script to execute
438 * @param jalviewContext
439 * the Jalview Desktop object passed in to the groovy binding
440 * as the 'Jalview' object.
442 private static void executeGroovyScript(String groovyscript,
443 Object jalviewContext)
445 if (jalviewContext == null)
448 .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
451 if (groovyscript.trim().equals("STDIN"))
453 // read from stdin into a tempfile and execute it
456 sfile = File.createTempFile("jalview", "groovy");
457 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
458 new FileOutputStream(sfile)));
459 BufferedReader br = new BufferedReader(
460 new java.io.InputStreamReader(System.in));
462 while ((line = br.readLine()) != null)
464 outfile.write(line + "\n");
470 } catch (Exception ex)
472 System.err.println("Failed to read from STDIN into tempfile "
473 + ((sfile == null) ? "(tempfile wasn't created)" : sfile
475 ex.printStackTrace();
481 sfile = new File(groovyscript);
485 System.err.println("File '" + groovyscript + "' does not exist.");
488 if (!sfile.canRead())
490 System.err.println("File '" + groovyscript + "' cannot be read.");
493 if (sfile.length() < 1)
495 System.err.println("File '" + groovyscript + "' is empty.");
498 boolean success = false;
502 * The following code performs the GroovyScriptEngine invocation using
503 * reflection, and is equivalent to this fragment from the embedding
504 * groovy documentation on the groovy site: <code> import
505 * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
507 * String[] roots = new String[] { "/my/groovy/script/path" };
508 * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding =
509 * new Binding(); binding.setVariable("input", "world");
510 * gse.run("hello.groovy", binding); </code>
512 ClassLoader cl = jalviewContext.getClass().getClassLoader();
513 Class gbindingc = cl.loadClass("groovy.lang.Binding");
514 Constructor gbcons = gbindingc.getConstructor(null);
515 Object gbinding = gbcons.newInstance(null);
516 java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
518 { String.class, Object.class });
519 setvar.invoke(gbinding, new Object[]
520 { "Jalview", jalviewContext });
521 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
522 Constructor gseccons = gsec.getConstructor(new Class[]
523 { URL[].class }); // String[].class });
524 Object gse = gseccons.newInstance(new Object[]
526 { sfile.toURL() } }); // .toString() } });
527 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
528 { String.class, gbindingc });
529 run.invoke(gse, new Object[]
530 { sfile.getName(), gbinding });
532 } catch (Exception e)
534 System.err.println("Exception Whilst trying to execute file " + sfile
535 + " as a groovy script.");
536 e.printStackTrace(System.err);
539 if (success && groovyscript.equals("STDIN"))
541 // delete temp file that we made - but only if it was successfully
548 * Check commandline for any das server definitions or any fetchfrom switches
550 * @return vector of DAS source nicknames to retrieve from
552 private static Vector checkDasArguments(ArgsParser aparser)
554 Vector source = null;
556 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
557 while ((data = aparser.getValue("dasserver")) != null)
559 String nickname = null;
561 int pos = data.indexOf('=');
564 nickname = data.substring(0, pos);
566 url = data.substring(pos + 1);
567 if (url != null && url.startsWith("http:"))
569 if (nickname == null)
573 if (locsources == null)
581 locsources = locsources + nickname + "|" + url;
583 .println("NOTE! dasserver parameter not yet really supported (got args of "
584 + nickname + "|" + url);
587 source = new Vector();
589 source.addElement(nickname);
591 } // loop until no more server entries are found.
592 if (locsources != null && locsources.indexOf('|') > -1)
594 Cache.log.debug("Setting local source list in properties file to:\n"
596 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
598 while ((data = aparser.getValue("fetchfrom")) != null)
600 System.out.println("adding source '" + data + "'");
603 source = new Vector();
605 source.addElement(data);
611 * start a feature fetcher for every alignment frame
615 private static void startFeatureFetching(final Vector dasSources)
617 AlignFrame afs[] = Desktop.getAlignframes();
618 if (afs == null || afs.length == 0)
622 for (int i = 0; i < afs.length; i++)
624 final AlignFrame af = afs[i];
625 SwingUtilities.invokeLater(new Runnable()
630 af.featureSettings_actionPerformed(null);
631 af.featureSettings.fetchDasFeatures(dasSources);
637 private static String checkProtocol(String file)
639 String protocol = jalview.io.FormatAdapter.FILE;
641 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
643 protocol = jalview.io.FormatAdapter.URL;
650 * Notes: this argParser does not distinguish between parameter switches,
651 * parameter values and argument text. If an argument happens to be identical to
652 * a parameter, it will be taken as such (even though it didn't have a '-'
655 * @author Andrew Waterhouse and JBP documented.
662 public ArgsParser(String[] args)
664 vargs = new Vector();
665 for (int i = 0; i < args.length; i++)
667 String arg = args[i].trim();
668 if (arg.charAt(0) == '-')
670 arg = arg.substring(1);
672 vargs.addElement(arg);
677 * check for and remove first occurence of arg+parameter in arglist.
680 * @return return the argument following the given arg if arg was in list.
682 public String getValue(String arg)
684 int index = vargs.indexOf(arg);
688 ret = vargs.elementAt(index + 1).toString();
689 vargs.removeElementAt(index);
690 vargs.removeElementAt(index);
696 * check for and remove first occurence of arg in arglist.
699 * @return true if arg was present in argslist.
701 public boolean contains(String arg)
703 if (vargs.contains(arg))
705 vargs.removeElement(arg);
714 public String nextValue()
716 return vargs.remove(0).toString();