2 * Jalview - A Sequence Alignment Editor and Viewer
3 * Copyright (C) 2007 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;
33 import jalview.io.AppletFormatAdapter;
36 * Main class for Jalview Application <br>
38 * start with java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview
47 * main class for Jalview application
50 * open <em>filename</em>
52 public static void main(String[] args)
54 System.out.println("Java version: "
55 + System.getProperty("java.version"));
56 System.out.println(System.getProperty("os.arch") + " "
57 + System.getProperty("os.name") + " "
58 + System.getProperty("os.version"));
60 ArgsParser aparser = new ArgsParser(args);
61 boolean headless = false;
63 if (aparser.contains("help") || aparser.contains("h"))
66 .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
67 + "-nodisplay\tRun Jalview without User Interface.\n"
68 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
69 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
70 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
71 + "-features FILE\tUse the given file to mark features on the alignment.\n"
72 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
73 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
74 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
75 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
76 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
77 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
78 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
79 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
80 + "-png FILE\tCreate PNG image FILE from alignment.\n"
81 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
82 + "-eps FILE\tCreate EPS file FILE from alignment."
83 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires."
84 + "-noquestionnaire\tTurn off questionnaire check."
85 + "-dasserver nickname=URL\tAdd and enable a das server with given nickname (alphanumeric or underscores only) for retrieval of features for all alignments."
86 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them."
87 + "-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)"
88 + "\n\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
92 Cache.loadProperties(aparser.getValue("props")); // must do this before
95 if (aparser.contains("nodisplay"))
97 System.setProperty("java.awt.headless", "true");
99 if (System.getProperty("java.awt.headless") != null
100 && System.getProperty("java.awt.headless").equals("true"))
108 } catch (java.lang.NoClassDefFoundError error)
110 error.printStackTrace();
112 .println("\nEssential logging libraries not found."
113 + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
117 Desktop desktop = null;
121 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()
122 // UIManager.getCrossPlatformLookAndFeelClassName()
123 // "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"
124 // "javax.swing.plaf.metal.MetalLookAndFeel"
125 // "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"
126 // "com.sun.java.swing.plaf.motif.MotifLookAndFeel"
129 } catch (Exception ex)
134 desktop = new Desktop();
135 desktop.setVisible(true);
136 desktop.discoverer.start();
137 if (!aparser.contains("noquestionnaire"))
139 String url = aparser.getValue("questionnaire");
142 // Start the desktop questionnaire prompter with the specified
144 Cache.log.debug("Starting questionnaire url at " + url);
145 desktop.checkForQuestionnaire(url);
149 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
151 // Start the desktop questionnaire prompter with the specified
154 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
156 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
157 Cache.log.debug("Starting questionnaire with default url: "
159 desktop.checkForQuestionnaire(defurl);
166 String file = null, protocol = null, format = null, data = null;
167 jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
168 Vector getFeatures = null; // vector of das source nicknames to fetch features from
170 String groovyscript = null; // script to execute after all loading is completed one way or another
171 // extract groovy argument and execute if necessary
172 groovyscript = aparser.getValue("groovy");
173 file = aparser.getValue("open");
175 if (file == null && desktop == null)
177 System.out.println("No files to open!");
183 System.out.println("Opening file: " + file);
185 if (!file.startsWith("http://"))
187 if (!(new java.io.File(file)).exists())
189 System.out.println("Can't find " + file);
197 protocol = checkProtocol(file);
199 format = new jalview.io.IdentifyFile().Identify(file, protocol);
201 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
206 System.out.println("error");
210 data = aparser.getValue("colour");
213 data.replaceAll("%20", " ");
215 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
216 .getColour(af.getViewport().getAlignment(), data);
220 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
222 ucs.parseAppletParameter(data);
226 System.out.println("colour is " + data);
230 // Must maintain ability to use the groups flag
231 data = aparser.getValue("groups");
234 af.parseFeaturesFile(data, checkProtocol(data));
235 System.out.println("Added " + data);
237 data = aparser.getValue("features");
240 af.parseFeaturesFile(data, checkProtocol(data));
241 System.out.println("Added " + data);
244 data = aparser.getValue("annotations");
247 af.loadJalviewDataFile(data);
248 System.out.println("Added " + data);
250 data = aparser.getValue("tree");
253 jalview.io.NewickFile fin = null;
256 fin = new jalview.io.NewickFile(data, checkProtocol(data));
259 af.getViewport().setCurrentTree(
260 af.ShowNewickTree(fin, data).getTree());
261 System.out.println("Added tree " + data);
263 } catch (IOException ex)
265 System.err.println("Couldn't add tree " + data);
266 ex.printStackTrace(System.err);
269 getFeatures = checkDasArguments(aparser);
270 if (af != null && getFeatures!=null)
272 startFeatureFetching(getFeatures);
273 // need to block until fetching is complete.
274 while (af.operationInProgress())
276 // wait around until fetching is finished.
279 } catch (Exception e)
285 if (groovyscript!=null)
287 // Execute the groovy script after we've done all the rendering stuff
288 // and before any images or figures are generated.
289 if (jalview.bin.Cache.groovyJarsPresent())
291 System.out.println("Executing script "+groovyscript);
292 executeGroovyScript(groovyscript, desktop);
294 System.err.println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "+groovyscript);
298 String imageName = "unnamed.png";
299 while (aparser.getSize() > 1)
301 format = aparser.nextValue();
302 file = aparser.nextValue();
304 if (format.equalsIgnoreCase("png"))
306 af.createPNG(new java.io.File(file));
307 imageName = (new java.io.File(file)).getName();
308 System.out.println("Creating PNG image: " + file);
311 else if (format.equalsIgnoreCase("imgMap"))
313 af.createImageMap(new java.io.File(file), imageName);
314 System.out.println("Creating image map: " + file);
317 else if (format.equalsIgnoreCase("eps"))
319 System.out.println("Creating EPS file: " + file);
320 af.createEPS(new java.io.File(file));
324 if (af.saveAlignment(file, format))
326 System.out.println("Written alignment in " + format
327 + " format to " + file);
331 System.out.println("Error writing file " + file + " in " + format
337 while (aparser.getSize() > 0)
339 System.out.println("Unknown arg: " + aparser.nextValue());
342 AlignFrame startUpAlframe = null;
343 // We'll only open the default file if the desktop is visible.
345 // ////////////////////
346 if (!headless && file == null
347 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
349 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
350 "http://www.jalview.org/examples/exampleFile_2_3.jar");
354 if (file.indexOf("http:") > -1)
359 if (file.endsWith(".jar"))
365 format = new jalview.io.IdentifyFile().Identify(file, protocol);
368 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
370 getFeatures = checkDasArguments(aparser);
371 // extract groovy arguments before anything else.
373 // Once all loading is done. Retrieve features.
374 if (getFeatures!=null)
376 if (startUpAlframe!=null)
378 startFeatureFetching(getFeatures);
381 if (groovyscript!=null)
383 if (jalview.bin.Cache.groovyJarsPresent())
385 System.out.println("Executing script "+groovyscript);
386 executeGroovyScript(groovyscript, desktop);
388 System.err.println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "+groovyscript);
392 // Once all other stuff is done, execute any groovy scripts (in order)
395 * Locate the given string as a file and pass it to the groovy interpreter.
396 * @param groovyscript the script to execute
397 * @param jalviewContext the Jalview Desktop object passed in to the groovy binding as the 'Jalview' object.
399 private static void executeGroovyScript(String groovyscript, Object jalviewContext)
401 if (jalviewContext==null)
403 System.err.println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
406 if (groovyscript.trim().equals("STDIN"))
408 // read from stdin into a tempfile and execute it
410 sfile = File.createTempFile("jalview", "groovy");
411 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(new FileOutputStream(sfile)));
412 BufferedReader br = new BufferedReader(new java.io.InputStreamReader(System.in));
414 while ((line=br.readLine())!=null)
416 outfile.write(line+"\n");
422 } catch (Exception ex)
424 System.err.println("Failed to read from STDIN into tempfile "+((sfile==null) ? "(tempfile wasn't created)" : sfile.toString()));
425 ex.printStackTrace();
429 sfile = new File(groovyscript);
433 System.err.println("File '"+groovyscript+"' does not exist.");
436 if (!sfile.canRead())
438 System.err.println("File '"+groovyscript+"' cannot be read.");
441 if (sfile.length()<1)
443 System.err.println("File '"+groovyscript+"' is empty.");
446 boolean success = false;
448 /* The following code performs the GroovyScriptEngine invocation using reflection,
449 * and is equivalent to this fragment from the embedding groovy documentation on
452 import groovy.lang.Binding;
453 import groovy.util.GroovyScriptEngine;
455 String[] roots = new String[] { "/my/groovy/script/path" };
456 GroovyScriptEngine gse = new GroovyScriptEngine(roots);
457 Binding binding = new Binding();
458 binding.setVariable("input", "world");
459 gse.run("hello.groovy", binding);
462 ClassLoader cl = jalviewContext.getClass().getClassLoader();
463 Class gbindingc = cl.loadClass("groovy.lang.Binding");
464 Constructor gbcons = gbindingc.getConstructor(null);
465 Object gbinding = gbcons.newInstance(null);
466 java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable", new Class[] { String.class, Object.class} );
467 setvar.invoke(gbinding, new Object[] { "Jalview", jalviewContext});
468 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
469 Constructor gseccons = gsec.getConstructor(new Class[] { String[].class });
470 Object gse = gseccons.newInstance(new Object[] { new String[] { sfile.toURL().toString() } });
471 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]{ String.class, gbindingc });
472 run.invoke(gse, new Object[] { sfile.toURL().toString(), gbinding });
474 } catch (Exception e)
476 System.err.println("Exception Whilst trying to execute file "+sfile+" as a groovy script.");
477 e.printStackTrace(System.err);
480 if (success && groovyscript.equals("STDIN"))
482 // delete temp file that we made - but only if it was successfully executed
487 * Check commandline for any das server definitions or any fetchfrom switches
488 * @return vector of DAS source nicknames to retrieve from
490 private static Vector checkDasArguments(ArgsParser aparser)
494 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
495 while ((data = aparser.getValue("dasserver"))!=null)
497 String nickname = null;
499 int pos = data.indexOf('=');
502 nickname = data.substring(0, pos);
504 url = data.substring(pos + 1);
505 if (url != null && url.startsWith("http:"))
507 if (nickname == null)
511 if (locsources==null)
517 locsources=locsources+nickname+"|"+url;
519 .println("NOTE! dasserver parameter not yet really supported (got args of "
520 + nickname + "|" + url);
523 source = new Vector();
525 source.addElement(nickname);
527 } // loop until no more server entries are found.
528 if (locsources!=null && locsources.indexOf('|')>-1)
530 Cache.log.debug("Setting local source list in properties file to:\n"+locsources);
531 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
533 while ((data = aparser.getValue("fetchfrom"))!=null)
535 System.out.println("adding source '"+data+"'");
538 source = new Vector();
540 source.addElement(data);
545 * start a feature fetcher for every alignment frame
548 private static void startFeatureFetching(final Vector dasSources)
550 AlignFrame afs[] = Desktop.getAlignframes();
551 if (afs==null || afs.length==0)
555 for (int i = 0; i<afs.length; i++)
557 final AlignFrame af = afs[i];
558 SwingUtilities.invokeLater(new Runnable() {
562 af.featureSettings_actionPerformed(null);
563 af.featureSettings.fetchDasFeatures(dasSources);
569 private static String checkProtocol(String file)
571 String protocol = jalview.io.FormatAdapter.FILE;
573 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
575 protocol = jalview.io.FormatAdapter.URL;
582 * Notes: this argParser does not distinguish between parameter switches,
583 * parameter values and argument text. If an argument happens to be identical
584 * to a parameter, it will be taken as such (even though it didn't have a '-' prefixing it).
586 * @author Andrew Waterhouse and JBP documented.
593 public ArgsParser(String[] args)
595 vargs = new Vector();
596 for (int i = 0; i < args.length; i++)
598 String arg = args[i].trim();
599 if (arg.charAt(0) == '-')
601 arg = arg.substring(1);
603 vargs.addElement(arg);
607 * check for and remove first occurence of arg+parameter in arglist.
609 * @return return the argument following the given arg if arg was in list.
611 public String getValue(String arg)
613 int index = vargs.indexOf(arg);
617 ret = vargs.elementAt(index + 1).toString();
618 vargs.removeElementAt(index);
619 vargs.removeElementAt(index);
624 * check for and remove first occurence of arg in arglist.
626 * @return true if arg was present in argslist.
628 public boolean contains(String arg)
630 if (vargs.contains(arg))
632 vargs.removeElement(arg);
641 public String nextValue()
643 return vargs.remove(0).toString();