2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.ext.so.SequenceOntology;
24 import jalview.gui.AlignFrame;
25 import jalview.gui.Desktop;
26 import jalview.gui.PromptUserConfig;
27 import jalview.io.AppletFormatAdapter;
28 import jalview.io.BioJsHTMLOutput;
29 import jalview.io.DataSourceType;
30 import jalview.io.FileFormat;
31 import jalview.io.FileFormatException;
32 import jalview.io.FileFormatI;
33 import jalview.io.FileLoader;
34 import jalview.io.HtmlSvgOutput;
35 import jalview.io.IdentifyFile;
36 import jalview.io.NewickFile;
37 import jalview.io.gff.SequenceOntologyFactory;
38 import jalview.schemes.ColourSchemeI;
39 import jalview.schemes.ColourSchemeProperty;
40 import jalview.util.MessageManager;
41 import jalview.util.Platform;
42 import jalview.ws.jws2.Jws2Discoverer;
44 import java.awt.event.ActionEvent;
45 import java.awt.event.ActionListener;
46 import java.io.BufferedReader;
48 import java.io.FileOutputStream;
49 import java.io.IOException;
50 import java.io.InputStreamReader;
51 import java.io.OutputStreamWriter;
52 import java.io.PrintWriter;
53 import java.net.MalformedURLException;
55 import java.net.URISyntaxException;
57 import java.security.AllPermission;
58 import java.security.CodeSource;
59 import java.security.PermissionCollection;
60 import java.security.Permissions;
61 import java.security.Policy;
62 import java.util.HashMap;
64 import java.util.Vector;
65 import java.util.logging.ConsoleHandler;
66 import java.util.logging.Level;
67 import java.util.logging.Logger;
69 import javax.swing.LookAndFeel;
70 import javax.swing.Timer;
71 import javax.swing.UIManager;
73 import groovy.lang.Binding;
74 import groovy.util.GroovyScriptEngine;
77 * Main class for Jalview Application <br>
79 * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
82 * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
83 * jalview.bin.Jalview jalview.bin.Jalview
85 * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
86 * embellish '*' to e.g. '*.jar')
94 // BH 6/19/2018 starting to work on JS version - just discovering issues
97 * singleton instance of this class
99 private static Jalview instance;
101 private Desktop desktop;
103 public static AlignFrame currentAlignFrame;
106 * Answers true if Jalview is running as Javascript, else false. The value is
107 * set at compile time.
111 public static boolean isJS()
113 return /** @j2sNative true || */
121 // grab all the rights we can the JVM
122 Policy.setPolicy(new Policy()
125 public PermissionCollection getPermissions(CodeSource codesource)
127 Permissions perms = new Permissions();
128 perms.add(new AllPermission());
133 public void refresh()
142 * keep track of feature fetching tasks.
150 * TODO: generalise to track all jalview events to orchestrate batch
154 private int queued = 0;
156 private int running = 0;
158 public FeatureFetcher()
163 public void addFetcher(final AlignFrame af,
164 final Vector<String> dasSources)
166 final long id = System.currentTimeMillis();
168 final FeatureFetcher us = this;
169 new Thread(new Runnable()
181 af.setProgressBar(MessageManager
182 .getString("status.das_features_being_retrived"), id);
183 af.featureSettings_actionPerformed(null);
184 af.setProgressBar(null, id);
193 public synchronized boolean allFinished()
195 return queued == 0 && running == 0;
200 public static Jalview getInstance()
206 * main class for Jalview application
209 * open <em>filename</em>
211 public static void main(String[] args)
213 // setLogging(); // BH - for event debugging in JavaScript
214 instance = new Jalview();
215 instance.doMain(args);
218 private static void logClass(String name)
220 // BH - for event debugging in JavaScript
221 ConsoleHandler consoleHandler = new ConsoleHandler();
222 consoleHandler.setLevel(Level.ALL);
223 Logger logger = Logger.getLogger(name);
224 logger.setLevel(Level.ALL);
225 logger.addHandler(consoleHandler);
228 @SuppressWarnings("unused")
229 private static void setLogging()
231 // BH - for event debugging in JavaScript (Java mode only)
232 if (!(/** @j2sNative true ||*/false))
234 Logger.getLogger("").setLevel(Level.ALL);
235 logClass("java.awt.EventDispatchThread");
236 logClass("java.awt.EventQueue");
237 logClass("java.awt.Component");
238 logClass("java.awt.focus.Component");
239 logClass("java.awt.focus.DefaultKeyboardFocusManager");
250 void doMain(String[] args)
255 System.setSecurityManager(null);
259 .println("Java version: " + System.getProperty("java.version"));
260 System.out.println(System.getProperty("os.arch") + " "
261 + System.getProperty("os.name") + " "
262 + System.getProperty("os.version"));
264 ArgsParser aparser = new ArgsParser(args);
265 boolean headless = false;
267 String usrPropsFile = aparser.getValue("props");
268 Cache.loadProperties(usrPropsFile); // must do this before
269 if (usrPropsFile != null)
272 "CMD [-props " + usrPropsFile + "] executed successfully!");
276 * BH 2018 ignoring this section for JS
281 if (aparser.contains("help") || aparser.contains("h"))
286 if (aparser.contains("nodisplay") || aparser.contains("nogui")
287 || aparser.contains("headless"))
289 System.setProperty("java.awt.headless", "true");
294 final String jabawsUrl = aparser.getValue("jabaws");
295 if (jabawsUrl != null)
299 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
301 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
302 } catch (MalformedURLException e)
305 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
310 String defs = aparser.getValue("setprop");
313 int p = defs.indexOf('=');
316 System.err.println("Ignoring invalid setprop argument : " + defs);
320 System.out.println("Executing setprop argument: " + defs);
321 // DISABLED FOR SECURITY REASONS
322 // TODO: add a property to allow properties to be overriden by cli args
323 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
325 defs = aparser.getValue("setprop");
327 if (System.getProperty("java.awt.headless") != null
328 && System.getProperty("java.awt.headless").equals("true"))
332 System.setProperty("http.agent",
333 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
337 } catch (NoClassDefFoundError error)
339 error.printStackTrace();
340 System.out.println("\nEssential logging libraries not found."
341 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
349 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
350 } catch (Exception ex)
352 System.err.println("Unexpected Look and Feel Exception");
353 ex.printStackTrace();
355 if (Platform.isAMac())
358 LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
360 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
362 System.setProperty("apple.laf.useScreenMenuBar", "true");
363 if (lookAndFeel != null)
367 UIManager.setLookAndFeel(lookAndFeel);
368 } catch (Throwable e)
371 "Failed to set QuaQua look and feel: " + e.toString());
374 if (lookAndFeel == null || !(lookAndFeel.getClass()
375 .isAssignableFrom(UIManager.getLookAndFeel().getClass()))
376 || !UIManager.getLookAndFeel().getClass().toString()
377 .toLowerCase().contains("quaqua"))
382 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
383 UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
384 } catch (Throwable e)
387 "Failed to reset look and feel: " + e.toString());
393 * configure 'full' SO model if preferences say to,
394 * else use the default (SO Lite)
396 if (Cache.getDefault("USE_FULL_SO", false))
398 SequenceOntologyFactory.setInstance(new SequenceOntology());
403 desktop = new Desktop()
407 // protected void processEvent(AWTEvent e) {
408 // System.out.println("Jalview.java " + e);
409 // super.processEvent(e);
413 desktop.setInBatchMode(true); // indicate we are starting up
414 desktop.setVisible(true);
417 * BH 2018 JS bypass this section
423 desktop.startServiceDiscovery();
424 if (!aparser.contains("nousagestats"))
426 startUsageStats(desktop);
430 System.err.println("CMD [-nousagestats] executed successfully!");
433 if (!aparser.contains("noquestionnaire"))
435 String url = aparser.getValue("questionnaire");
438 // Start the desktop questionnaire prompter with the specified
440 Cache.log.debug("Starting questionnaire url at " + url);
441 desktop.checkForQuestionnaire(url);
442 System.out.println("CMD questionnaire[-" + url
443 + "] executed successfully!");
447 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
449 // Start the desktop questionnaire prompter with the specified
452 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
454 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
456 "Starting questionnaire with default url: " + defurl);
457 desktop.checkForQuestionnaire(defurl);
464 .println("CMD [-noquestionnaire] executed successfully!");
467 if (!aparser.contains("nonews"))
469 desktop.checkForNews();
472 BioJsHTMLOutput.updateBioJS();
476 String file = null, data = null;
477 FileFormatI format = null;
478 DataSourceType protocol = null;
479 FileLoader fileLoader = new FileLoader(!headless);
480 Vector<String> getFeatures = null; // vector of das source nicknames to
484 String groovyscript = null; // script to execute after all loading is
485 // completed one way or another
486 // extract groovy argument and execute if necessary
487 groovyscript = aparser.getValue("groovy", true);
488 file = aparser.getValue("open", true);
490 if (file == null && desktop == null)
492 System.out.println("No files to open!");
495 String vamsasImport = aparser.getValue("vdoc");
496 String vamsasSession = aparser.getValue("vsess");
497 if (vamsasImport != null || vamsasSession != null)
499 if (desktop == null || headless)
502 "Headless vamsas sessions not yet supported. Sorry.");
505 // if we have a file, start a new session and import it.
506 boolean inSession = false;
507 if (vamsasImport != null)
511 DataSourceType viprotocol = AppletFormatAdapter
512 .checkProtocol(vamsasImport);
513 if (viprotocol == DataSourceType.FILE)
515 inSession = desktop.vamsasImport(new File(vamsasImport));
517 else if (viprotocol == DataSourceType.URL)
519 inSession = desktop.vamsasImport(new URL(vamsasImport));
522 } catch (Exception e)
524 System.err.println("Exeption when importing " + vamsasImport
525 + " as a vamsas document.");
530 System.err.println("Failed to import " + vamsasImport
531 + " as a vamsas document.");
535 System.out.println("Imported Successfully into new session "
536 + desktop.getVamsasApplication().getCurrentSession());
539 if (vamsasSession != null)
541 if (vamsasImport != null)
543 // close the newly imported session and import the Jalview specific
544 // remnants into the new session later on.
545 desktop.vamsasStop_actionPerformed(null);
547 // now join the new session
550 if (desktop.joinVamsasSession(vamsasSession))
553 "Successfully joined vamsas session " + vamsasSession);
557 System.err.println("WARNING: Failed to join vamsas session "
560 } catch (Exception e)
563 "ERROR: Failed to join vamsas session " + vamsasSession);
566 if (vamsasImport != null)
568 // the Jalview specific remnants can now be imported into the new
569 // session at the user's leisure.
571 "Skipping Push for import of data into existing vamsas session."); // TODO:
576 // desktop.getVamsasApplication().push_update();
581 // Finally, deal with the remaining input data.
586 desktop.setProgressBar(
588 .getString("status.processing_commandline_args"),
589 progress = System.currentTimeMillis());
591 System.out.println("CMD [-open " + file + "] executed successfully!");
593 if (!isJS() && !file.startsWith("http://"))
595 if (!(new File(file)).exists())
597 System.out.println("Can't find " + file);
605 protocol = AppletFormatAdapter.checkProtocol(file);
609 format = new IdentifyFile().identify(file, protocol);
610 } catch (FileFormatException e1)
615 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
619 System.out.println("error");
623 setCurrentAlignFrame(af);
624 data = aparser.getValue("colour", true);
627 data.replaceAll("%20", " ");
629 ColourSchemeI cs = ColourSchemeProperty
630 .getColourScheme(af.getViewport().getAlignment(), data);
635 "CMD [-color " + data + "] executed successfully!");
640 // Must maintain ability to use the groups flag
641 data = aparser.getValue("groups", true);
644 af.parseFeaturesFile(data,
645 AppletFormatAdapter.checkProtocol(data));
646 // System.out.println("Added " + data);
648 "CMD groups[-" + data + "] executed successfully!");
650 data = aparser.getValue("features", true);
653 af.parseFeaturesFile(data,
654 AppletFormatAdapter.checkProtocol(data));
655 // System.out.println("Added " + data);
657 "CMD [-features " + data + "] executed successfully!");
660 data = aparser.getValue("annotations", true);
663 af.loadJalviewDataFile(data, null, null, null);
664 // System.out.println("Added " + data);
666 "CMD [-annotations " + data + "] executed successfully!");
668 // set or clear the sortbytree flag.
669 if (aparser.contains("sortbytree"))
671 af.getViewport().setSortByTree(true);
672 if (af.getViewport().getSortByTree())
674 System.out.println("CMD [-sortbytree] executed successfully!");
677 if (aparser.contains("no-annotation"))
679 af.getViewport().setShowAnnotation(false);
680 if (!af.getViewport().isShowAnnotation())
682 System.out.println("CMD no-annotation executed successfully!");
685 if (aparser.contains("nosortbytree"))
687 af.getViewport().setSortByTree(false);
688 if (!af.getViewport().getSortByTree())
691 .println("CMD [-nosortbytree] executed successfully!");
694 data = aparser.getValue("tree", true);
700 "CMD [-tree " + data + "] executed successfully!");
701 NewickFile nf = new NewickFile(data,
702 AppletFormatAdapter.checkProtocol(data));
704 .setCurrentTree(af.showNewickTree(nf, data).getTree());
705 } catch (IOException ex)
707 System.err.println("Couldn't add tree " + data);
708 ex.printStackTrace(System.err);
711 // TODO - load PDB structure(s) to alignment JAL-629
712 // (associate with identical sequence in alignment, or a specified
715 getFeatures = checkDasArguments(aparser);
716 if (af != null && getFeatures != null)
718 FeatureFetcher ff = startFeatureFetching(getFeatures);
721 while (!ff.allFinished() || af.operationInProgress())
723 // wait around until fetching is finished.
727 } catch (Exception e)
733 getFeatures = null; // have retrieved features - forget them now.
735 if (groovyscript != null)
737 // Execute the groovy script after we've done all the rendering stuff
738 // and before any images or figures are generated.
739 System.out.println("Executing script " + groovyscript);
740 executeGroovyScript(groovyscript, af);
741 System.out.println("CMD groovy[" + groovyscript
742 + "] executed successfully!");
745 String imageName = "unnamed.png";
746 while (aparser.getSize() > 1)
748 String outputFormat = aparser.nextValue();
749 file = aparser.nextValue();
751 if (outputFormat.equalsIgnoreCase("png"))
753 af.createPNG(new File(file));
754 imageName = (new File(file)).getName();
755 System.out.println("Creating PNG image: " + file);
758 else if (outputFormat.equalsIgnoreCase("svg"))
760 File imageFile = new File(file);
761 imageName = imageFile.getName();
762 af.createSVG(imageFile);
763 System.out.println("Creating SVG image: " + file);
766 else if (outputFormat.equalsIgnoreCase("html"))
768 File imageFile = new File(file);
769 imageName = imageFile.getName();
770 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
771 htmlSVG.exportHTML(file);
773 System.out.println("Creating HTML image: " + file);
776 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
780 System.err.println("The output html file must not be null");
785 BioJsHTMLOutput.refreshVersionInfo(
786 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
787 } catch (URISyntaxException e)
791 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
792 bjs.exportHTML(file);
794 .println("Creating BioJS MSA Viwer HTML file: " + file);
797 else if (outputFormat.equalsIgnoreCase("imgMap"))
799 af.createImageMap(new File(file), imageName);
800 System.out.println("Creating image map: " + file);
803 else if (outputFormat.equalsIgnoreCase("eps"))
805 File outputFile = new File(file);
807 "Creating EPS file: " + outputFile.getAbsolutePath());
808 af.createEPS(outputFile);
812 af.saveAlignment(file, format);
813 if (af.isSaveAlignmentSuccessful())
815 System.out.println("Written alignment in " + format
816 + " format to " + file);
820 System.out.println("Error writing file " + file + " in "
821 + format + " format!!");
826 while (aparser.getSize() > 0)
828 System.out.println("Unknown arg: " + aparser.nextValue());
832 AlignFrame startUpAlframe = null;
833 // We'll only open the default file if the desktop is visible.
835 // ////////////////////
837 if (/** @j2sNative false && */ // BH 2018
838 !headless && file == null && vamsasImport == null
839 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
841 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
842 jalview.bin.Cache.getDefault("www.jalview.org",
843 "http://www.jalview.org")
844 + "/examples/exampleFile_2_7.jar");
846 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
848 // hardwire upgrade of the startup file
849 file.replace("_2_3.jar", "_2_7.jar");
850 // and remove the stale setting
851 jalview.bin.Cache.removeProperty("STARTUP_FILE");
854 protocol = DataSourceType.FILE;
856 if (file.indexOf("http:") > -1)
858 protocol = DataSourceType.URL;
861 if (file.endsWith(".jar"))
863 format = FileFormat.Jalview;
869 format = new IdentifyFile().identify(file, protocol);
870 } catch (FileFormatException e)
876 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
878 getFeatures = checkDasArguments(aparser);
879 // extract groovy arguments before anything else.
881 // If the user has specified features to be retrieved,
882 // or a groovy script to be executed, do them if they
883 // haven't been done already
884 // fetch features for the default alignment
885 if (getFeatures != null)
887 if (startUpAlframe != null)
889 startFeatureFetching(getFeatures);
892 // Once all other stuff is done, execute any groovy scripts (in order)
893 if (groovyscript != null)
895 if (Cache.groovyJarsPresent())
897 System.out.println("Executing script " + groovyscript);
898 executeGroovyScript(groovyscript, startUpAlframe);
903 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
907 // and finally, turn off batch mode indicator - if the desktop still exists
912 desktop.setProgressBar(null, progress);
914 desktop.setInBatchMode(false);
918 private static void showUsage()
921 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
922 + "-nodisplay\tRun Jalview without User Interface.\n"
923 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
924 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
925 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
926 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
927 + "-features FILE\tUse the given file to mark features on the alignment.\n"
928 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
929 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
930 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
931 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
932 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
933 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
934 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
935 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
936 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
937 + "-png FILE\tCreate PNG image FILE from alignment.\n"
938 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
939 + "-html FILE\tCreate HTML file from alignment.\n"
940 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
941 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
942 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
943 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
944 + "-noquestionnaire\tTurn off questionnaire check.\n"
945 + "-nonews\tTurn off check for Jalview news.\n"
946 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
947 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
949 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
950 // after all other properties files have been read\n\t
951 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
952 // passed in correctly)"
953 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
954 + "-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"
955 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
956 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
957 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
959 // "-vdoc vamsas-document\tImport vamsas document into new
960 // session or join existing session with same URN\n"
961 // + "-vses vamsas-session\tJoin session with given URN\n"
962 + "-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"
963 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
966 private static void startUsageStats(final Desktop desktop)
969 * start a User Config prompt asking if we can log usage statistics.
971 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
972 "USAGESTATS", "Jalview Usage Statistics",
973 "Do you want to help make Jalview better by enabling "
974 + "the collection of usage statistics with Google Analytics ?"
975 + "\n\n(you can enable or disable usage tracking in the preferences)",
982 "Initialising googletracker for usage stats.");
983 Cache.initGoogleTracker();
984 Cache.log.debug("Tracking enabled.");
991 Cache.log.debug("Not enabling Google Tracking.");
994 desktop.addDialogThread(prompter);
998 * Locate the given string as a file and pass it to the groovy interpreter.
1000 * @param groovyscript
1001 * the script to execute
1002 * @param jalviewContext
1003 * the Jalview Desktop object passed in to the groovy binding as the
1006 private void executeGroovyScript(String groovyscript, AlignFrame af)
1009 * for scripts contained in files
1016 if (groovyscript.trim().equals("STDIN"))
1018 // read from stdin into a tempfile and execute it
1021 tfile = File.createTempFile("jalview", "groovy");
1022 PrintWriter outfile = new PrintWriter(
1023 new OutputStreamWriter(new FileOutputStream(tfile)));
1024 BufferedReader br = new BufferedReader(
1025 new InputStreamReader(System.in));
1027 while ((line = br.readLine()) != null)
1029 outfile.write(line + "\n");
1035 } catch (Exception ex)
1037 System.err.println("Failed to read from STDIN into tempfile "
1038 + ((tfile == null) ? "(tempfile wasn't created)"
1039 : tfile.toString()));
1040 ex.printStackTrace();
1045 sfile = tfile.toURI().toURL();
1046 } catch (Exception x)
1049 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1051 x.printStackTrace();
1059 sfile = new URI(groovyscript).toURL();
1060 } catch (Exception x)
1062 tfile = new File(groovyscript);
1063 if (!tfile.exists())
1065 System.err.println("File '" + groovyscript + "' does not exist.");
1068 if (!tfile.canRead())
1070 System.err.println("File '" + groovyscript + "' cannot be read.");
1073 if (tfile.length() < 1)
1075 System.err.println("File '" + groovyscript + "' is empty.");
1080 sfile = tfile.getAbsoluteFile().toURI().toURL();
1081 } catch (Exception ex)
1083 System.err.println("Failed to create a file URL for "
1084 + tfile.getAbsoluteFile());
1091 Map<String, Object> vbinding = new HashMap<>();
1092 vbinding.put("Jalview", this);
1095 vbinding.put("currentAlFrame", af);
1097 Binding gbinding = new Binding(vbinding);
1098 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1099 gse.run(sfile.toString(), gbinding);
1100 if ("STDIN".equals(groovyscript))
1102 // delete temp file that we made -
1103 // only if it was successfully executed
1106 } catch (Exception e)
1108 System.err.println("Exception Whilst trying to execute file " + sfile
1109 + " as a groovy script.");
1110 e.printStackTrace(System.err);
1116 * Check commandline for any das server definitions or any fetchfrom switches
1118 * @return vector of DAS source nicknames to retrieve from
1120 private static Vector<String> checkDasArguments(ArgsParser aparser)
1122 Vector<String> source = null;
1124 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
1125 while ((data = aparser.getValue("dasserver", true)) != null)
1127 String nickname = null;
1129 int pos = data.indexOf('=');
1130 // determine capabilities
1133 nickname = data.substring(0, pos);
1135 url = data.substring(pos + 1);
1136 if (url != null && (url.startsWith("http:")
1137 || url.startsWith("sequence:http:")))
1139 if (nickname == null)
1143 if (locsources == null)
1151 locsources = locsources + nickname + "|" + url;
1153 "NOTE! dasserver parameter not yet really supported (got args of "
1154 + nickname + "|" + url);
1157 source = new Vector<>();
1159 source.addElement(nickname);
1162 "CMD [-dasserver " + data + "] executed successfully!");
1163 } // loop until no more server entries are found.
1164 if (locsources != null && locsources.indexOf('|') > -1)
1166 Cache.log.debug("Setting local source list in properties file to:\n"
1168 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
1170 while ((data = aparser.getValue("fetchfrom", true)) != null)
1172 System.out.println("adding source '" + data + "'");
1175 source = new Vector<>();
1177 source.addElement(data);
1183 * start a feature fetcher for every alignment frame
1187 private FeatureFetcher startFeatureFetching(
1188 final Vector<String> dasSources)
1190 FeatureFetcher ff = new FeatureFetcher();
1191 AlignFrame afs[] = Desktop.getAlignFrames();
1192 if (afs == null || afs.length == 0)
1196 for (int i = 0; i < afs.length; i++)
1198 ff.addFetcher(afs[i], dasSources);
1203 public static boolean isHeadlessMode()
1205 String isheadless = System.getProperty("java.awt.headless");
1206 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1213 public AlignFrame[] getAlignFrames()
1215 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1216 : Desktop.getAlignFrames();
1221 * Quit method delegates to Desktop.quit - unless running in headless mode
1222 * when it just ends the JVM
1226 if (desktop != null)
1236 public static AlignFrame getCurrentAlignFrame()
1238 return Jalview.currentAlignFrame;
1241 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1243 Jalview.currentAlignFrame = currentAlignFrame;