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.util.Worker;
43 import jalview.ws.jws2.Jws2Discoverer;
45 import java.io.BufferedReader;
47 import java.io.FileOutputStream;
48 import java.io.IOException;
49 import java.io.InputStreamReader;
50 import java.io.OutputStreamWriter;
51 import java.io.PrintWriter;
52 import java.net.MalformedURLException;
54 import java.net.URISyntaxException;
56 import java.security.AllPermission;
57 import java.security.CodeSource;
58 import java.security.PermissionCollection;
59 import java.security.Permissions;
60 import java.security.Policy;
61 import java.util.ArrayList;
62 import java.util.Arrays;
63 import java.util.HashMap;
64 import java.util.List;
66 import java.util.Vector;
68 import javax.swing.LookAndFeel;
69 import javax.swing.UIManager;
71 import groovy.lang.Binding;
72 import groovy.util.GroovyScriptEngine;
75 * Main class for Jalview Application <br>
77 * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
80 * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
81 * jalview.bin.Jalview jalview.bin.Jalview
83 * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
84 * embellish '*' to e.g. '*.jar')
92 * singleton instance of this class
94 private static Jalview instance;
96 private Desktop desktop;
98 public static AlignFrame currentAlignFrame;
102 // grab all the rights we can the JVM
103 Policy.setPolicy(new Policy()
106 public PermissionCollection getPermissions(CodeSource codesource)
108 Permissions perms = new Permissions();
109 perms.add(new AllPermission());
114 public void refresh()
121 * keep track of feature fetching tasks.
129 * TODO: generalise to track all jalview events to orchestrate batch
133 private int queued = 0;
135 private int running = 0;
137 public FeatureFetcher()
142 public void addFetcher(final AlignFrame af,
143 final Vector<String> dasSources)
145 final long id = System.currentTimeMillis();
147 final FeatureFetcher us = this;
148 new Thread(new Runnable()
160 af.setProgressBar(MessageManager
161 .getString("status.das_features_being_retrived"), id);
162 af.featureSettings_actionPerformed(null);
163 af.setProgressBar(null, id);
172 public synchronized boolean allFinished()
174 return queued == 0 && running == 0;
179 public static Jalview getInstance()
185 * main class for Jalview application
188 * open <em>filename</em>
190 public static void main(String[] args)
192 float ONE_MB = 1048576f;
193 Runtime runtime = Runtime.getRuntime();
194 float maxMemory = runtime.maxMemory() / ONE_MB;
195 boolean is9or10 = System.getProperty("java.version").startsWith("10.")
196 || System.getProperty("java.version").startsWith("9.")
197 || System.getProperty("java.version").startsWith("10.")
198 || System.getProperty("java.version").startsWith("1.10.")
199 || System.getProperty("java.version").startsWith("1.9.");
200 if (maxMemory < 1024 * 14)
202 ArrayList<String> cmd = new ArrayList();
204 boolean dontspawn=false;
205 for (String r : args)
208 if (r.indexOf("-Xmx")>-1) {
216 String[] javargs=new String[1];
218 javargs = new String[2];
219 javargs[1] = "--add-modules=java.se.ee";
220 javargs[1] = "--illegal-access=WARN";
222 javargs[0]="-Xmx15G";
224 System.err.print("relaunching with 15G: ");
227 System.err.print(r + " ");
229 System.err.println("");
230 Worker worker = Worker.jalviewDesktopRunner(false,
231 cmd.toArray(new String[0]), 0, javargs);
235 while (worker.getExitValue() == null)
240 } catch (Exception q)
245 } catch (Exception q)
250 System.exit(worker.getExitValue());
254 List<String> rgs = new ArrayList();
255 rgs.addAll(Arrays.asList(args));
257 while (i < rgs.size())
259 if (rgs.get(i).indexOf("-Xmx") > -1)
268 instance = new Jalview();
269 instance.doMain(args);
275 void doMain(String[] args)
277 System.setSecurityManager(null);
279 .println("Java version: " + System.getProperty("java.version"));
280 System.out.println(System.getProperty("os.arch") + " "
281 + System.getProperty("os.name") + " "
282 + System.getProperty("os.version"));
284 ArgsParser aparser = new ArgsParser(args);
285 boolean headless = false;
287 if (aparser.contains("help") || aparser.contains("h"))
292 if (aparser.contains("nodisplay") || aparser.contains("nogui")
293 || aparser.contains("headless"))
295 System.setProperty("java.awt.headless", "true");
298 String usrPropsFile = aparser.getValue("props");
299 Cache.loadProperties(usrPropsFile); // must do this before
300 if (usrPropsFile != null)
303 "CMD [-props " + usrPropsFile + "] executed successfully!");
308 final String jabawsUrl = aparser.getValue("jabaws");
309 if (jabawsUrl != null)
313 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
315 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
316 } catch (MalformedURLException e)
319 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
323 String defs = aparser.getValue("setprop");
326 int p = defs.indexOf('=');
329 System.err.println("Ignoring invalid setprop argument : " + defs);
333 System.out.println("Executing setprop argument: " + defs);
334 // DISABLED FOR SECURITY REASONS
335 // TODO: add a property to allow properties to be overriden by cli args
336 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
338 defs = aparser.getValue("setprop");
340 if (System.getProperty("java.awt.headless") != null
341 && System.getProperty("java.awt.headless").equals("true"))
345 System.setProperty("http.agent",
346 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
350 } catch (NoClassDefFoundError error)
352 error.printStackTrace();
353 System.out.println("\nEssential logging libraries not found."
354 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
362 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
363 } catch (Exception ex)
365 System.err.println("Unexpected Look and Feel Exception");
366 ex.printStackTrace();
368 if (Platform.isAMac())
371 LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
373 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
375 System.setProperty("apple.laf.useScreenMenuBar", "true");
376 if (lookAndFeel != null)
380 UIManager.setLookAndFeel(lookAndFeel);
381 } catch (Throwable e)
384 "Failed to set QuaQua look and feel: " + e.toString());
387 if (lookAndFeel == null || !(lookAndFeel.getClass()
388 .isAssignableFrom(UIManager.getLookAndFeel().getClass()))
389 || !UIManager.getLookAndFeel().getClass().toString()
390 .toLowerCase().contains("quaqua"))
395 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
396 UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
397 } catch (Throwable e)
400 "Failed to reset look and feel: " + e.toString());
406 * configure 'full' SO model if preferences say to,
407 * else use the default (SO Lite)
409 if (Cache.getDefault("USE_FULL_SO", false))
411 SequenceOntologyFactory.setInstance(new SequenceOntology());
416 desktop = new Desktop();
417 desktop.setInBatchMode(true); // indicate we are starting up
418 desktop.setVisible(true);
419 desktop.startServiceDiscovery();
420 if (!aparser.contains("nousagestats"))
422 startUsageStats(desktop);
426 System.err.println("CMD [-nousagestats] executed successfully!");
429 if (!aparser.contains("noquestionnaire"))
431 String url = aparser.getValue("questionnaire");
434 // Start the desktop questionnaire prompter with the specified
436 Cache.log.debug("Starting questionnaire url at " + url);
437 desktop.checkForQuestionnaire(url);
439 "CMD questionnaire[-" + url + "] executed successfully!");
443 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
445 // Start the desktop questionnaire prompter with the specified
448 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
450 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
452 "Starting questionnaire with default url: " + defurl);
453 desktop.checkForQuestionnaire(defurl);
459 System.err.println("CMD [-noquestionnaire] executed successfully!");
462 if (!aparser.contains("nonews"))
464 desktop.checkForNews();
467 BioJsHTMLOutput.updateBioJS();
470 String file = null, data = null;
471 FileFormatI format = null;
472 DataSourceType protocol = null;
473 FileLoader fileLoader = new FileLoader(!headless);
474 Vector<String> getFeatures = null; // vector of das source nicknames to
478 String groovyscript = null; // script to execute after all loading is
479 // completed one way or another
480 // extract groovy argument and execute if necessary
481 groovyscript = aparser.getValue("groovy", true);
482 file = aparser.getValue("open", true);
484 if (file == null && desktop == null)
486 System.out.println("No files to open!");
489 String vamsasImport = aparser.getValue("vdoc");
490 String vamsasSession = aparser.getValue("vsess");
491 if (vamsasImport != null || vamsasSession != null)
493 if (desktop == null || headless)
496 "Headless vamsas sessions not yet supported. Sorry.");
499 // if we have a file, start a new session and import it.
500 boolean inSession = false;
501 if (vamsasImport != null)
505 DataSourceType viprotocol = AppletFormatAdapter
506 .checkProtocol(vamsasImport);
507 if (viprotocol == DataSourceType.FILE)
509 inSession = desktop.vamsasImport(new File(vamsasImport));
511 else if (viprotocol == DataSourceType.URL)
513 inSession = desktop.vamsasImport(new URL(vamsasImport));
516 } catch (Exception e)
518 System.err.println("Exeption when importing " + vamsasImport
519 + " as a vamsas document.");
524 System.err.println("Failed to import " + vamsasImport
525 + " as a vamsas document.");
529 System.out.println("Imported Successfully into new session "
530 + desktop.getVamsasApplication().getCurrentSession());
533 if (vamsasSession != null)
535 if (vamsasImport != null)
537 // close the newly imported session and import the Jalview specific
538 // remnants into the new session later on.
539 desktop.vamsasStop_actionPerformed(null);
541 // now join the new session
544 if (desktop.joinVamsasSession(vamsasSession))
547 "Successfully joined vamsas session " + vamsasSession);
551 System.err.println("WARNING: Failed to join vamsas session "
554 } catch (Exception e)
557 "ERROR: Failed to join vamsas session " + vamsasSession);
560 if (vamsasImport != null)
562 // the Jalview specific remnants can now be imported into the new
563 // session at the user's leisure.
565 "Skipping Push for import of data into existing vamsas session."); // TODO:
570 // desktop.getVamsasApplication().push_update();
575 // Finally, deal with the remaining input data.
580 desktop.setProgressBar(
582 .getString("status.processing_commandline_args"),
583 progress = System.currentTimeMillis());
585 System.out.println("CMD [-open " + file + "] executed successfully!");
587 if (!file.startsWith("http://"))
589 if (!(new File(file)).exists())
591 System.out.println("Can't find " + file);
599 protocol = AppletFormatAdapter.checkProtocol(file);
603 format = new IdentifyFile().identify(file, protocol);
604 } catch (FileFormatException e1)
609 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
613 System.out.println("error");
617 setCurrentAlignFrame(af);
618 data = aparser.getValue("colour", true);
621 data.replaceAll("%20", " ");
623 ColourSchemeI cs = ColourSchemeProperty
624 .getColourScheme(af.getViewport().getAlignment(), data);
629 "CMD [-color " + data + "] executed successfully!");
634 // Must maintain ability to use the groups flag
635 data = aparser.getValue("groups", true);
638 af.parseFeaturesFile(data,
639 AppletFormatAdapter.checkProtocol(data));
640 // System.out.println("Added " + data);
642 "CMD groups[-" + data + "] executed successfully!");
644 data = aparser.getValue("features", true);
647 af.parseFeaturesFile(data,
648 AppletFormatAdapter.checkProtocol(data));
649 // System.out.println("Added " + data);
651 "CMD [-features " + data + "] executed successfully!");
654 data = aparser.getValue("annotations", true);
657 af.loadJalviewDataFile(data, null, null, null);
658 // System.out.println("Added " + data);
660 "CMD [-annotations " + data + "] executed successfully!");
662 // set or clear the sortbytree flag.
663 if (aparser.contains("sortbytree"))
665 af.getViewport().setSortByTree(true);
666 if (af.getViewport().getSortByTree())
668 System.out.println("CMD [-sortbytree] executed successfully!");
671 if (aparser.contains("no-annotation"))
673 af.getViewport().setShowAnnotation(false);
674 if (!af.getViewport().isShowAnnotation())
676 System.out.println("CMD no-annotation executed successfully!");
679 if (aparser.contains("nosortbytree"))
681 af.getViewport().setSortByTree(false);
682 if (!af.getViewport().getSortByTree())
685 .println("CMD [-nosortbytree] executed successfully!");
688 data = aparser.getValue("tree", true);
694 "CMD [-tree " + data + "] executed successfully!");
695 NewickFile nf = new NewickFile(data,
696 AppletFormatAdapter.checkProtocol(data));
698 .setCurrentTree(af.showNewickTree(nf, data).getTree());
699 } catch (IOException ex)
701 System.err.println("Couldn't add tree " + data);
702 ex.printStackTrace(System.err);
705 // TODO - load PDB structure(s) to alignment JAL-629
706 // (associate with identical sequence in alignment, or a specified
709 getFeatures = checkDasArguments(aparser);
710 if (af != null && getFeatures != null)
712 FeatureFetcher ff = startFeatureFetching(getFeatures);
715 while (!ff.allFinished() || af.operationInProgress())
717 // wait around until fetching is finished.
721 } catch (Exception e)
727 getFeatures = null; // have retrieved features - forget them now.
729 if (groovyscript != null)
731 // Execute the groovy script after we've done all the rendering stuff
732 // and before any images or figures are generated.
733 System.out.println("Executing script " + groovyscript);
734 executeGroovyScript(groovyscript, af);
735 System.out.println("CMD groovy[" + groovyscript
736 + "] executed successfully!");
739 String imageName = "unnamed.png";
740 while (aparser.getSize() > 1)
742 String outputFormat = aparser.nextValue();
743 file = aparser.nextValue();
745 if (outputFormat.equalsIgnoreCase("png"))
747 af.createPNG(new File(file));
748 imageName = (new File(file)).getName();
749 System.out.println("Creating PNG image: " + file);
752 else if (outputFormat.equalsIgnoreCase("svg"))
754 File imageFile = new File(file);
755 imageName = imageFile.getName();
756 af.createSVG(imageFile);
757 System.out.println("Creating SVG image: " + file);
760 else if (outputFormat.equalsIgnoreCase("html"))
762 File imageFile = new File(file);
763 imageName = imageFile.getName();
764 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
765 htmlSVG.exportHTML(file);
767 System.out.println("Creating HTML image: " + file);
770 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
774 System.err.println("The output html file must not be null");
779 BioJsHTMLOutput.refreshVersionInfo(
780 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
781 } catch (URISyntaxException e)
785 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
786 bjs.exportHTML(file);
788 .println("Creating BioJS MSA Viwer HTML file: " + file);
791 else if (outputFormat.equalsIgnoreCase("imgMap"))
793 af.createImageMap(new File(file), imageName);
794 System.out.println("Creating image map: " + file);
797 else if (outputFormat.equalsIgnoreCase("eps"))
799 File outputFile = new File(file);
801 "Creating EPS file: " + outputFile.getAbsolutePath());
802 af.createEPS(outputFile);
806 if (af.saveAlignment(file, format))
808 System.out.println("Written alignment in " + format
809 + " format to " + file);
813 System.out.println("Error writing file " + file + " in "
814 + format + " format!!");
819 while (aparser.getSize() > 0)
821 System.out.println("Unknown arg: " + aparser.nextValue());
825 AlignFrame startUpAlframe = null;
826 // We'll only open the default file if the desktop is visible.
828 // ////////////////////
830 if (!headless && file == null && vamsasImport == null
831 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
833 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
834 jalview.bin.Cache.getDefault("www.jalview.org",
835 "http://www.jalview.org")
836 + "/examples/exampleFile_2_7.jar");
838 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
840 // hardwire upgrade of the startup file
841 file.replace("_2_3.jar", "_2_7.jar");
842 // and remove the stale setting
843 jalview.bin.Cache.removeProperty("STARTUP_FILE");
846 protocol = DataSourceType.FILE;
848 if (file.indexOf("http:") > -1)
850 protocol = DataSourceType.URL;
853 if (file.endsWith(".jar"))
855 format = FileFormat.Jalview;
861 format = new IdentifyFile().identify(file, protocol);
862 } catch (FileFormatException e)
868 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
870 getFeatures = checkDasArguments(aparser);
871 // extract groovy arguments before anything else.
873 // If the user has specified features to be retrieved,
874 // or a groovy script to be executed, do them if they
875 // haven't been done already
876 // fetch features for the default alignment
877 if (getFeatures != null)
879 if (startUpAlframe != null)
881 startFeatureFetching(getFeatures);
884 // Once all other stuff is done, execute any groovy scripts (in order)
885 if (groovyscript != null)
887 if (Cache.groovyJarsPresent())
889 System.out.println("Executing script " + groovyscript);
890 executeGroovyScript(groovyscript, startUpAlframe);
895 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
899 // and finally, turn off batch mode indicator - if the desktop still exists
904 desktop.setProgressBar(null, progress);
906 desktop.setInBatchMode(false);
910 private static void showUsage()
913 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
914 + "-nodisplay\tRun Jalview without User Interface.\n"
915 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
916 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
917 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
918 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
919 + "-features FILE\tUse the given file to mark features on the alignment.\n"
920 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
921 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
922 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
923 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
924 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
925 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
926 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
927 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
928 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
929 + "-png FILE\tCreate PNG image FILE from alignment.\n"
930 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
931 + "-html FILE\tCreate HTML file from alignment.\n"
932 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
933 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
934 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
935 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
936 + "-noquestionnaire\tTurn off questionnaire check.\n"
937 + "-nonews\tTurn off check for Jalview news.\n"
938 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
939 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
941 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
942 // after all other properties files have been read\n\t
943 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
944 // passed in correctly)"
945 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
946 + "-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"
947 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
948 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
949 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
951 // "-vdoc vamsas-document\tImport vamsas document into new
952 // session or join existing session with same URN\n"
953 // + "-vses vamsas-session\tJoin session with given URN\n"
954 + "-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"
955 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
958 private static void startUsageStats(final Desktop desktop)
961 * start a User Config prompt asking if we can log usage statistics.
963 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
964 "USAGESTATS", "Jalview Usage Statistics",
965 "Do you want to help make Jalview better by enabling "
966 + "the collection of usage statistics with Google Analytics ?"
967 + "\n\n(you can enable or disable usage tracking in the preferences)",
974 "Initialising googletracker for usage stats.");
975 Cache.initGoogleTracker();
976 Cache.log.debug("Tracking enabled.");
983 Cache.log.debug("Not enabling Google Tracking.");
986 desktop.addDialogThread(prompter);
990 * Locate the given string as a file and pass it to the groovy interpreter.
992 * @param groovyscript
993 * the script to execute
994 * @param jalviewContext
995 * the Jalview Desktop object passed in to the groovy binding as the
998 private void executeGroovyScript(String groovyscript, AlignFrame af)
1001 * for scripts contained in files
1008 if (groovyscript.trim().equals("STDIN"))
1010 // read from stdin into a tempfile and execute it
1013 tfile = File.createTempFile("jalview", "groovy");
1014 PrintWriter outfile = new PrintWriter(
1015 new OutputStreamWriter(new FileOutputStream(tfile)));
1016 BufferedReader br = new BufferedReader(
1017 new InputStreamReader(System.in));
1019 while ((line = br.readLine()) != null)
1021 outfile.write(line + "\n");
1027 } catch (Exception ex)
1029 System.err.println("Failed to read from STDIN into tempfile "
1030 + ((tfile == null) ? "(tempfile wasn't created)"
1031 : tfile.toString()));
1032 ex.printStackTrace();
1037 sfile = tfile.toURI().toURL();
1038 } catch (Exception x)
1041 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1043 x.printStackTrace();
1051 sfile = new URI(groovyscript).toURL();
1052 } catch (Exception x)
1054 tfile = new File(groovyscript);
1055 if (!tfile.exists())
1057 System.err.println("File '" + groovyscript + "' does not exist.");
1060 if (!tfile.canRead())
1062 System.err.println("File '" + groovyscript + "' cannot be read.");
1065 if (tfile.length() < 1)
1067 System.err.println("File '" + groovyscript + "' is empty.");
1072 sfile = tfile.getAbsoluteFile().toURI().toURL();
1073 } catch (Exception ex)
1075 System.err.println("Failed to create a file URL for "
1076 + tfile.getAbsoluteFile());
1083 Map<String, Object> vbinding = new HashMap<>();
1084 vbinding.put("Jalview", this);
1087 vbinding.put("currentAlFrame", af);
1089 Binding gbinding = new Binding(vbinding);
1090 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1091 gse.run(sfile.toString(), gbinding);
1092 if ("STDIN".equals(groovyscript))
1094 // delete temp file that we made -
1095 // only if it was successfully executed
1098 } catch (Exception e)
1100 System.err.println("Exception Whilst trying to execute file " + sfile
1101 + " as a groovy script.");
1102 e.printStackTrace(System.err);
1108 * Check commandline for any das server definitions or any fetchfrom switches
1110 * @return vector of DAS source nicknames to retrieve from
1112 private static Vector<String> checkDasArguments(ArgsParser aparser)
1114 Vector<String> source = null;
1116 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
1117 while ((data = aparser.getValue("dasserver", true)) != null)
1119 String nickname = null;
1121 int pos = data.indexOf('=');
1122 // determine capabilities
1125 nickname = data.substring(0, pos);
1127 url = data.substring(pos + 1);
1128 if (url != null && (url.startsWith("http:")
1129 || url.startsWith("sequence:http:")))
1131 if (nickname == null)
1135 if (locsources == null)
1143 locsources = locsources + nickname + "|" + url;
1145 "NOTE! dasserver parameter not yet really supported (got args of "
1146 + nickname + "|" + url);
1149 source = new Vector<>();
1151 source.addElement(nickname);
1154 "CMD [-dasserver " + data + "] executed successfully!");
1155 } // loop until no more server entries are found.
1156 if (locsources != null && locsources.indexOf('|') > -1)
1158 Cache.log.debug("Setting local source list in properties file to:\n"
1160 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
1162 while ((data = aparser.getValue("fetchfrom", true)) != null)
1164 System.out.println("adding source '" + data + "'");
1167 source = new Vector<>();
1169 source.addElement(data);
1175 * start a feature fetcher for every alignment frame
1179 private FeatureFetcher startFeatureFetching(
1180 final Vector<String> dasSources)
1182 FeatureFetcher ff = new FeatureFetcher();
1183 AlignFrame afs[] = Desktop.getAlignFrames();
1184 if (afs == null || afs.length == 0)
1188 for (int i = 0; i < afs.length; i++)
1190 ff.addFetcher(afs[i], dasSources);
1195 public static boolean isHeadlessMode()
1197 String isheadless = System.getProperty("java.awt.headless");
1198 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1205 public AlignFrame[] getAlignFrames()
1207 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1208 : Desktop.getAlignFrames();
1213 * Quit method delegates to Desktop.quit - unless running in headless mode
1214 * when it just ends the JVM
1218 if (desktop != null)
1228 public static AlignFrame getCurrentAlignFrame()
1230 return Jalview.currentAlignFrame;
1233 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1235 Jalview.currentAlignFrame = currentAlignFrame;