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.net.URLDecoder;
30 import java.security.AllPermission;
31 import java.security.CodeSource;
32 import java.security.PermissionCollection;
33 import java.security.Permissions;
34 import java.security.Policy;
40 import jalview.io.AppletFormatAdapter;
43 * Main class for Jalview Application <br>
45 * start with java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview
54 // grab all the rights we can the JVM
55 Policy.setPolicy(new Policy()
57 public PermissionCollection getPermissions(CodeSource codesource)
59 Permissions perms = new Permissions();
60 perms.add(new AllPermission());
71 * main class for Jalview application
74 * open <em>filename</em>
76 public static void main(String[] args)
78 System.out.println("Java version: "
79 + System.getProperty("java.version"));
80 System.out.println(System.getProperty("os.arch") + " "
81 + System.getProperty("os.name") + " "
82 + System.getProperty("os.version"));
84 ArgsParser aparser = new ArgsParser(args);
85 boolean headless = false;
87 if (aparser.contains("help") || aparser.contains("h"))
90 .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
91 + "-nodisplay\tRun Jalview without User Interface.\n"
92 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
93 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
94 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
95 + "-features FILE\tUse the given file to mark features on the alignment.\n"
96 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
97 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
98 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
99 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
100 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
101 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
102 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
103 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
104 + "-png FILE\tCreate PNG image FILE from alignment.\n"
105 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
106 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
107 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
108 + "-noquestionnaire\tTurn off questionnaire check.\n"
109 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
110 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
112 // "-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)"
113 + "-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"
114 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
115 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
116 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
118 // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
119 // + "-vses vamsas-session\tJoin session with given URN\n"
120 + "-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"
121 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
124 Cache.loadProperties(aparser.getValue("props")); // must do this before
126 String defs = aparser.getValue("setprop");
129 int p = defs.indexOf('=');
132 System.err.println("Ignoring invalid setprop argument : " + defs);
136 System.out.println("Executing setprop argument: " + defs);
137 // DISABLED FOR SECURITY REASONS
138 // TODO: add a property to allow properties to be overriden by cli args
139 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
141 defs = aparser.getValue("setprop");
143 if (aparser.contains("nodisplay"))
145 System.setProperty("java.awt.headless", "true");
147 if (System.getProperty("java.awt.headless") != null
148 && System.getProperty("java.awt.headless").equals("true"))
156 } catch (java.lang.NoClassDefFoundError error)
158 error.printStackTrace();
160 .println("\nEssential logging libraries not found."
161 + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
165 Desktop desktop = null;
169 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()
170 // UIManager.getCrossPlatformLookAndFeelClassName()
171 // "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"
172 // "javax.swing.plaf.metal.MetalLookAndFeel"
173 // "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"
174 // "com.sun.java.swing.plaf.motif.MotifLookAndFeel"
177 } catch (Exception ex)
182 desktop = new Desktop();
183 desktop.setVisible(true);
184 desktop.discoverer.start();
185 if (!aparser.contains("nousagestats"))
187 startUsageStats(desktop);
189 if (!aparser.contains("noquestionnaire"))
191 String url = aparser.getValue("questionnaire");
194 // Start the desktop questionnaire prompter with the specified
196 Cache.log.debug("Starting questionnaire url at " + url);
197 desktop.checkForQuestionnaire(url);
201 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
203 // Start the desktop questionnaire prompter with the specified
206 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
208 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
209 Cache.log.debug("Starting questionnaire with default url: "
211 desktop.checkForQuestionnaire(defurl);
218 String file = null, protocol = null, format = null, data = null;
219 jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
220 Vector getFeatures = null; // vector of das source nicknames to fetch
223 String groovyscript = null; // script to execute after all loading is
224 // completed one way or another
225 // extract groovy argument and execute if necessary
226 groovyscript = aparser.getValue("groovy",true);
227 file = aparser.getValue("open",true);
229 if (file == null && desktop == null)
231 System.out.println("No files to open!");
234 String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
236 if (vamsasImport != null || vamsasSession != null)
238 if (desktop == null || headless)
241 .println("Headless vamsas sessions not yet supported. Sorry.");
244 // if we have a file, start a new session and import it.
245 boolean inSession = false;
246 if (vamsasImport != null)
250 String viprotocol = Jalview.checkProtocol(vamsasImport);
251 if (viprotocol == jalview.io.FormatAdapter.FILE)
253 inSession = desktop.vamsasImport(new File(vamsasImport));
255 else if (viprotocol == jalview.io.FormatAdapter.URL)
257 inSession = desktop.vamsasImport(new URL(vamsasImport));
260 } catch (Exception e)
262 System.err.println("Exeption when importing " + vamsasImport
263 + " as a vamsas document.");
268 System.err.println("Failed to import " + vamsasImport
269 + " as a vamsas document.");
273 System.out.println("Imported Successfully into new session "
274 + desktop.getVamsasApplication().getCurrentSession());
277 if (vamsasSession != null)
279 if (vamsasImport != null)
281 // close the newly imported session and import the Jalview specific
282 // remnants into the new session later on.
283 desktop.vamsasStop_actionPerformed(null);
285 // now join the new session
288 if (desktop.joinVamsasSession(vamsasSession))
290 System.out.println("Successfully joined vamsas session "
295 System.err.println("WARNING: Failed to join vamsas session "
298 } catch (Exception e)
300 System.err.println("ERROR: Failed to join vamsas session "
304 if (vamsasImport != null)
306 // the Jalview specific remnants can now be imported into the new
307 // session at the user's leisure.
309 .info("Skipping Push for import of data into existing vamsas session."); // TODO:
314 // desktop.getVamsasApplication().push_update();
318 // Finally, deal with the remaining input data.
321 System.out.println("Opening file: " + file);
323 if (!file.startsWith("http://"))
325 if (!(new java.io.File(file)).exists())
327 System.out.println("Can't find " + file);
335 protocol = checkProtocol(file);
337 format = new jalview.io.IdentifyFile().Identify(file, protocol);
339 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
343 System.out.println("error");
347 data = aparser.getValue("colour",true);
350 data.replaceAll("%20", " ");
352 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
353 .getColour(af.getViewport().getAlignment(), data);
357 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
359 ucs.parseAppletParameter(data);
363 System.out.println("colour is " + data);
367 // Must maintain ability to use the groups flag
368 data = aparser.getValue("groups",true);
371 af.parseFeaturesFile(data, checkProtocol(data));
372 System.out.println("Added " + data);
374 data = aparser.getValue("features",true);
377 af.parseFeaturesFile(data, checkProtocol(data));
378 System.out.println("Added " + data);
381 data = aparser.getValue("annotations",true);
384 af.loadJalviewDataFile(data);
385 System.out.println("Added " + data);
387 // set or clear the sortbytree flag.
388 if (aparser.contains("sortbytree"))
390 af.getViewport().setSortByTree(true);
392 if (aparser.contains("nosortbytree"))
394 af.getViewport().setSortByTree(false);
396 data = aparser.getValue("tree",true);
399 jalview.io.NewickFile fin = null;
402 fin = new jalview.io.NewickFile(data, checkProtocol(data));
405 af.getViewport().setCurrentTree(
406 af.ShowNewickTree(fin, data).getTree());
407 System.out.println("Added tree " + data);
409 } catch (IOException ex)
411 System.err.println("Couldn't add tree " + data);
412 ex.printStackTrace(System.err);
415 // todo - load PDB structure to alignment
416 // (associate with identical sequence in alignment, or a specified sequence)
419 getFeatures = checkDasArguments(aparser);
420 if (af != null && getFeatures != null)
422 FeatureFetcher ff = startFeatureFetching(getFeatures);
424 while (!ff.allFinished() || af.operationInProgress())
426 // wait around until fetching is finished.
430 } catch (Exception e)
435 getFeatures = null; // have retrieved features - forget them now.
437 if (groovyscript != null)
439 // Execute the groovy script after we've done all the rendering stuff
440 // and before any images or figures are generated.
441 if (jalview.bin.Cache.groovyJarsPresent())
443 System.out.println("Executing script " + groovyscript);
444 executeGroovyScript(groovyscript, desktop);
449 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
454 String imageName = "unnamed.png";
455 while (aparser.getSize() > 1)
457 format = aparser.nextValue();
458 file = aparser.nextValue();
460 if (format.equalsIgnoreCase("png"))
462 af.createPNG(new java.io.File(file));
463 imageName = (new java.io.File(file)).getName();
464 System.out.println("Creating PNG image: " + file);
467 else if (format.equalsIgnoreCase("imgMap"))
469 af.createImageMap(new java.io.File(file), imageName);
470 System.out.println("Creating image map: " + file);
473 else if (format.equalsIgnoreCase("eps"))
475 System.out.println("Creating EPS file: " + file);
476 af.createEPS(new java.io.File(file));
480 if (af.saveAlignment(file, format))
482 System.out.println("Written alignment in " + format
483 + " format to " + file);
487 System.out.println("Error writing file " + file + " in " + format
493 while (aparser.getSize() > 0)
495 System.out.println("Unknown arg: " + aparser.nextValue());
498 AlignFrame startUpAlframe = null;
499 // We'll only open the default file if the desktop is visible.
501 // ////////////////////
502 if (!headless && file == null && vamsasImport == null
503 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
505 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
506 "http://www.jalview.org/examples/exampleFile_2_3.jar");
510 if (file.indexOf("http:") > -1)
515 if (file.endsWith(".jar"))
521 format = new jalview.io.IdentifyFile().Identify(file, protocol);
524 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
526 getFeatures = checkDasArguments(aparser);
527 // extract groovy arguments before anything else.
529 // If the user has specified features to be retrieved,
530 // or a groovy script to be executed, do them if they
531 // haven't been done already
532 // fetch features for the default alignment
533 if (getFeatures != null)
535 if (startUpAlframe != null)
537 startFeatureFetching(getFeatures);
540 // execute a groovy script.
541 if (groovyscript != null)
543 if (jalview.bin.Cache.groovyJarsPresent())
545 System.out.println("Executing script " + groovyscript);
546 executeGroovyScript(groovyscript, desktop);
551 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
556 // Once all other stuff is done, execute any groovy scripts (in order)
559 private static void startUsageStats(final Desktop desktop)
562 * start a User Config prompt asking if we can log usage statistics.
564 jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
567 "Jalview Usage Statistics",
568 "Do you want to help make Jalview better by enabling "
569 +"the collection of usage statistics with Google Analytics ?"
570 +"\n\n(you can enable or disable usage tracking in the preferences)",
576 .info("Initialising googletracker for usage stats.");
577 Cache.initGoogleTracker();
578 Cache.log.debug("Tracking enabled.");
584 Cache.log.info("Not enabling Google Tracking.");
587 SwingUtilities.invokeLater(prompter);
591 * Locate the given string as a file and pass it to the groovy interpreter.
593 * @param groovyscript
594 * the script to execute
595 * @param jalviewContext
596 * the Jalview Desktop object passed in to the groovy binding as the
599 private static void executeGroovyScript(String groovyscript,
600 Object jalviewContext)
602 if (jalviewContext == null)
605 .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
608 if (groovyscript.trim().equals("STDIN"))
610 // read from stdin into a tempfile and execute it
613 sfile = File.createTempFile("jalview", "groovy");
614 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
615 new FileOutputStream(sfile)));
616 BufferedReader br = new BufferedReader(
617 new java.io.InputStreamReader(System.in));
619 while ((line = br.readLine()) != null)
621 outfile.write(line + "\n");
627 } catch (Exception ex)
629 System.err.println("Failed to read from STDIN into tempfile "
630 + ((sfile == null) ? "(tempfile wasn't created)" : sfile
632 ex.printStackTrace();
638 sfile = new File(groovyscript);
642 System.err.println("File '" + groovyscript + "' does not exist.");
645 if (!sfile.canRead())
647 System.err.println("File '" + groovyscript + "' cannot be read.");
650 if (sfile.length() < 1)
652 System.err.println("File '" + groovyscript + "' is empty.");
655 boolean success = false;
659 * The following code performs the GroovyScriptEngine invocation using
660 * reflection, and is equivalent to this fragment from the embedding
661 * groovy documentation on the groovy site: <code> import
662 * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
664 * String[] roots = new String[] { "/my/groovy/script/path" };
665 * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
666 * = new Binding(); binding.setVariable("input", "world");
667 * gse.run("hello.groovy", binding); </code>
669 ClassLoader cl = jalviewContext.getClass().getClassLoader();
670 Class gbindingc = cl.loadClass("groovy.lang.Binding");
671 Constructor gbcons = gbindingc.getConstructor(null);
672 Object gbinding = gbcons.newInstance(null);
673 java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
675 { String.class, Object.class });
676 setvar.invoke(gbinding, new Object[]
677 { "Jalview", jalviewContext });
678 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
679 Constructor gseccons = gsec.getConstructor(new Class[]
680 { URL[].class }); // String[].class });
681 Object gse = gseccons.newInstance(new Object[]
683 { sfile.toURL() } }); // .toString() } });
684 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
685 { String.class, gbindingc });
686 run.invoke(gse, new Object[]
687 { sfile.getName(), gbinding });
689 } catch (Exception e)
691 System.err.println("Exception Whilst trying to execute file " + sfile
692 + " as a groovy script.");
693 e.printStackTrace(System.err);
696 if (success && groovyscript.equals("STDIN"))
698 // delete temp file that we made - but only if it was successfully
705 * Check commandline for any das server definitions or any fetchfrom switches
707 * @return vector of DAS source nicknames to retrieve from
709 private static Vector checkDasArguments(ArgsParser aparser)
711 Vector source = null;
713 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
714 while ((data = aparser.getValue("dasserver",true)) != null)
716 String nickname = null;
718 boolean seq = false, feat = true;
719 int pos = data.indexOf('=');
720 // determine capabilities
723 nickname = data.substring(0, pos);
725 url = data.substring(pos + 1);
727 && (url.startsWith("http:") || url
728 .startsWith("sequence:http:")))
730 if (nickname == null)
734 if (locsources == null)
742 locsources = locsources + nickname + "|" + url;
744 .println("NOTE! dasserver parameter not yet really supported (got args of "
745 + nickname + "|" + url);
748 source = new Vector();
750 source.addElement(nickname);
752 } // loop until no more server entries are found.
753 if (locsources != null && locsources.indexOf('|') > -1)
755 Cache.log.debug("Setting local source list in properties file to:\n"
757 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
759 while ((data = aparser.getValue("fetchfrom",true)) != null)
761 System.out.println("adding source '" + data + "'");
764 source = new Vector();
766 source.addElement(data);
772 * start a feature fetcher for every alignment frame
776 private static FeatureFetcher startFeatureFetching(final Vector dasSources)
778 FeatureFetcher ff = new FeatureFetcher();
779 AlignFrame afs[] = Desktop.getAlignframes();
780 if (afs == null || afs.length == 0)
784 for (int i = 0; i < afs.length; i++)
786 ff.addFetcher(afs[i], dasSources);
790 private static String checkProtocol(String file)
792 String protocol = jalview.io.FormatAdapter.FILE;
794 if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
796 protocol = jalview.io.FormatAdapter.URL;
803 * Notes: this argParser does not distinguish between parameter switches,
804 * parameter values and argument text. If an argument happens to be identical to
805 * a parameter, it will be taken as such (even though it didn't have a '-'
808 * @author Andrew Waterhouse and JBP documented.
815 public ArgsParser(String[] args)
817 vargs = new Vector();
818 for (int i = 0; i < args.length; i++)
820 String arg = args[i].trim();
821 if (arg.charAt(0) == '-')
823 arg = arg.substring(1);
825 vargs.addElement(arg);
830 * check for and remove first occurence of arg+parameter in arglist.
833 * @return return the argument following the given arg if arg was in list.
835 public String getValue(String arg)
837 return getValue(arg, false);
839 public String getValue(String arg, boolean utf8decode)
841 int index = vargs.indexOf(arg);
842 String dc=null,ret = null;
845 ret = vargs.elementAt(index + 1).toString();
846 vargs.removeElementAt(index);
847 vargs.removeElementAt(index);
848 if (utf8decode && ret!=null)
851 dc = URLDecoder.decode(ret,"UTF-8");
853 } catch (Exception e)
855 // TODO: log failure to decode
863 * check for and remove first occurence of arg in arglist.
866 * @return true if arg was present in argslist.
868 public boolean contains(String arg)
870 if (vargs.contains(arg))
872 vargs.removeElement(arg);
881 public String nextValue()
883 return vargs.remove(0).toString();
893 * keep track of feature fetching tasks.
897 class FeatureFetcher {
899 * TODO: generalise to track all jalview events to orchestrate batch processing events.
902 private int queued=0;
903 private int running=0;
904 public FeatureFetcher()
908 public void addFetcher(final AlignFrame af, final Vector dasSources)
910 final long id = System.currentTimeMillis();
912 final FeatureFetcher us=this;
913 new Thread(new Runnable()
923 af.setProgressBar("DAS features being retrieved...", id);
924 af.featureSettings_actionPerformed(null);
925 af.featureSettings.fetchDasFeatures(dasSources, true);
926 af.setProgressBar(null, id);
933 public synchronized boolean allFinished() {
934 return queued==0 && running==0;