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')
91 public class JalviewJS
94 // BH 6/19/2018 starting to work on JS version - just discovering issues
97 * singleton instance of this class
99 private static JalviewJS 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 JalviewJS getInstance()
206 * main class for Jalview application
209 * open <em>filename</em>
211 public static void main(String[] args)
213 instance = new JalviewJS();
214 instance.doMain(new String[] {"open","http://www.jalview.org/examples/uniref50.fa", "-features","http://www.jalview.org/examples/exampleFeatures.txt"});
217 private static void logClass(String name)
219 // BH - for event debugging in JavaScript
220 ConsoleHandler consoleHandler = new ConsoleHandler();
221 consoleHandler.setLevel(Level.ALL);
222 Logger logger = Logger.getLogger(name);
223 logger.setLevel(Level.ALL);
224 logger.addHandler(consoleHandler);
227 @SuppressWarnings("unused")
228 private static void setLogging()
230 // BH - for event debugging in JavaScript (Java mode only)
231 if (!(/** @j2sNative true ||*/false))
233 Logger.getLogger("").setLevel(Level.ALL);
234 logClass("java.awt.EventDispatchThread");
235 logClass("java.awt.EventQueue");
236 logClass("java.awt.Component");
237 logClass("java.awt.focus.Component");
238 logClass("java.awt.focus.DefaultKeyboardFocusManager");
249 void doMain(String[] args)
254 System.setSecurityManager(null);
258 .println("Java version: " + System.getProperty("java.version"));
259 System.out.println(System.getProperty("os.arch") + " "
260 + System.getProperty("os.name") + " "
261 + System.getProperty("os.version"));
263 ArgsParser aparser = new ArgsParser(args);
264 boolean headless = false;
266 String usrPropsFile = aparser.getValue("props");
267 Cache.loadProperties(usrPropsFile); // must do this before
268 if (usrPropsFile != null)
271 "CMD [-props " + usrPropsFile + "] executed successfully!");
275 * BH 2018 ignoring this section for JS
280 if (aparser.contains("help") || aparser.contains("h"))
285 if (aparser.contains("nodisplay") || aparser.contains("nogui")
286 || aparser.contains("headless"))
288 System.setProperty("java.awt.headless", "true");
293 final String jabawsUrl = aparser.getValue("jabaws");
294 if (jabawsUrl != null)
298 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
300 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
301 } catch (MalformedURLException e)
304 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
309 String defs = aparser.getValue("setprop");
312 int p = defs.indexOf('=');
315 System.err.println("Ignoring invalid setprop argument : " + defs);
319 System.out.println("Executing setprop argument: " + defs);
320 // DISABLED FOR SECURITY REASONS
321 // TODO: add a property to allow properties to be overriden by cli args
322 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
324 defs = aparser.getValue("setprop");
326 if (System.getProperty("java.awt.headless") != null
327 && System.getProperty("java.awt.headless").equals("true"))
331 System.setProperty("http.agent",
332 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
336 } catch (NoClassDefFoundError error)
338 error.printStackTrace();
339 System.out.println("\nEssential logging libraries not found."
340 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
348 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
349 } catch (Exception ex)
351 System.err.println("Unexpected Look and Feel Exception");
352 ex.printStackTrace();
354 if (Platform.isAMacAndNotJS())
357 LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
359 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
361 System.setProperty("apple.laf.useScreenMenuBar", "true");
362 if (lookAndFeel != null)
366 UIManager.setLookAndFeel(lookAndFeel);
367 } catch (Throwable e)
370 "Failed to set QuaQua look and feel: " + e.toString());
373 if (lookAndFeel == null || !(lookAndFeel.getClass()
374 .isAssignableFrom(UIManager.getLookAndFeel().getClass()))
375 || !UIManager.getLookAndFeel().getClass().toString()
376 .toLowerCase().contains("quaqua"))
381 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
382 UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
383 } catch (Throwable e)
386 "Failed to reset look and feel: " + e.toString());
392 * configure 'full' SO model if preferences say to,
393 * else use the default (SO Lite)
395 if (Cache.getDefault("USE_FULL_SO", false))
397 SequenceOntologyFactory.setInstance(new SequenceOntology());
402 desktop = new Desktop()
406 // protected void processEvent(AWTEvent e) {
407 // System.out.println("Jalview.java " + e);
408 // super.processEvent(e);
412 desktop.setInBatchMode(true); // indicate we are starting up
413 desktop.setVisible(true);
416 * BH 2018 JS bypass this section
422 desktop.startServiceDiscovery();
423 if (!aparser.contains("nousagestats"))
425 startUsageStats(desktop);
429 System.err.println("CMD [-nousagestats] executed successfully!");
432 if (!aparser.contains("noquestionnaire"))
434 String url = aparser.getValue("questionnaire");
437 // Start the desktop questionnaire prompter with the specified
439 Cache.log.debug("Starting questionnaire url at " + url);
440 desktop.checkForQuestionnaire(url);
441 System.out.println("CMD questionnaire[-" + url
442 + "] executed successfully!");
446 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
448 // Start the desktop questionnaire prompter with the specified
451 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
453 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
455 "Starting questionnaire with default url: " + defurl);
456 desktop.checkForQuestionnaire(defurl);
463 .println("CMD [-noquestionnaire] executed successfully!");
466 if (!aparser.contains("nonews"))
468 desktop.checkForNews();
471 BioJsHTMLOutput.updateBioJS();
475 String file = null, data = null;
476 FileFormatI format = null;
477 DataSourceType protocol = null;
478 FileLoader fileLoader = new FileLoader(!headless);
479 Vector<String> getFeatures = null; // vector of das source nicknames to
483 String groovyscript = null; // script to execute after all loading is
484 // completed one way or another
485 // extract groovy argument and execute if necessary
486 groovyscript = aparser.getValue("groovy", true);
487 file = aparser.getValue("open", true);
489 if (file == null && desktop == null)
491 System.out.println("No files to open!");
494 String vamsasImport = aparser.getValue("vdoc");
495 String vamsasSession = aparser.getValue("vsess");
496 if (vamsasImport != null || vamsasSession != null)
498 if (desktop == null || headless)
501 "Headless vamsas sessions not yet supported. Sorry.");
504 // if we have a file, start a new session and import it.
505 boolean inSession = false;
506 if (vamsasImport != null)
510 DataSourceType viprotocol = AppletFormatAdapter
511 .checkProtocol(vamsasImport);
512 if (viprotocol == DataSourceType.FILE)
514 inSession = desktop.vamsasImport(new File(vamsasImport));
516 else if (viprotocol == DataSourceType.URL)
518 inSession = desktop.vamsasImport(new URL(vamsasImport));
521 } catch (Exception e)
523 System.err.println("Exeption when importing " + vamsasImport
524 + " as a vamsas document.");
529 System.err.println("Failed to import " + vamsasImport
530 + " as a vamsas document.");
534 System.out.println("Imported Successfully into new session "
535 + desktop.getVamsasApplication().getCurrentSession());
538 if (vamsasSession != null)
540 if (vamsasImport != null)
542 // close the newly imported session and import the Jalview specific
543 // remnants into the new session later on.
544 desktop.vamsasStop_actionPerformed(null);
546 // now join the new session
549 if (desktop.joinVamsasSession(vamsasSession))
552 "Successfully joined vamsas session " + vamsasSession);
556 System.err.println("WARNING: Failed to join vamsas session "
559 } catch (Exception e)
562 "ERROR: Failed to join vamsas session " + vamsasSession);
565 if (vamsasImport != null)
567 // the Jalview specific remnants can now be imported into the new
568 // session at the user's leisure.
570 "Skipping Push for import of data into existing vamsas session."); // TODO:
575 // desktop.getVamsasApplication().push_update();
580 // Finally, deal with the remaining input data.
585 desktop.setProgressBar(
587 .getString("status.processing_commandline_args"),
588 progress = System.currentTimeMillis());
590 System.out.println("CMD [-open " + file + "] executed successfully!");
592 if (!isJS() && !file.startsWith("http://"))
594 if (!(new File(file)).exists())
596 System.out.println("Can't find " + file);
604 protocol = AppletFormatAdapter.checkProtocol(file);
608 format = new IdentifyFile().identify(file, protocol);
609 } catch (FileFormatException e1)
614 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
618 System.out.println("error");
622 setCurrentAlignFrame(af);
623 data = aparser.getValue("colour", true);
626 data.replaceAll("%20", " ");
628 ColourSchemeI cs = ColourSchemeProperty
629 .getColourScheme(af.getViewport().getAlignment(), data);
634 "CMD [-color " + data + "] executed successfully!");
639 // Must maintain ability to use the groups flag
640 data = aparser.getValue("groups", true);
643 af.parseFeaturesFile(data,
644 AppletFormatAdapter.checkProtocol(data));
645 // System.out.println("Added " + data);
647 "CMD groups[-" + data + "] executed successfully!");
649 data = aparser.getValue("features", true);
652 af.parseFeaturesFile(data,
653 AppletFormatAdapter.checkProtocol(data));
654 // System.out.println("Added " + data);
656 "CMD [-features " + data + "] executed successfully!");
659 data = aparser.getValue("annotations", true);
662 af.loadJalviewDataFile(data, null, null, null);
663 // System.out.println("Added " + data);
665 "CMD [-annotations " + data + "] executed successfully!");
667 // set or clear the sortbytree flag.
668 if (aparser.contains("sortbytree"))
670 af.getViewport().setSortByTree(true);
671 if (af.getViewport().getSortByTree())
673 System.out.println("CMD [-sortbytree] executed successfully!");
676 if (aparser.contains("no-annotation"))
678 af.getViewport().setShowAnnotation(false);
679 if (!af.getViewport().isShowAnnotation())
681 System.out.println("CMD no-annotation executed successfully!");
684 if (aparser.contains("nosortbytree"))
686 af.getViewport().setSortByTree(false);
687 if (!af.getViewport().getSortByTree())
690 .println("CMD [-nosortbytree] executed successfully!");
693 data = aparser.getValue("tree", true);
699 "CMD [-tree " + data + "] executed successfully!");
700 NewickFile nf = new NewickFile(data,
701 AppletFormatAdapter.checkProtocol(data));
703 .setCurrentTree(af.showNewickTree(nf, data).getTree());
704 } catch (IOException ex)
706 System.err.println("Couldn't add tree " + data);
707 ex.printStackTrace(System.err);
710 // TODO - load PDB structure(s) to alignment JAL-629
711 // (associate with identical sequence in alignment, or a specified
714 getFeatures = checkDasArguments(aparser);
715 if (af != null && getFeatures != null)
717 FeatureFetcher ff = startFeatureFetching(getFeatures);
720 while (!ff.allFinished() || af.operationInProgress())
722 // wait around until fetching is finished.
726 } catch (Exception e)
732 getFeatures = null; // have retrieved features - forget them now.
734 if (groovyscript != null)
736 // Execute the groovy script after we've done all the rendering stuff
737 // and before any images or figures are generated.
738 System.out.println("Executing script " + groovyscript);
739 executeGroovyScript(groovyscript, af);
740 System.out.println("CMD groovy[" + groovyscript
741 + "] executed successfully!");
744 String imageName = "unnamed.png";
745 while (aparser.getSize() > 1)
747 String outputFormat = aparser.nextValue();
748 file = aparser.nextValue();
750 if (outputFormat.equalsIgnoreCase("png"))
752 af.createPNG(new File(file));
753 imageName = (new File(file)).getName();
754 System.out.println("Creating PNG image: " + file);
757 else if (outputFormat.equalsIgnoreCase("svg"))
759 File imageFile = new File(file);
760 imageName = imageFile.getName();
761 af.createSVG(imageFile);
762 System.out.println("Creating SVG image: " + file);
765 else if (outputFormat.equalsIgnoreCase("html"))
767 File imageFile = new File(file);
768 imageName = imageFile.getName();
769 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
770 htmlSVG.exportHTML(file);
772 System.out.println("Creating HTML image: " + file);
775 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
779 System.err.println("The output html file must not be null");
784 BioJsHTMLOutput.refreshVersionInfo(
785 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
786 } catch (URISyntaxException e)
790 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
791 bjs.exportHTML(file);
793 .println("Creating BioJS MSA Viwer HTML file: " + file);
796 else if (outputFormat.equalsIgnoreCase("imgMap"))
798 af.createImageMap(new File(file), imageName);
799 System.out.println("Creating image map: " + file);
802 else if (outputFormat.equalsIgnoreCase("eps"))
804 File outputFile = new File(file);
806 "Creating EPS file: " + outputFile.getAbsolutePath());
807 af.createEPS(outputFile);
811 af.saveAlignment(file, format);
812 if (af.isSaveAlignmentSuccessful())
814 System.out.println("Written alignment in " + format
815 + " format to " + file);
819 System.out.println("Error writing file " + file + " in "
820 + format + " format!!");
825 while (aparser.getSize() > 0)
827 System.out.println("Unknown arg: " + aparser.nextValue());
831 AlignFrame startUpAlframe = null;
832 // We'll only open the default file if the desktop is visible.
834 // ////////////////////
836 if (/** @j2sNative false && */ // BH 2018
837 !headless && file == null && vamsasImport == null
838 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
840 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
841 jalview.bin.Cache.getDefault("www.jalview.org",
842 "http://www.jalview.org")
843 + "/examples/exampleFile_2_7.jar");
845 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
847 // hardwire upgrade of the startup file
848 file.replace("_2_3.jar", "_2_7.jar");
849 // and remove the stale setting
850 jalview.bin.Cache.removeProperty("STARTUP_FILE");
853 protocol = DataSourceType.FILE;
855 if (file.indexOf("http:") > -1)
857 protocol = DataSourceType.URL;
860 if (file.endsWith(".jar"))
862 format = FileFormat.Jalview;
868 format = new IdentifyFile().identify(file, protocol);
869 } catch (FileFormatException e)
875 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
877 getFeatures = checkDasArguments(aparser);
878 // extract groovy arguments before anything else.
880 // If the user has specified features to be retrieved,
881 // or a groovy script to be executed, do them if they
882 // haven't been done already
883 // fetch features for the default alignment
884 if (getFeatures != null)
886 if (startUpAlframe != null)
888 startFeatureFetching(getFeatures);
891 // Once all other stuff is done, execute any groovy scripts (in order)
892 if (groovyscript != null)
894 if (Cache.groovyJarsPresent())
896 System.out.println("Executing script " + groovyscript);
897 executeGroovyScript(groovyscript, startUpAlframe);
902 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
906 // and finally, turn off batch mode indicator - if the desktop still exists
911 desktop.setProgressBar(null, progress);
913 desktop.setInBatchMode(false);
917 private static void showUsage()
920 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
921 + "-nodisplay\tRun Jalview without User Interface.\n"
922 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
923 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
924 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
925 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
926 + "-features FILE\tUse the given file to mark features on the alignment.\n"
927 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
928 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
929 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
930 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
931 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
932 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
933 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
934 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
935 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
936 + "-png FILE\tCreate PNG image FILE from alignment.\n"
937 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
938 + "-html FILE\tCreate HTML file from alignment.\n"
939 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
940 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
941 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
942 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
943 + "-noquestionnaire\tTurn off questionnaire check.\n"
944 + "-nonews\tTurn off check for Jalview news.\n"
945 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
946 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
948 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
949 // after all other properties files have been read\n\t
950 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
951 // passed in correctly)"
952 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
953 + "-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"
954 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
955 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
956 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
958 // "-vdoc vamsas-document\tImport vamsas document into new
959 // session or join existing session with same URN\n"
960 // + "-vses vamsas-session\tJoin session with given URN\n"
961 + "-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"
962 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
965 private static void startUsageStats(final Desktop desktop)
968 * start a User Config prompt asking if we can log usage statistics.
970 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
971 "USAGESTATS", "Jalview Usage Statistics",
972 "Do you want to help make Jalview better by enabling "
973 + "the collection of usage statistics with Google Analytics ?"
974 + "\n\n(you can enable or disable usage tracking in the preferences)",
981 "Initialising googletracker for usage stats.");
982 Cache.initGoogleTracker();
983 Cache.log.debug("Tracking enabled.");
990 Cache.log.debug("Not enabling Google Tracking.");
993 desktop.addDialogThread(prompter);
997 * Locate the given string as a file and pass it to the groovy interpreter.
999 * @param groovyscript
1000 * the script to execute
1001 * @param jalviewContext
1002 * the Jalview Desktop object passed in to the groovy binding as the
1005 private void executeGroovyScript(String groovyscript, AlignFrame af)
1008 * for scripts contained in files
1015 if (groovyscript.trim().equals("STDIN"))
1017 // read from stdin into a tempfile and execute it
1020 tfile = File.createTempFile("jalview", "groovy");
1021 PrintWriter outfile = new PrintWriter(
1022 new OutputStreamWriter(new FileOutputStream(tfile)));
1023 BufferedReader br = new BufferedReader(
1024 new InputStreamReader(System.in));
1026 while ((line = br.readLine()) != null)
1028 outfile.write(line + "\n");
1034 } catch (Exception ex)
1036 System.err.println("Failed to read from STDIN into tempfile "
1037 + ((tfile == null) ? "(tempfile wasn't created)"
1038 : tfile.toString()));
1039 ex.printStackTrace();
1044 sfile = tfile.toURI().toURL();
1045 } catch (Exception x)
1048 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1050 x.printStackTrace();
1058 sfile = new URI(groovyscript).toURL();
1059 } catch (Exception x)
1061 tfile = new File(groovyscript);
1062 if (!tfile.exists())
1064 System.err.println("File '" + groovyscript + "' does not exist.");
1067 if (!tfile.canRead())
1069 System.err.println("File '" + groovyscript + "' cannot be read.");
1072 if (tfile.length() < 1)
1074 System.err.println("File '" + groovyscript + "' is empty.");
1079 sfile = tfile.getAbsoluteFile().toURI().toURL();
1080 } catch (Exception ex)
1082 System.err.println("Failed to create a file URL for "
1083 + tfile.getAbsoluteFile());
1090 Map<String, Object> vbinding = new HashMap<>();
1091 vbinding.put("Jalview", this);
1094 vbinding.put("currentAlFrame", af);
1096 Binding gbinding = new Binding(vbinding);
1097 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1098 gse.run(sfile.toString(), gbinding);
1099 if ("STDIN".equals(groovyscript))
1101 // delete temp file that we made -
1102 // only if it was successfully executed
1105 } catch (Exception e)
1107 System.err.println("Exception Whilst trying to execute file " + sfile
1108 + " as a groovy script.");
1109 e.printStackTrace(System.err);
1115 * Check commandline for any das server definitions or any fetchfrom switches
1117 * @return vector of DAS source nicknames to retrieve from
1119 private static Vector<String> checkDasArguments(ArgsParser aparser)
1121 Vector<String> source = null;
1123 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
1124 while ((data = aparser.getValue("dasserver", true)) != null)
1126 String nickname = null;
1128 int pos = data.indexOf('=');
1129 // determine capabilities
1132 nickname = data.substring(0, pos);
1134 url = data.substring(pos + 1);
1135 if (url != null && (url.startsWith("http:")
1136 || url.startsWith("sequence:http:")))
1138 if (nickname == null)
1142 if (locsources == null)
1150 locsources = locsources + nickname + "|" + url;
1152 "NOTE! dasserver parameter not yet really supported (got args of "
1153 + nickname + "|" + url);
1156 source = new Vector<>();
1158 source.addElement(nickname);
1161 "CMD [-dasserver " + data + "] executed successfully!");
1162 } // loop until no more server entries are found.
1163 if (locsources != null && locsources.indexOf('|') > -1)
1165 Cache.log.debug("Setting local source list in properties file to:\n"
1167 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
1169 while ((data = aparser.getValue("fetchfrom", true)) != null)
1171 System.out.println("adding source '" + data + "'");
1174 source = new Vector<>();
1176 source.addElement(data);
1182 * start a feature fetcher for every alignment frame
1186 private FeatureFetcher startFeatureFetching(
1187 final Vector<String> dasSources)
1189 FeatureFetcher ff = new FeatureFetcher();
1190 AlignFrame afs[] = Desktop.getAlignFrames();
1191 if (afs == null || afs.length == 0)
1195 for (int i = 0; i < afs.length; i++)
1197 ff.addFetcher(afs[i], dasSources);
1202 public static boolean isHeadlessMode()
1204 String isheadless = System.getProperty("java.awt.headless");
1205 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1212 public AlignFrame[] getAlignFrames()
1214 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1215 : Desktop.getAlignFrames();
1220 * Quit method delegates to Desktop.quit - unless running in headless mode
1221 * when it just ends the JVM
1225 if (desktop != null)
1235 public static AlignFrame getCurrentAlignFrame()
1237 return JalviewJS.currentAlignFrame;
1240 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1242 JalviewJS.currentAlignFrame = currentAlignFrame;