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.io.BufferedReader;
46 import java.io.FileOutputStream;
47 import java.io.IOException;
48 import java.io.InputStreamReader;
49 import java.io.OutputStreamWriter;
50 import java.io.PrintWriter;
51 import java.net.MalformedURLException;
53 import java.net.URISyntaxException;
55 import java.security.AllPermission;
56 import java.security.CodeSource;
57 import java.security.PermissionCollection;
58 import java.security.Permissions;
59 import java.security.Policy;
60 import java.util.HashMap;
62 import java.util.Vector;
63 import java.util.logging.ConsoleHandler;
64 import java.util.logging.Level;
65 import java.util.logging.Logger;
67 import javax.swing.LookAndFeel;
68 import javax.swing.UIManager;
70 import groovy.lang.Binding;
71 import groovy.util.GroovyScriptEngine;
74 * Main class for Jalview Application <br>
76 * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
79 * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
80 * jalview.bin.Jalview jalview.bin.Jalview
82 * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
83 * embellish '*' to e.g. '*.jar')
91 // BH 6/19/2018 starting to work on JS version - just discovering issues
94 * singleton instance of this class
96 private static Jalview instance;
98 private Desktop desktop;
100 public static AlignFrame currentAlignFrame;
103 * Answers true if Jalview is running as Javascript, else false. The value is
104 * set at compile time.
108 public static boolean isJS()
110 return /** @j2sNative true || */
118 // grab all the rights we can the JVM
119 Policy.setPolicy(new Policy()
122 public PermissionCollection getPermissions(CodeSource codesource)
124 Permissions perms = new Permissions();
125 perms.add(new AllPermission());
130 public void refresh()
139 * keep track of feature fetching tasks.
147 * TODO: generalise to track all jalview events to orchestrate batch
151 private int queued = 0;
153 private int running = 0;
155 public FeatureFetcher()
160 public void addFetcher(final AlignFrame af,
161 final Vector<String> dasSources)
163 final long id = System.currentTimeMillis();
165 final FeatureFetcher us = this;
166 new Thread(new Runnable()
178 af.setProgressBar(MessageManager
179 .getString("status.das_features_being_retrived"), id);
180 af.featureSettings_actionPerformed(null);
181 af.setProgressBar(null, id);
190 public synchronized boolean allFinished()
192 return queued == 0 && running == 0;
197 public static Jalview getInstance()
203 * main class for Jalview application
206 * open <em>filename</em>
208 public static void main(String[] args)
210 // setLogging(); // BH - for event debugging in JavaScript
211 instance = new Jalview();
212 instance.doMain(args);
215 private static void logClass(String name)
217 // BH - for event debugging in JavaScript
218 ConsoleHandler consoleHandler = new ConsoleHandler();
219 consoleHandler.setLevel(Level.ALL);
220 Logger logger = Logger.getLogger(name);
221 logger.setLevel(Level.ALL);
222 logger.addHandler(consoleHandler);
225 @SuppressWarnings("unused")
226 private static void setLogging()
228 // BH - for event debugging in JavaScript (Java mode only)
229 if (!(/** @j2sNative true ||*/false))
231 Logger.getLogger("").setLevel(Level.ALL);
232 logClass("java.awt.EventDispatchThread");
233 logClass("java.awt.EventQueue");
234 logClass("java.awt.Component");
235 logClass("java.awt.focus.Component");
236 logClass("java.awt.focus.DefaultKeyboardFocusManager");
247 void doMain(String[] args)
252 System.setSecurityManager(null);
256 .println("Java version: " + System.getProperty("java.version"));
257 System.out.println(System.getProperty("os.arch") + " "
258 + System.getProperty("os.name") + " "
259 + System.getProperty("os.version"));
261 ArgsParser aparser = new ArgsParser(args);
262 boolean headless = false;
264 String usrPropsFile = aparser.getValue("props");
265 Cache.loadProperties(usrPropsFile); // must do this before
266 if (usrPropsFile != null)
269 "CMD [-props " + usrPropsFile + "] executed successfully!");
273 * BH 2018 ignoring this section for JS
278 if (aparser.contains("help") || aparser.contains("h"))
283 if (aparser.contains("nodisplay") || aparser.contains("nogui")
284 || aparser.contains("headless"))
286 System.setProperty("java.awt.headless", "true");
291 final String jabawsUrl = aparser.getValue("jabaws");
292 if (jabawsUrl != null)
296 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
298 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
299 } catch (MalformedURLException e)
302 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
307 String defs = aparser.getValue("setprop");
310 int p = defs.indexOf('=');
313 System.err.println("Ignoring invalid setprop argument : " + defs);
317 System.out.println("Executing setprop argument: " + defs);
318 // DISABLED FOR SECURITY REASONS
319 // TODO: add a property to allow properties to be overriden by cli args
320 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
322 defs = aparser.getValue("setprop");
324 if (System.getProperty("java.awt.headless") != null
325 && System.getProperty("java.awt.headless").equals("true"))
329 System.setProperty("http.agent",
330 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
334 } catch (NoClassDefFoundError error)
336 error.printStackTrace();
337 System.out.println("\nEssential logging libraries not found."
338 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
346 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
347 } catch (Exception ex)
349 System.err.println("Unexpected Look and Feel Exception");
350 ex.printStackTrace();
352 if (Platform.isAMac())
355 LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
357 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
359 System.setProperty("apple.laf.useScreenMenuBar", "true");
360 if (lookAndFeel != null)
364 UIManager.setLookAndFeel(lookAndFeel);
365 } catch (Throwable e)
368 "Failed to set QuaQua look and feel: " + e.toString());
371 if (lookAndFeel == null || !(lookAndFeel.getClass()
372 .isAssignableFrom(UIManager.getLookAndFeel().getClass()))
373 || !UIManager.getLookAndFeel().getClass().toString()
374 .toLowerCase().contains("quaqua"))
379 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
380 UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
381 } catch (Throwable e)
384 "Failed to reset look and feel: " + e.toString());
390 * configure 'full' SO model if preferences say to,
391 * else use the default (SO Lite)
393 if (Cache.getDefault("USE_FULL_SO", false))
395 SequenceOntologyFactory.setInstance(new SequenceOntology());
400 desktop = new Desktop()
404 // protected void processEvent(AWTEvent e) {
405 // System.out.println("Jalview.java " + e);
406 // super.processEvent(e);
410 desktop.setInBatchMode(true); // indicate we are starting up
411 desktop.setVisible(true);
414 * BH 2018 JS bypass this section
420 desktop.startServiceDiscovery();
421 if (!aparser.contains("nousagestats"))
423 startUsageStats(desktop);
427 System.err.println("CMD [-nousagestats] executed successfully!");
430 if (!aparser.contains("noquestionnaire"))
432 String url = aparser.getValue("questionnaire");
435 // Start the desktop questionnaire prompter with the specified
437 Cache.log.debug("Starting questionnaire url at " + url);
438 desktop.checkForQuestionnaire(url);
439 System.out.println("CMD questionnaire[-" + url
440 + "] executed successfully!");
444 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
446 // Start the desktop questionnaire prompter with the specified
449 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
451 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
453 "Starting questionnaire with default url: " + defurl);
454 desktop.checkForQuestionnaire(defurl);
461 .println("CMD [-noquestionnaire] executed successfully!");
464 if (!aparser.contains("nonews"))
466 desktop.checkForNews();
469 BioJsHTMLOutput.updateBioJS();
473 String file = null, data = null;
474 FileFormatI format = null;
475 DataSourceType protocol = null;
476 FileLoader fileLoader = new FileLoader(!headless);
477 Vector<String> getFeatures = null; // vector of das source nicknames to
481 String groovyscript = null; // script to execute after all loading is
482 // completed one way or another
483 // extract groovy argument and execute if necessary
484 groovyscript = aparser.getValue("groovy", true);
485 file = aparser.getValue("open", true);
487 if (file == null && desktop == null)
489 System.out.println("No files to open!");
492 String vamsasImport = aparser.getValue("vdoc");
493 String vamsasSession = aparser.getValue("vsess");
494 if (vamsasImport != null || vamsasSession != null)
496 if (desktop == null || headless)
499 "Headless vamsas sessions not yet supported. Sorry.");
502 // if we have a file, start a new session and import it.
503 boolean inSession = false;
504 if (vamsasImport != null)
508 DataSourceType viprotocol = AppletFormatAdapter
509 .checkProtocol(vamsasImport);
510 if (viprotocol == DataSourceType.FILE)
512 inSession = desktop.vamsasImport(new File(vamsasImport));
514 else if (viprotocol == DataSourceType.URL)
516 inSession = desktop.vamsasImport(new URL(vamsasImport));
519 } catch (Exception e)
521 System.err.println("Exeption when importing " + vamsasImport
522 + " as a vamsas document.");
527 System.err.println("Failed to import " + vamsasImport
528 + " as a vamsas document.");
532 System.out.println("Imported Successfully into new session "
533 + desktop.getVamsasApplication().getCurrentSession());
536 if (vamsasSession != null)
538 if (vamsasImport != null)
540 // close the newly imported session and import the Jalview specific
541 // remnants into the new session later on.
542 desktop.vamsasStop_actionPerformed(null);
544 // now join the new session
547 if (desktop.joinVamsasSession(vamsasSession))
550 "Successfully joined vamsas session " + vamsasSession);
554 System.err.println("WARNING: Failed to join vamsas session "
557 } catch (Exception e)
560 "ERROR: Failed to join vamsas session " + vamsasSession);
563 if (vamsasImport != null)
565 // the Jalview specific remnants can now be imported into the new
566 // session at the user's leisure.
568 "Skipping Push for import of data into existing vamsas session."); // TODO:
573 // desktop.getVamsasApplication().push_update();
578 // Finally, deal with the remaining input data.
583 desktop.setProgressBar(
585 .getString("status.processing_commandline_args"),
586 progress = System.currentTimeMillis());
588 System.out.println("CMD [-open " + file + "] executed successfully!");
590 if (!isJS() && !file.startsWith("http://"))
592 if (!(new File(file)).exists())
594 System.out.println("Can't find " + file);
602 protocol = AppletFormatAdapter.checkProtocol(file);
606 format = new IdentifyFile().identify(file, protocol);
607 } catch (FileFormatException e1)
612 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
616 System.out.println("error");
620 setCurrentAlignFrame(af);
621 data = aparser.getValue("colour", true);
624 data.replaceAll("%20", " ");
626 ColourSchemeI cs = ColourSchemeProperty
627 .getColourScheme(af.getViewport().getAlignment(), data);
632 "CMD [-color " + data + "] executed successfully!");
637 // Must maintain ability to use the groups flag
638 data = aparser.getValue("groups", true);
641 af.parseFeaturesFile(data,
642 AppletFormatAdapter.checkProtocol(data));
643 // System.out.println("Added " + data);
645 "CMD groups[-" + data + "] executed successfully!");
647 data = aparser.getValue("features", true);
650 af.parseFeaturesFile(data,
651 AppletFormatAdapter.checkProtocol(data));
652 // System.out.println("Added " + data);
654 "CMD [-features " + data + "] executed successfully!");
657 data = aparser.getValue("annotations", true);
660 af.loadJalviewDataFile(data, null, null, null);
661 // System.out.println("Added " + data);
663 "CMD [-annotations " + data + "] executed successfully!");
665 // set or clear the sortbytree flag.
666 if (aparser.contains("sortbytree"))
668 af.getViewport().setSortByTree(true);
669 if (af.getViewport().getSortByTree())
671 System.out.println("CMD [-sortbytree] executed successfully!");
674 if (aparser.contains("no-annotation"))
676 af.getViewport().setShowAnnotation(false);
677 if (!af.getViewport().isShowAnnotation())
679 System.out.println("CMD no-annotation executed successfully!");
682 if (aparser.contains("nosortbytree"))
684 af.getViewport().setSortByTree(false);
685 if (!af.getViewport().getSortByTree())
688 .println("CMD [-nosortbytree] executed successfully!");
691 data = aparser.getValue("tree", true);
697 "CMD [-tree " + data + "] executed successfully!");
698 NewickFile nf = new NewickFile(data,
699 AppletFormatAdapter.checkProtocol(data));
701 .setCurrentTree(af.showNewickTree(nf, data).getTree());
702 } catch (IOException ex)
704 System.err.println("Couldn't add tree " + data);
705 ex.printStackTrace(System.err);
708 // TODO - load PDB structure(s) to alignment JAL-629
709 // (associate with identical sequence in alignment, or a specified
712 getFeatures = checkDasArguments(aparser);
713 if (af != null && getFeatures != null)
715 FeatureFetcher ff = startFeatureFetching(getFeatures);
718 while (!ff.allFinished() || af.operationInProgress())
720 // wait around until fetching is finished.
724 } catch (Exception e)
730 getFeatures = null; // have retrieved features - forget them now.
732 if (groovyscript != null)
734 // Execute the groovy script after we've done all the rendering stuff
735 // and before any images or figures are generated.
736 System.out.println("Executing script " + groovyscript);
737 executeGroovyScript(groovyscript, af);
738 System.out.println("CMD groovy[" + groovyscript
739 + "] executed successfully!");
742 String imageName = "unnamed.png";
743 while (aparser.getSize() > 1)
745 String outputFormat = aparser.nextValue();
746 file = aparser.nextValue();
748 if (outputFormat.equalsIgnoreCase("png"))
750 af.createPNG(new File(file));
751 imageName = (new File(file)).getName();
752 System.out.println("Creating PNG image: " + file);
755 else if (outputFormat.equalsIgnoreCase("svg"))
757 File imageFile = new File(file);
758 imageName = imageFile.getName();
759 af.createSVG(imageFile);
760 System.out.println("Creating SVG image: " + file);
763 else if (outputFormat.equalsIgnoreCase("html"))
765 File imageFile = new File(file);
766 imageName = imageFile.getName();
767 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
768 htmlSVG.exportHTML(file);
770 System.out.println("Creating HTML image: " + file);
773 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
777 System.err.println("The output html file must not be null");
782 BioJsHTMLOutput.refreshVersionInfo(
783 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
784 } catch (URISyntaxException e)
788 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
789 bjs.exportHTML(file);
791 .println("Creating BioJS MSA Viwer HTML file: " + file);
794 else if (outputFormat.equalsIgnoreCase("imgMap"))
796 af.createImageMap(new File(file), imageName);
797 System.out.println("Creating image map: " + file);
800 else if (outputFormat.equalsIgnoreCase("eps"))
802 File outputFile = new File(file);
804 "Creating EPS file: " + outputFile.getAbsolutePath());
805 af.createEPS(outputFile);
809 af.saveAlignment(file, format);
810 if (af.isSaveAlignmentSuccessful())
812 System.out.println("Written alignment in " + format
813 + " format to " + file);
817 System.out.println("Error writing file " + file + " in "
818 + format + " format!!");
823 while (aparser.getSize() > 0)
825 System.out.println("Unknown arg: " + aparser.nextValue());
829 AlignFrame startUpAlframe = null;
830 // We'll only open the default file if the desktop is visible.
832 // ////////////////////
834 if (/** @j2sNative false && */ // BH 2018
835 !headless && file == null && vamsasImport == null
836 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
838 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
839 jalview.bin.Cache.getDefault("www.jalview.org",
840 "http://www.jalview.org")
841 + "/examples/exampleFile_2_7.jar");
843 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
845 // hardwire upgrade of the startup file
846 file.replace("_2_3.jar", "_2_7.jar");
847 // and remove the stale setting
848 jalview.bin.Cache.removeProperty("STARTUP_FILE");
851 protocol = DataSourceType.FILE;
853 if (file.indexOf("http:") > -1)
855 protocol = DataSourceType.URL;
858 if (file.endsWith(".jar"))
860 format = FileFormat.Jalview;
866 format = new IdentifyFile().identify(file, protocol);
867 } catch (FileFormatException e)
873 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
875 getFeatures = checkDasArguments(aparser);
876 // extract groovy arguments before anything else.
878 // If the user has specified features to be retrieved,
879 // or a groovy script to be executed, do them if they
880 // haven't been done already
881 // fetch features for the default alignment
882 if (getFeatures != null)
884 if (startUpAlframe != null)
886 startFeatureFetching(getFeatures);
889 // Once all other stuff is done, execute any groovy scripts (in order)
890 if (groovyscript != null)
892 if (Cache.groovyJarsPresent())
894 System.out.println("Executing script " + groovyscript);
895 executeGroovyScript(groovyscript, startUpAlframe);
900 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
904 // and finally, turn off batch mode indicator - if the desktop still exists
909 desktop.setProgressBar(null, progress);
911 desktop.setInBatchMode(false);
915 private static void showUsage()
918 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
919 + "-nodisplay\tRun Jalview without User Interface.\n"
920 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
921 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
922 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
923 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
924 + "-features FILE\tUse the given file to mark features on the alignment.\n"
925 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
926 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
927 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
928 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
929 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
930 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
931 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
932 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
933 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
934 + "-png FILE\tCreate PNG image FILE from alignment.\n"
935 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
936 + "-html FILE\tCreate HTML file from alignment.\n"
937 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
938 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
939 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
940 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
941 + "-noquestionnaire\tTurn off questionnaire check.\n"
942 + "-nonews\tTurn off check for Jalview news.\n"
943 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
944 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
946 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
947 // after all other properties files have been read\n\t
948 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
949 // passed in correctly)"
950 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
951 + "-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"
952 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
953 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
954 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
956 // "-vdoc vamsas-document\tImport vamsas document into new
957 // session or join existing session with same URN\n"
958 // + "-vses vamsas-session\tJoin session with given URN\n"
959 + "-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"
960 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
963 private static void startUsageStats(final Desktop desktop)
966 * start a User Config prompt asking if we can log usage statistics.
968 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
969 "USAGESTATS", "Jalview Usage Statistics",
970 "Do you want to help make Jalview better by enabling "
971 + "the collection of usage statistics with Google Analytics ?"
972 + "\n\n(you can enable or disable usage tracking in the preferences)",
979 "Initialising googletracker for usage stats.");
980 Cache.initGoogleTracker();
981 Cache.log.debug("Tracking enabled.");
988 Cache.log.debug("Not enabling Google Tracking.");
991 desktop.addDialogThread(prompter);
995 * Locate the given string as a file and pass it to the groovy interpreter.
997 * @param groovyscript
998 * the script to execute
999 * @param jalviewContext
1000 * the Jalview Desktop object passed in to the groovy binding as the
1003 private void executeGroovyScript(String groovyscript, AlignFrame af)
1006 * for scripts contained in files
1013 if (groovyscript.trim().equals("STDIN"))
1015 // read from stdin into a tempfile and execute it
1018 tfile = File.createTempFile("jalview", "groovy");
1019 PrintWriter outfile = new PrintWriter(
1020 new OutputStreamWriter(new FileOutputStream(tfile)));
1021 BufferedReader br = new BufferedReader(
1022 new InputStreamReader(System.in));
1024 while ((line = br.readLine()) != null)
1026 outfile.write(line + "\n");
1032 } catch (Exception ex)
1034 System.err.println("Failed to read from STDIN into tempfile "
1035 + ((tfile == null) ? "(tempfile wasn't created)"
1036 : tfile.toString()));
1037 ex.printStackTrace();
1042 sfile = tfile.toURI().toURL();
1043 } catch (Exception x)
1046 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1048 x.printStackTrace();
1056 sfile = new URI(groovyscript).toURL();
1057 } catch (Exception x)
1059 tfile = new File(groovyscript);
1060 if (!tfile.exists())
1062 System.err.println("File '" + groovyscript + "' does not exist.");
1065 if (!tfile.canRead())
1067 System.err.println("File '" + groovyscript + "' cannot be read.");
1070 if (tfile.length() < 1)
1072 System.err.println("File '" + groovyscript + "' is empty.");
1077 sfile = tfile.getAbsoluteFile().toURI().toURL();
1078 } catch (Exception ex)
1080 System.err.println("Failed to create a file URL for "
1081 + tfile.getAbsoluteFile());
1088 Map<String, Object> vbinding = new HashMap<>();
1089 vbinding.put("Jalview", this);
1092 vbinding.put("currentAlFrame", af);
1094 Binding gbinding = new Binding(vbinding);
1095 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1096 gse.run(sfile.toString(), gbinding);
1097 if ("STDIN".equals(groovyscript))
1099 // delete temp file that we made -
1100 // only if it was successfully executed
1103 } catch (Exception e)
1105 System.err.println("Exception Whilst trying to execute file " + sfile
1106 + " as a groovy script.");
1107 e.printStackTrace(System.err);
1113 * Check commandline for any das server definitions or any fetchfrom switches
1115 * @return vector of DAS source nicknames to retrieve from
1117 private static Vector<String> checkDasArguments(ArgsParser aparser)
1119 Vector<String> source = null;
1121 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
1122 while ((data = aparser.getValue("dasserver", true)) != null)
1124 String nickname = null;
1126 int pos = data.indexOf('=');
1127 // determine capabilities
1130 nickname = data.substring(0, pos);
1132 url = data.substring(pos + 1);
1133 if (url != null && (url.startsWith("http:")
1134 || url.startsWith("sequence:http:")))
1136 if (nickname == null)
1140 if (locsources == null)
1148 locsources = locsources + nickname + "|" + url;
1150 "NOTE! dasserver parameter not yet really supported (got args of "
1151 + nickname + "|" + url);
1154 source = new Vector<>();
1156 source.addElement(nickname);
1159 "CMD [-dasserver " + data + "] executed successfully!");
1160 } // loop until no more server entries are found.
1161 if (locsources != null && locsources.indexOf('|') > -1)
1163 Cache.log.debug("Setting local source list in properties file to:\n"
1165 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
1167 while ((data = aparser.getValue("fetchfrom", true)) != null)
1169 System.out.println("adding source '" + data + "'");
1172 source = new Vector<>();
1174 source.addElement(data);
1180 * start a feature fetcher for every alignment frame
1184 private FeatureFetcher startFeatureFetching(
1185 final Vector<String> dasSources)
1187 FeatureFetcher ff = new FeatureFetcher();
1188 AlignFrame afs[] = Desktop.getAlignFrames();
1189 if (afs == null || afs.length == 0)
1193 for (int i = 0; i < afs.length; i++)
1195 ff.addFetcher(afs[i], dasSources);
1200 public static boolean isHeadlessMode()
1202 String isheadless = System.getProperty("java.awt.headless");
1203 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1210 public AlignFrame[] getAlignFrames()
1212 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1213 : Desktop.getAlignFrames();
1218 * Quit method delegates to Desktop.quit - unless running in headless mode
1219 * when it just ends the JVM
1223 if (desktop != null)
1233 public static AlignFrame getCurrentAlignFrame()
1235 return Jalview.currentAlignFrame;
1238 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1240 Jalview.currentAlignFrame = currentAlignFrame;