2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
20 import java.io.BufferedReader;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStreamWriter;
25 import java.io.PrintWriter;
26 import java.lang.reflect.Constructor;
28 import java.net.URLDecoder;
29 import java.security.AllPermission;
30 import java.security.CodeSource;
31 import java.security.PermissionCollection;
32 import java.security.Permissions;
33 import java.security.Policy;
39 import jalview.io.FileParse;
40 import jalview.util.Platform;
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"));
83 if (new Platform().isAMac())
85 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
87 System.setProperty("apple.laf.useScreenMenuBar", "true");
90 ArgsParser aparser = new ArgsParser(args);
91 boolean headless = false;
93 if (aparser.contains("help") || aparser.contains("h"))
96 .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
97 + "-nodisplay\tRun Jalview without User Interface.\n"
98 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
99 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
100 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
101 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
102 + "-features FILE\tUse the given file to mark features on the alignment.\n"
103 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
104 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
105 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
106 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
107 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
108 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
109 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
110 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
111 + "-png FILE\tCreate PNG image FILE from alignment.\n"
112 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
113 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
114 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
115 + "-noquestionnaire\tTurn off questionnaire check.\n"
116 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
117 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
119 // "-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)"
120 + "-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"
121 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
122 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
123 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
125 // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
126 // + "-vses vamsas-session\tJoin session with given URN\n"
127 + "-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"
128 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
131 Cache.loadProperties(aparser.getValue("props")); // must do this before
133 String defs = aparser.getValue("setprop");
136 int p = defs.indexOf('=');
139 System.err.println("Ignoring invalid setprop argument : " + defs);
143 System.out.println("Executing setprop argument: " + defs);
144 // DISABLED FOR SECURITY REASONS
145 // TODO: add a property to allow properties to be overriden by cli args
146 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
148 defs = aparser.getValue("setprop");
150 if (aparser.contains("nodisplay"))
152 System.setProperty("java.awt.headless", "true");
154 if (System.getProperty("java.awt.headless") != null
155 && System.getProperty("java.awt.headless").equals("true"))
163 } catch (java.lang.NoClassDefFoundError error)
165 error.printStackTrace();
167 .println("\nEssential logging libraries not found."
168 + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
172 Desktop desktop = null;
176 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
177 } catch (Exception ex)
183 desktop = new Desktop();
184 desktop.setInBatchMode(true); // indicate we are starting up
185 desktop.setVisible(true);
186 desktop.startServiceDiscovery();
187 if (!aparser.contains("nousagestats"))
189 startUsageStats(desktop);
191 if (!aparser.contains("noquestionnaire"))
193 String url = aparser.getValue("questionnaire");
196 // Start the desktop questionnaire prompter with the specified
198 Cache.log.debug("Starting questionnaire url at " + url);
199 desktop.checkForQuestionnaire(url);
203 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
205 // Start the desktop questionnaire prompter with the specified
208 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
210 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
211 Cache.log.debug("Starting questionnaire with default url: "
213 desktop.checkForQuestionnaire(defurl);
220 String file = null, protocol = null, format = null, data = null;
221 jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
222 Vector getFeatures = null; // vector of das source nicknames to fetch
225 String groovyscript = null; // script to execute after all loading is
226 // completed one way or another
227 // extract groovy argument and execute if necessary
228 groovyscript = aparser.getValue("groovy", true);
229 file = aparser.getValue("open", true);
231 if (file == null && desktop == null)
233 System.out.println("No files to open!");
236 String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
238 if (vamsasImport != null || vamsasSession != null)
240 if (desktop == null || headless)
243 .println("Headless vamsas sessions not yet supported. Sorry.");
246 // if we have a file, start a new session and import it.
247 boolean inSession = false;
248 if (vamsasImport != null)
252 String viprotocol = FileParse.checkProtocol(vamsasImport);
253 if (viprotocol == jalview.io.FormatAdapter.FILE)
255 inSession = desktop.vamsasImport(new File(vamsasImport));
257 else if (viprotocol == jalview.io.FormatAdapter.URL)
259 inSession = desktop.vamsasImport(new URL(vamsasImport));
262 } catch (Exception e)
264 System.err.println("Exeption when importing " + vamsasImport
265 + " as a vamsas document.");
270 System.err.println("Failed to import " + vamsasImport
271 + " as a vamsas document.");
275 System.out.println("Imported Successfully into new session "
276 + desktop.getVamsasApplication().getCurrentSession());
279 if (vamsasSession != null)
281 if (vamsasImport != null)
283 // close the newly imported session and import the Jalview specific
284 // remnants into the new session later on.
285 desktop.vamsasStop_actionPerformed(null);
287 // now join the new session
290 if (desktop.joinVamsasSession(vamsasSession))
292 System.out.println("Successfully joined vamsas session "
297 System.err.println("WARNING: Failed to join vamsas session "
300 } catch (Exception e)
302 System.err.println("ERROR: Failed to join vamsas session "
306 if (vamsasImport != null)
308 // the Jalview specific remnants can now be imported into the new
309 // session at the user's leisure.
311 .info("Skipping Push for import of data into existing vamsas session."); // TODO:
316 // desktop.getVamsasApplication().push_update();
320 // Finally, deal with the remaining input data.
323 System.out.println("Opening file: " + file);
325 if (!file.startsWith("http://"))
327 if (!(new java.io.File(file)).exists())
329 System.out.println("Can't find " + file);
337 protocol = FileParse.checkProtocol(file);
339 format = new jalview.io.IdentifyFile().Identify(file, protocol);
341 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
345 System.out.println("error");
349 data = aparser.getValue("colour", true);
352 data.replaceAll("%20", " ");
354 jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
355 .getColour(af.getViewport().getAlignment(), data);
359 jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
361 ucs.parseAppletParameter(data);
365 System.out.println("colour is " + data);
369 // Must maintain ability to use the groups flag
370 data = aparser.getValue("groups", true);
373 af.parseFeaturesFile(data, FileParse.checkProtocol(data));
374 System.out.println("Added " + data);
376 data = aparser.getValue("features", true);
379 af.parseFeaturesFile(data, FileParse.checkProtocol(data));
380 System.out.println("Added " + data);
383 data = aparser.getValue("annotations", true);
386 af.loadJalviewDataFile(data);
387 System.out.println("Added " + data);
389 // set or clear the sortbytree flag.
390 if (aparser.contains("sortbytree"))
392 af.getViewport().setSortByTree(true);
394 if (aparser.contains("nosortbytree"))
396 af.getViewport().setSortByTree(false);
398 data = aparser.getValue("tree", true);
401 jalview.io.NewickFile fin = null;
404 fin = new jalview.io.NewickFile(data, FileParse.checkProtocol(data));
407 af.getViewport().setCurrentTree(
408 af.ShowNewickTree(fin, data).getTree());
409 System.out.println("Added tree " + data);
411 } catch (IOException ex)
413 System.err.println("Couldn't add tree " + data);
414 ex.printStackTrace(System.err);
417 // TODO - load PDB structure(s) to alignment JAL-629
418 // (associate with identical sequence in alignment, or a specified
421 getFeatures = checkDasArguments(aparser);
422 if (af != null && getFeatures != null)
424 FeatureFetcher ff = startFeatureFetching(getFeatures);
426 while (!ff.allFinished() || af.operationInProgress())
428 // wait around until fetching is finished.
432 } catch (Exception e)
437 getFeatures = null; // have retrieved features - forget them now.
439 if (groovyscript != null)
441 // Execute the groovy script after we've done all the rendering stuff
442 // and before any images or figures are generated.
443 if (jalview.bin.Cache.groovyJarsPresent())
445 System.out.println("Executing script " + groovyscript);
446 executeGroovyScript(groovyscript, desktop);
451 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
456 String imageName = "unnamed.png";
457 while (aparser.getSize() > 1)
459 format = aparser.nextValue();
460 file = aparser.nextValue();
462 if (format.equalsIgnoreCase("png"))
464 af.createPNG(new java.io.File(file));
465 imageName = (new java.io.File(file)).getName();
466 System.out.println("Creating PNG image: " + file);
469 else if (format.equalsIgnoreCase("imgMap"))
471 af.createImageMap(new java.io.File(file), imageName);
472 System.out.println("Creating image map: " + file);
475 else if (format.equalsIgnoreCase("eps"))
477 System.out.println("Creating EPS file: " + file);
478 af.createEPS(new java.io.File(file));
482 if (af.saveAlignment(file, format))
484 System.out.println("Written alignment in " + format
485 + " format to " + file);
489 System.out.println("Error writing file " + file + " in " + format
495 while (aparser.getSize() > 0)
497 System.out.println("Unknown arg: " + aparser.nextValue());
500 AlignFrame startUpAlframe = null;
501 // We'll only open the default file if the desktop is visible.
503 // ////////////////////
504 if (!headless && file == null && vamsasImport == null
505 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
507 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
508 "http://www.jalview.org/examples/exampleFile_2_3.jar");
512 if (file.indexOf("http:") > -1)
517 if (file.endsWith(".jar"))
523 format = new jalview.io.IdentifyFile().Identify(file, protocol);
526 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
528 getFeatures = checkDasArguments(aparser);
529 // extract groovy arguments before anything else.
531 // If the user has specified features to be retrieved,
532 // or a groovy script to be executed, do them if they
533 // haven't been done already
534 // fetch features for the default alignment
535 if (getFeatures != null)
537 if (startUpAlframe != null)
539 startFeatureFetching(getFeatures);
542 // Once all other stuff is done, execute any groovy scripts (in order)
543 if (groovyscript != null)
545 if (jalview.bin.Cache.groovyJarsPresent())
547 System.out.println("Executing script " + groovyscript);
548 executeGroovyScript(groovyscript, desktop);
553 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
557 // and finally, turn off batch mode indicator - if the desktop still exists
560 desktop.setInBatchMode(false);
564 private static void startUsageStats(final Desktop desktop)
567 * start a User Config prompt asking if we can log usage statistics.
569 jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
572 "Jalview Usage Statistics",
573 "Do you want to help make Jalview better by enabling "
574 + "the collection of usage statistics with Google Analytics ?"
575 + "\n\n(you can enable or disable usage tracking in the preferences)",
581 .info("Initialising googletracker for usage stats.");
582 Cache.initGoogleTracker();
583 Cache.log.debug("Tracking enabled.");
589 Cache.log.info("Not enabling Google Tracking.");
592 SwingUtilities.invokeLater(prompter);
596 * Locate the given string as a file and pass it to the groovy interpreter.
598 * @param groovyscript
599 * the script to execute
600 * @param jalviewContext
601 * the Jalview Desktop object passed in to the groovy binding as the
604 private static void executeGroovyScript(String groovyscript,
605 Object jalviewContext)
607 if (jalviewContext == null)
610 .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
613 if (groovyscript.trim().equals("STDIN"))
615 // read from stdin into a tempfile and execute it
618 sfile = File.createTempFile("jalview", "groovy");
619 PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
620 new FileOutputStream(sfile)));
621 BufferedReader br = new BufferedReader(
622 new java.io.InputStreamReader(System.in));
624 while ((line = br.readLine()) != null)
626 outfile.write(line + "\n");
632 } catch (Exception ex)
634 System.err.println("Failed to read from STDIN into tempfile "
635 + ((sfile == null) ? "(tempfile wasn't created)" : sfile
637 ex.printStackTrace();
643 sfile = new File(groovyscript);
647 System.err.println("File '" + groovyscript + "' does not exist.");
650 if (!sfile.canRead())
652 System.err.println("File '" + groovyscript + "' cannot be read.");
655 if (sfile.length() < 1)
657 System.err.println("File '" + groovyscript + "' is empty.");
660 boolean success = false;
664 * The following code performs the GroovyScriptEngine invocation using
665 * reflection, and is equivalent to this fragment from the embedding
666 * groovy documentation on the groovy site: <code> import
667 * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
669 * String[] roots = new String[] { "/my/groovy/script/path" };
670 * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
671 * = new Binding(); binding.setVariable("input", "world");
672 * gse.run("hello.groovy", binding); </code>
674 ClassLoader cl = jalviewContext.getClass().getClassLoader();
675 Class gbindingc = cl.loadClass("groovy.lang.Binding");
676 Constructor gbcons = gbindingc.getConstructor(null);
677 Object gbinding = gbcons.newInstance(null);
678 java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
680 { String.class, Object.class });
681 setvar.invoke(gbinding, new Object[]
682 { "Jalview", jalviewContext });
683 Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
684 Constructor gseccons = gsec.getConstructor(new Class[]
685 { URL[].class }); // String[].class });
686 Object gse = gseccons.newInstance(new Object[]
688 { sfile.toURL() } }); // .toString() } });
689 java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
690 { String.class, gbindingc });
691 run.invoke(gse, new Object[]
692 { sfile.getName(), gbinding });
694 } catch (Exception e)
696 System.err.println("Exception Whilst trying to execute file " + sfile
697 + " as a groovy script.");
698 e.printStackTrace(System.err);
701 if (success && groovyscript.equals("STDIN"))
703 // delete temp file that we made - but only if it was successfully
710 * Check commandline for any das server definitions or any fetchfrom switches
712 * @return vector of DAS source nicknames to retrieve from
714 private static Vector checkDasArguments(ArgsParser aparser)
716 Vector source = null;
718 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
719 while ((data = aparser.getValue("dasserver", true)) != null)
721 String nickname = null;
723 boolean seq = false, feat = true;
724 int pos = data.indexOf('=');
725 // determine capabilities
728 nickname = data.substring(0, pos);
730 url = data.substring(pos + 1);
732 && (url.startsWith("http:") || url
733 .startsWith("sequence:http:")))
735 if (nickname == null)
739 if (locsources == null)
747 locsources = locsources + nickname + "|" + url;
749 .println("NOTE! dasserver parameter not yet really supported (got args of "
750 + nickname + "|" + url);
753 source = new Vector();
755 source.addElement(nickname);
757 } // loop until no more server entries are found.
758 if (locsources != null && locsources.indexOf('|') > -1)
760 Cache.log.debug("Setting local source list in properties file to:\n"
762 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
764 while ((data = aparser.getValue("fetchfrom", true)) != null)
766 System.out.println("adding source '" + data + "'");
769 source = new Vector();
771 source.addElement(data);
777 * start a feature fetcher for every alignment frame
781 private static FeatureFetcher startFeatureFetching(final Vector dasSources)
783 FeatureFetcher ff = new FeatureFetcher();
784 AlignFrame afs[] = Desktop.getAlignframes();
785 if (afs == null || afs.length == 0)
789 for (int i = 0; i < afs.length; i++)
791 ff.addFetcher(afs[i], dasSources);
798 * Notes: this argParser does not distinguish between parameter switches,
799 * parameter values and argument text. If an argument happens to be identical to
800 * a parameter, it will be taken as such (even though it didn't have a '-'
803 * @author Andrew Waterhouse and JBP documented.
810 public ArgsParser(String[] args)
812 vargs = new Vector();
813 for (int i = 0; i < args.length; i++)
815 String arg = args[i].trim();
816 if (arg.charAt(0) == '-')
818 arg = arg.substring(1);
820 vargs.addElement(arg);
825 * check for and remove first occurence of arg+parameter in arglist.
828 * @return return the argument following the given arg if arg was in list.
830 public String getValue(String arg)
832 return getValue(arg, false);
835 public String getValue(String arg, boolean utf8decode)
837 int index = vargs.indexOf(arg);
838 String dc = null, ret = null;
841 ret = vargs.elementAt(index + 1).toString();
842 vargs.removeElementAt(index);
843 vargs.removeElementAt(index);
844 if (utf8decode && ret != null)
848 dc = URLDecoder.decode(ret, "UTF-8");
850 } catch (Exception e)
852 // TODO: log failure to decode
860 * check for and remove first occurence of arg in arglist.
863 * @return true if arg was present in argslist.
865 public boolean contains(String arg)
867 if (vargs.contains(arg))
869 vargs.removeElement(arg);
878 public String nextValue()
880 return vargs.remove(0).toString();
891 * keep track of feature fetching tasks.
899 * TODO: generalise to track all jalview events to orchestrate batch
903 private int queued = 0;
905 private int running = 0;
907 public FeatureFetcher()
912 public void addFetcher(final AlignFrame af, final Vector dasSources)
914 final long id = System.currentTimeMillis();
916 final FeatureFetcher us = this;
917 new Thread(new Runnable()
928 af.setProgressBar("DAS features being retrieved...", id);
929 af.featureSettings_actionPerformed(null);
930 af.featureSettings.fetchDasFeatures(dasSources, true);
931 af.setProgressBar(null, id);
940 public synchronized boolean allFinished()
942 return queued == 0 && running == 0;