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;
104 if (!Platform.isJS())
106 // grab all the rights we can the JVM
107 Policy.setPolicy(new Policy()
110 public PermissionCollection getPermissions(CodeSource codesource)
112 Permissions perms = new Permissions();
113 perms.add(new AllPermission());
118 public void refresh()
127 * keep track of feature fetching tasks.
135 * TODO: generalise to track all jalview events to orchestrate batch
139 private int queued = 0;
141 private int running = 0;
143 public FeatureFetcher()
148 public void addFetcher(final AlignFrame af,
149 final Vector<String> dasSources)
151 final long id = System.currentTimeMillis();
153 final FeatureFetcher us = this;
154 new Thread(new Runnable()
166 af.setProgressBar(MessageManager
167 .getString("status.das_features_being_retrived"), id);
168 af.featureSettings_actionPerformed(null);
169 af.setProgressBar(null, id);
178 public synchronized boolean allFinished()
180 return queued == 0 && running == 0;
185 public static Jalview getInstance()
191 * main class for Jalview application
194 * open <em>filename</em>
196 public static void main(String[] args)
198 // setLogging(); // BH - for event debugging in JavaScript
199 instance = new Jalview();
200 instance.doMain(args);
203 private static void logClass(String name)
205 // BH - for event debugging in JavaScript
206 ConsoleHandler consoleHandler = new ConsoleHandler();
207 consoleHandler.setLevel(Level.ALL);
208 Logger logger = Logger.getLogger(name);
209 logger.setLevel(Level.ALL);
210 logger.addHandler(consoleHandler);
213 @SuppressWarnings("unused")
214 private static void setLogging()
216 // BH - for event debugging in JavaScript (Java mode only)
217 if (!Platform.isJS())
219 Logger.getLogger("").setLevel(Level.ALL);
220 logClass("java.awt.EventDispatchThread");
221 logClass("java.awt.EventQueue");
222 logClass("java.awt.Component");
223 logClass("java.awt.focus.Component");
224 logClass("java.awt.focus.DefaultKeyboardFocusManager");
235 void doMain(String[] args)
238 if (!Platform.isJS())
240 System.setSecurityManager(null);
244 .println("Java version: " + System.getProperty("java.version"));
245 System.out.println(System.getProperty("os.arch") + " "
246 + System.getProperty("os.name") + " "
247 + System.getProperty("os.version"));
249 ArgsParser aparser = new ArgsParser(args);
250 boolean headless = false;
252 String usrPropsFile = aparser.getValue("props");
253 Cache.loadProperties(usrPropsFile); // must do this before
254 if (usrPropsFile != null)
257 "CMD [-props " + usrPropsFile + "] executed successfully!");
260 if (!Platform.isJS()) {
261 if (aparser.contains("help") || aparser.contains("h"))
266 if (aparser.contains("nodisplay") || aparser.contains("nogui")
267 || aparser.contains("headless"))
269 System.setProperty("java.awt.headless", "true");
274 final String jabawsUrl = aparser.getValue("jabaws");
275 if (jabawsUrl != null)
279 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
281 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
282 } catch (MalformedURLException e)
285 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
290 String defs = aparser.getValue("setprop");
293 int p = defs.indexOf('=');
296 System.err.println("Ignoring invalid setprop argument : " + defs);
300 System.out.println("Executing setprop argument: " + defs);
301 // DISABLED FOR SECURITY REASONS
302 // TODO: add a property to allow properties to be overriden by cli args
303 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
305 defs = aparser.getValue("setprop");
307 if (System.getProperty("java.awt.headless") != null
308 && System.getProperty("java.awt.headless").equals("true"))
312 System.setProperty("http.agent",
313 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
317 } catch (NoClassDefFoundError error)
319 error.printStackTrace();
320 System.out.println("\nEssential logging libraries not found."
321 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
329 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
330 } catch (Exception ex)
332 System.err.println("Unexpected Look and Feel Exception");
333 ex.printStackTrace();
335 if (Platform.isAMacAndNotJS())
338 LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
340 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
342 System.setProperty("apple.laf.useScreenMenuBar", "true");
343 if (lookAndFeel != null)
347 UIManager.setLookAndFeel(lookAndFeel);
348 } catch (Throwable e)
351 "Failed to set QuaQua look and feel: " + e.toString());
354 if (lookAndFeel == null || !(lookAndFeel.getClass()
355 .isAssignableFrom(UIManager.getLookAndFeel().getClass()))
356 || !UIManager.getLookAndFeel().getClass().toString()
357 .toLowerCase().contains("quaqua"))
362 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
363 UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
364 } catch (Throwable e)
367 "Failed to reset look and feel: " + e.toString());
373 * configure 'full' SO model if preferences say to,
374 * else use the default (SO Lite)
376 if (Cache.getDefault("USE_FULL_SO", false))
378 SequenceOntologyFactory.setInstance(new SequenceOntology());
383 desktop = new Desktop()
387 // protected void processEvent(AWTEvent e) {
388 // System.out.println("Jalview.java " + e);
389 // super.processEvent(e);
393 desktop.setInBatchMode(true); // indicate we are starting up
394 desktop.setVisible(true);
397 if (!Platform.isJS()) {
398 desktop.startServiceDiscovery();
399 if (!aparser.contains("nousagestats"))
401 startUsageStats(desktop);
405 System.err.println("CMD [-nousagestats] executed successfully!");
408 if (!aparser.contains("noquestionnaire"))
410 String url = aparser.getValue("questionnaire");
413 // Start the desktop questionnaire prompter with the specified
415 Cache.log.debug("Starting questionnaire url at " + url);
416 desktop.checkForQuestionnaire(url);
417 System.out.println("CMD questionnaire[-" + url
418 + "] executed successfully!");
422 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
424 // Start the desktop questionnaire prompter with the specified
427 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
429 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
431 "Starting questionnaire with default url: " + defurl);
432 desktop.checkForQuestionnaire(defurl);
439 .println("CMD [-noquestionnaire] executed successfully!");
442 if (!aparser.contains("nonews"))
444 desktop.checkForNews();
447 BioJsHTMLOutput.updateBioJS();
451 String file = null, data = null;
452 FileFormatI format = null;
453 DataSourceType protocol = null;
454 FileLoader fileLoader = new FileLoader(!headless);
455 Vector<String> getFeatures = null; // vector of das source nicknames to
459 String groovyscript = null; // script to execute after all loading is
460 // completed one way or another
461 // extract groovy argument and execute if necessary
462 groovyscript = aparser.getValue("groovy", true);
463 file = aparser.getValue("open", true);
465 if (file == null && desktop == null)
467 System.out.println("No files to open!");
470 String vamsasImport = aparser.getValue("vdoc");
471 String vamsasSession = aparser.getValue("vsess");
472 if (vamsasImport != null || vamsasSession != null)
474 if (desktop == null || headless)
477 "Headless vamsas sessions not yet supported. Sorry.");
480 // if we have a file, start a new session and import it.
481 boolean inSession = false;
482 if (vamsasImport != null)
486 DataSourceType viprotocol = AppletFormatAdapter
487 .checkProtocol(vamsasImport);
488 if (viprotocol == DataSourceType.FILE)
490 inSession = desktop.vamsasImport(new File(vamsasImport));
492 else if (viprotocol == DataSourceType.URL)
494 inSession = desktop.vamsasImport(new URL(vamsasImport));
497 } catch (Exception e)
499 System.err.println("Exeption when importing " + vamsasImport
500 + " as a vamsas document.");
505 System.err.println("Failed to import " + vamsasImport
506 + " as a vamsas document.");
510 System.out.println("Imported Successfully into new session "
511 + desktop.getVamsasApplication().getCurrentSession());
514 if (vamsasSession != null)
516 if (vamsasImport != null)
518 // close the newly imported session and import the Jalview specific
519 // remnants into the new session later on.
520 desktop.vamsasStop_actionPerformed(null);
522 // now join the new session
525 if (desktop.joinVamsasSession(vamsasSession))
528 "Successfully joined vamsas session " + vamsasSession);
532 System.err.println("WARNING: Failed to join vamsas session "
535 } catch (Exception e)
538 "ERROR: Failed to join vamsas session " + vamsasSession);
541 if (vamsasImport != null)
543 // the Jalview specific remnants can now be imported into the new
544 // session at the user's leisure.
546 "Skipping Push for import of data into existing vamsas session."); // TODO:
551 // desktop.getVamsasApplication().push_update();
556 // Finally, deal with the remaining input data.
561 desktop.setProgressBar(
563 .getString("status.processing_commandline_args"),
564 progress = System.currentTimeMillis());
566 System.out.println("CMD [-open " + file + "] executed successfully!");
568 if (!Platform.isJS() && !file.startsWith("http://"))
570 if (!(new File(file)).exists())
572 System.out.println("Can't find " + file);
580 protocol = AppletFormatAdapter.checkProtocol(file);
584 format = new IdentifyFile().identify(file, protocol);
585 } catch (FileFormatException e1)
590 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
594 System.out.println("error");
598 setCurrentAlignFrame(af);
599 data = aparser.getValue("colour", true);
602 data.replaceAll("%20", " ");
604 ColourSchemeI cs = ColourSchemeProperty
605 .getColourScheme(af.getViewport().getAlignment(), data);
610 "CMD [-color " + data + "] executed successfully!");
615 // Must maintain ability to use the groups flag
616 data = aparser.getValue("groups", true);
619 af.parseFeaturesFile(data,
620 AppletFormatAdapter.checkProtocol(data));
621 // System.out.println("Added " + data);
623 "CMD groups[-" + data + "] executed successfully!");
625 data = aparser.getValue("features", true);
628 af.parseFeaturesFile(data,
629 AppletFormatAdapter.checkProtocol(data));
630 // System.out.println("Added " + data);
632 "CMD [-features " + data + "] executed successfully!");
635 data = aparser.getValue("annotations", true);
638 af.loadJalviewDataFile(data, null, null, null);
639 // System.out.println("Added " + data);
641 "CMD [-annotations " + data + "] executed successfully!");
643 // set or clear the sortbytree flag.
644 if (aparser.contains("sortbytree"))
646 af.getViewport().setSortByTree(true);
647 if (af.getViewport().getSortByTree())
649 System.out.println("CMD [-sortbytree] executed successfully!");
652 if (aparser.contains("no-annotation"))
654 af.getViewport().setShowAnnotation(false);
655 if (!af.getViewport().isShowAnnotation())
657 System.out.println("CMD no-annotation executed successfully!");
660 if (aparser.contains("nosortbytree"))
662 af.getViewport().setSortByTree(false);
663 if (!af.getViewport().getSortByTree())
666 .println("CMD [-nosortbytree] executed successfully!");
669 data = aparser.getValue("tree", true);
675 "CMD [-tree " + data + "] executed successfully!");
676 NewickFile nf = new NewickFile(data,
677 AppletFormatAdapter.checkProtocol(data));
679 .setCurrentTree(af.showNewickTree(nf, data).getTree());
680 } catch (IOException ex)
682 System.err.println("Couldn't add tree " + data);
683 ex.printStackTrace(System.err);
686 // TODO - load PDB structure(s) to alignment JAL-629
687 // (associate with identical sequence in alignment, or a specified
690 getFeatures = checkDasArguments(aparser);
691 if (af != null && getFeatures != null)
693 FeatureFetcher ff = startFeatureFetching(getFeatures);
696 while (!ff.allFinished() || af.operationInProgress())
698 // wait around until fetching is finished.
702 } catch (Exception e)
708 getFeatures = null; // have retrieved features - forget them now.
710 if (groovyscript != null)
712 // Execute the groovy script after we've done all the rendering stuff
713 // and before any images or figures are generated.
714 System.out.println("Executing script " + groovyscript);
715 executeGroovyScript(groovyscript, af);
716 System.out.println("CMD groovy[" + groovyscript
717 + "] executed successfully!");
720 String imageName = "unnamed.png";
721 while (aparser.getSize() > 1)
723 String outputFormat = aparser.nextValue();
724 file = aparser.nextValue();
726 if (outputFormat.equalsIgnoreCase("png"))
728 af.createPNG(new File(file));
729 imageName = (new File(file)).getName();
730 System.out.println("Creating PNG image: " + file);
733 else if (outputFormat.equalsIgnoreCase("svg"))
735 File imageFile = new File(file);
736 imageName = imageFile.getName();
737 af.createSVG(imageFile);
738 System.out.println("Creating SVG image: " + file);
741 else if (outputFormat.equalsIgnoreCase("html"))
743 File imageFile = new File(file);
744 imageName = imageFile.getName();
745 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
746 htmlSVG.exportHTML(file);
748 System.out.println("Creating HTML image: " + file);
751 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
755 System.err.println("The output html file must not be null");
760 BioJsHTMLOutput.refreshVersionInfo(
761 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
762 } catch (URISyntaxException e)
766 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
767 bjs.exportHTML(file);
769 .println("Creating BioJS MSA Viwer HTML file: " + file);
772 else if (outputFormat.equalsIgnoreCase("imgMap"))
774 af.createImageMap(new File(file), imageName);
775 System.out.println("Creating image map: " + file);
778 else if (outputFormat.equalsIgnoreCase("eps"))
780 File outputFile = new File(file);
782 "Creating EPS file: " + outputFile.getAbsolutePath());
783 af.createEPS(outputFile);
787 af.saveAlignment(file, format);
788 if (af.isSaveAlignmentSuccessful())
790 System.out.println("Written alignment in " + format
791 + " format to " + file);
795 System.out.println("Error writing file " + file + " in "
796 + format + " format!!");
801 while (aparser.getSize() > 0)
803 System.out.println("Unknown arg: " + aparser.nextValue());
807 AlignFrame startUpAlframe = null;
808 // We'll only open the default file if the desktop is visible.
810 // ////////////////////
812 if (!Platform.isJS() && !headless && file == null && vamsasImport == null
813 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
815 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
816 jalview.bin.Cache.getDefault("www.jalview.org",
817 "http://www.jalview.org")
818 + "/examples/exampleFile_2_7.jar");
820 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
822 // hardwire upgrade of the startup file
823 file.replace("_2_3.jar", "_2_7.jar");
824 // and remove the stale setting
825 jalview.bin.Cache.removeProperty("STARTUP_FILE");
828 protocol = DataSourceType.FILE;
830 if (file.indexOf("http:") > -1)
832 protocol = DataSourceType.URL;
835 if (file.endsWith(".jar"))
837 format = FileFormat.Jalview;
843 format = new IdentifyFile().identify(file, protocol);
844 } catch (FileFormatException e)
850 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
852 getFeatures = checkDasArguments(aparser);
853 // extract groovy arguments before anything else.
855 // If the user has specified features to be retrieved,
856 // or a groovy script to be executed, do them if they
857 // haven't been done already
858 // fetch features for the default alignment
859 if (getFeatures != null)
861 if (startUpAlframe != null)
863 startFeatureFetching(getFeatures);
866 // Once all other stuff is done, execute any groovy scripts (in order)
867 if (groovyscript != null)
869 if (Cache.groovyJarsPresent())
871 System.out.println("Executing script " + groovyscript);
872 executeGroovyScript(groovyscript, startUpAlframe);
877 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
881 // and finally, turn off batch mode indicator - if the desktop still exists
886 desktop.setProgressBar(null, progress);
888 desktop.setInBatchMode(false);
892 private static void showUsage()
895 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
896 + "-nodisplay\tRun Jalview without User Interface.\n"
897 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
898 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
899 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
900 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
901 + "-features FILE\tUse the given file to mark features on the alignment.\n"
902 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
903 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
904 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
905 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
906 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
907 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
908 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
909 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
910 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
911 + "-png FILE\tCreate PNG image FILE from alignment.\n"
912 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
913 + "-html FILE\tCreate HTML file from alignment.\n"
914 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
915 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
916 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
917 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
918 + "-noquestionnaire\tTurn off questionnaire check.\n"
919 + "-nonews\tTurn off check for Jalview news.\n"
920 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
921 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
923 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
924 // after all other properties files have been read\n\t
925 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
926 // passed in correctly)"
927 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
928 + "-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"
929 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
930 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
931 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
933 // "-vdoc vamsas-document\tImport vamsas document into new
934 // session or join existing session with same URN\n"
935 // + "-vses vamsas-session\tJoin session with given URN\n"
936 + "-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"
937 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
940 private static void startUsageStats(final Desktop desktop)
943 * start a User Config prompt asking if we can log usage statistics.
945 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
946 "USAGESTATS", "Jalview Usage Statistics",
947 "Do you want to help make Jalview better by enabling "
948 + "the collection of usage statistics with Google Analytics ?"
949 + "\n\n(you can enable or disable usage tracking in the preferences)",
956 "Initialising googletracker for usage stats.");
957 Cache.initGoogleTracker();
958 Cache.log.debug("Tracking enabled.");
965 Cache.log.debug("Not enabling Google Tracking.");
968 desktop.addDialogThread(prompter);
972 * Locate the given string as a file and pass it to the groovy interpreter.
974 * @param groovyscript
975 * the script to execute
976 * @param jalviewContext
977 * the Jalview Desktop object passed in to the groovy binding as the
980 private void executeGroovyScript(String groovyscript, AlignFrame af)
983 * for scripts contained in files
990 if (groovyscript.trim().equals("STDIN"))
992 // read from stdin into a tempfile and execute it
995 tfile = File.createTempFile("jalview", "groovy");
996 PrintWriter outfile = new PrintWriter(
997 new OutputStreamWriter(new FileOutputStream(tfile)));
998 BufferedReader br = new BufferedReader(
999 new InputStreamReader(System.in));
1001 while ((line = br.readLine()) != null)
1003 outfile.write(line + "\n");
1009 } catch (Exception ex)
1011 System.err.println("Failed to read from STDIN into tempfile "
1012 + ((tfile == null) ? "(tempfile wasn't created)"
1013 : tfile.toString()));
1014 ex.printStackTrace();
1019 sfile = tfile.toURI().toURL();
1020 } catch (Exception x)
1023 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1025 x.printStackTrace();
1033 sfile = new URI(groovyscript).toURL();
1034 } catch (Exception x)
1036 tfile = new File(groovyscript);
1037 if (!tfile.exists())
1039 System.err.println("File '" + groovyscript + "' does not exist.");
1042 if (!tfile.canRead())
1044 System.err.println("File '" + groovyscript + "' cannot be read.");
1047 if (tfile.length() < 1)
1049 System.err.println("File '" + groovyscript + "' is empty.");
1054 sfile = tfile.getAbsoluteFile().toURI().toURL();
1055 } catch (Exception ex)
1057 System.err.println("Failed to create a file URL for "
1058 + tfile.getAbsoluteFile());
1065 Map<String, Object> vbinding = new HashMap<>();
1066 vbinding.put("Jalview", this);
1069 vbinding.put("currentAlFrame", af);
1071 Binding gbinding = new Binding(vbinding);
1072 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1073 gse.run(sfile.toString(), gbinding);
1074 if ("STDIN".equals(groovyscript))
1076 // delete temp file that we made -
1077 // only if it was successfully executed
1080 } catch (Exception e)
1082 System.err.println("Exception Whilst trying to execute file " + sfile
1083 + " as a groovy script.");
1084 e.printStackTrace(System.err);
1090 * Check commandline for any das server definitions or any fetchfrom switches
1092 * @return vector of DAS source nicknames to retrieve from
1094 private static Vector<String> checkDasArguments(ArgsParser aparser)
1096 Vector<String> source = null;
1098 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
1099 while ((data = aparser.getValue("dasserver", true)) != null)
1101 String nickname = null;
1103 int pos = data.indexOf('=');
1104 // determine capabilities
1107 nickname = data.substring(0, pos);
1109 url = data.substring(pos + 1);
1110 if (url != null && (url.startsWith("http:")
1111 || url.startsWith("sequence:http:")))
1113 if (nickname == null)
1117 if (locsources == null)
1125 locsources = locsources + nickname + "|" + url;
1127 "NOTE! dasserver parameter not yet really supported (got args of "
1128 + nickname + "|" + url);
1131 source = new Vector<>();
1133 source.addElement(nickname);
1136 "CMD [-dasserver " + data + "] executed successfully!");
1137 } // loop until no more server entries are found.
1138 if (locsources != null && locsources.indexOf('|') > -1)
1140 Cache.log.debug("Setting local source list in properties file to:\n"
1142 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
1144 while ((data = aparser.getValue("fetchfrom", true)) != null)
1146 System.out.println("adding source '" + data + "'");
1149 source = new Vector<>();
1151 source.addElement(data);
1157 * start a feature fetcher for every alignment frame
1161 private FeatureFetcher startFeatureFetching(
1162 final Vector<String> dasSources)
1164 FeatureFetcher ff = new FeatureFetcher();
1165 AlignFrame afs[] = Desktop.getAlignFrames();
1166 if (afs == null || afs.length == 0)
1170 for (int i = 0; i < afs.length; i++)
1172 ff.addFetcher(afs[i], dasSources);
1177 public static boolean isHeadlessMode()
1179 String isheadless = System.getProperty("java.awt.headless");
1180 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1187 public AlignFrame[] getAlignFrames()
1189 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1190 : Desktop.getAlignFrames();
1195 * Quit method delegates to Desktop.quit - unless running in headless mode
1196 * when it just ends the JVM
1200 if (desktop != null)
1210 public static AlignFrame getCurrentAlignFrame()
1212 return Jalview.currentAlignFrame;
1215 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1217 Jalview.currentAlignFrame = currentAlignFrame;