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";
221 javargs[0]="-Xmx15G";
223 System.err.print("relaunching with 15G: ");
226 System.err.print(r + " ");
228 System.err.println("");
229 Worker worker = Worker.jalviewDesktopRunner(false,
230 cmd.toArray(new String[0]), 0, javargs);
234 while (worker.getExitValue() == null)
239 } catch (Exception q)
244 } catch (Exception q)
249 System.exit(worker.getExitValue());
253 List<String> rgs = new ArrayList();
254 rgs.addAll(Arrays.asList(args));
256 while (i < rgs.size())
258 if (rgs.get(i).indexOf("-Xmx") > -1)
267 instance = new Jalview();
268 instance.doMain(args);
274 void doMain(String[] args)
276 System.setSecurityManager(null);
278 .println("Java version: " + System.getProperty("java.version"));
279 System.out.println(System.getProperty("os.arch") + " "
280 + System.getProperty("os.name") + " "
281 + System.getProperty("os.version"));
283 ArgsParser aparser = new ArgsParser(args);
284 boolean headless = false;
286 if (aparser.contains("help") || aparser.contains("h"))
291 if (aparser.contains("nodisplay") || aparser.contains("nogui")
292 || aparser.contains("headless"))
294 System.setProperty("java.awt.headless", "true");
297 String usrPropsFile = aparser.getValue("props");
298 Cache.loadProperties(usrPropsFile); // must do this before
299 if (usrPropsFile != null)
302 "CMD [-props " + usrPropsFile + "] executed successfully!");
307 final String jabawsUrl = aparser.getValue("jabaws");
308 if (jabawsUrl != null)
312 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
314 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
315 } catch (MalformedURLException e)
318 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
322 String defs = aparser.getValue("setprop");
325 int p = defs.indexOf('=');
328 System.err.println("Ignoring invalid setprop argument : " + defs);
332 System.out.println("Executing setprop argument: " + defs);
333 // DISABLED FOR SECURITY REASONS
334 // TODO: add a property to allow properties to be overriden by cli args
335 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
337 defs = aparser.getValue("setprop");
339 if (System.getProperty("java.awt.headless") != null
340 && System.getProperty("java.awt.headless").equals("true"))
344 System.setProperty("http.agent",
345 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
349 } catch (NoClassDefFoundError error)
351 error.printStackTrace();
352 System.out.println("\nEssential logging libraries not found."
353 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
361 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
362 } catch (Exception ex)
364 System.err.println("Unexpected Look and Feel Exception");
365 ex.printStackTrace();
367 if (Platform.isAMac())
370 LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
372 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
374 System.setProperty("apple.laf.useScreenMenuBar", "true");
375 if (lookAndFeel != null)
379 UIManager.setLookAndFeel(lookAndFeel);
380 } catch (Throwable e)
383 "Failed to set QuaQua look and feel: " + e.toString());
386 if (lookAndFeel == null || !(lookAndFeel.getClass()
387 .isAssignableFrom(UIManager.getLookAndFeel().getClass()))
388 || !UIManager.getLookAndFeel().getClass().toString()
389 .toLowerCase().contains("quaqua"))
394 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
395 UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
396 } catch (Throwable e)
399 "Failed to reset look and feel: " + e.toString());
405 * configure 'full' SO model if preferences say to,
406 * else use the default (SO Lite)
408 if (Cache.getDefault("USE_FULL_SO", false))
410 SequenceOntologyFactory.setInstance(new SequenceOntology());
415 desktop = new Desktop();
416 desktop.setInBatchMode(true); // indicate we are starting up
417 desktop.setVisible(true);
418 desktop.startServiceDiscovery();
419 if (!aparser.contains("nousagestats"))
421 startUsageStats(desktop);
425 System.err.println("CMD [-nousagestats] executed successfully!");
428 if (!aparser.contains("noquestionnaire"))
430 String url = aparser.getValue("questionnaire");
433 // Start the desktop questionnaire prompter with the specified
435 Cache.log.debug("Starting questionnaire url at " + url);
436 desktop.checkForQuestionnaire(url);
438 "CMD questionnaire[-" + url + "] executed successfully!");
442 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
444 // Start the desktop questionnaire prompter with the specified
447 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
449 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
451 "Starting questionnaire with default url: " + defurl);
452 desktop.checkForQuestionnaire(defurl);
458 System.err.println("CMD [-noquestionnaire] executed successfully!");
461 if (!aparser.contains("nonews"))
463 desktop.checkForNews();
466 BioJsHTMLOutput.updateBioJS();
469 String file = null, data = null;
470 FileFormatI format = null;
471 DataSourceType protocol = null;
472 FileLoader fileLoader = new FileLoader(!headless);
473 Vector<String> getFeatures = null; // vector of das source nicknames to
477 String groovyscript = null; // script to execute after all loading is
478 // completed one way or another
479 // extract groovy argument and execute if necessary
480 groovyscript = aparser.getValue("groovy", true);
481 file = aparser.getValue("open", true);
483 if (file == null && desktop == null)
485 System.out.println("No files to open!");
488 String vamsasImport = aparser.getValue("vdoc");
489 String vamsasSession = aparser.getValue("vsess");
490 if (vamsasImport != null || vamsasSession != null)
492 if (desktop == null || headless)
495 "Headless vamsas sessions not yet supported. Sorry.");
498 // if we have a file, start a new session and import it.
499 boolean inSession = false;
500 if (vamsasImport != null)
504 DataSourceType viprotocol = AppletFormatAdapter
505 .checkProtocol(vamsasImport);
506 if (viprotocol == DataSourceType.FILE)
508 inSession = desktop.vamsasImport(new File(vamsasImport));
510 else if (viprotocol == DataSourceType.URL)
512 inSession = desktop.vamsasImport(new URL(vamsasImport));
515 } catch (Exception e)
517 System.err.println("Exeption when importing " + vamsasImport
518 + " as a vamsas document.");
523 System.err.println("Failed to import " + vamsasImport
524 + " as a vamsas document.");
528 System.out.println("Imported Successfully into new session "
529 + desktop.getVamsasApplication().getCurrentSession());
532 if (vamsasSession != null)
534 if (vamsasImport != null)
536 // close the newly imported session and import the Jalview specific
537 // remnants into the new session later on.
538 desktop.vamsasStop_actionPerformed(null);
540 // now join the new session
543 if (desktop.joinVamsasSession(vamsasSession))
546 "Successfully joined vamsas session " + vamsasSession);
550 System.err.println("WARNING: Failed to join vamsas session "
553 } catch (Exception e)
556 "ERROR: Failed to join vamsas session " + vamsasSession);
559 if (vamsasImport != null)
561 // the Jalview specific remnants can now be imported into the new
562 // session at the user's leisure.
564 "Skipping Push for import of data into existing vamsas session."); // TODO:
569 // desktop.getVamsasApplication().push_update();
574 // Finally, deal with the remaining input data.
579 desktop.setProgressBar(
581 .getString("status.processing_commandline_args"),
582 progress = System.currentTimeMillis());
584 System.out.println("CMD [-open " + file + "] executed successfully!");
586 if (!file.startsWith("http://"))
588 if (!(new File(file)).exists())
590 System.out.println("Can't find " + file);
598 protocol = AppletFormatAdapter.checkProtocol(file);
602 format = new IdentifyFile().identify(file, protocol);
603 } catch (FileFormatException e1)
608 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
612 System.out.println("error");
616 setCurrentAlignFrame(af);
617 data = aparser.getValue("colour", true);
620 data.replaceAll("%20", " ");
622 ColourSchemeI cs = ColourSchemeProperty
623 .getColourScheme(af.getViewport().getAlignment(), data);
628 "CMD [-color " + data + "] executed successfully!");
633 // Must maintain ability to use the groups flag
634 data = aparser.getValue("groups", true);
637 af.parseFeaturesFile(data,
638 AppletFormatAdapter.checkProtocol(data));
639 // System.out.println("Added " + data);
641 "CMD groups[-" + data + "] executed successfully!");
643 data = aparser.getValue("features", true);
646 af.parseFeaturesFile(data,
647 AppletFormatAdapter.checkProtocol(data));
648 // System.out.println("Added " + data);
650 "CMD [-features " + data + "] executed successfully!");
653 data = aparser.getValue("annotations", true);
656 af.loadJalviewDataFile(data, null, null, null);
657 // System.out.println("Added " + data);
659 "CMD [-annotations " + data + "] executed successfully!");
661 // set or clear the sortbytree flag.
662 if (aparser.contains("sortbytree"))
664 af.getViewport().setSortByTree(true);
665 if (af.getViewport().getSortByTree())
667 System.out.println("CMD [-sortbytree] executed successfully!");
670 if (aparser.contains("no-annotation"))
672 af.getViewport().setShowAnnotation(false);
673 if (!af.getViewport().isShowAnnotation())
675 System.out.println("CMD no-annotation executed successfully!");
678 if (aparser.contains("nosortbytree"))
680 af.getViewport().setSortByTree(false);
681 if (!af.getViewport().getSortByTree())
684 .println("CMD [-nosortbytree] executed successfully!");
687 data = aparser.getValue("tree", true);
693 "CMD [-tree " + data + "] executed successfully!");
694 NewickFile nf = new NewickFile(data,
695 AppletFormatAdapter.checkProtocol(data));
697 .setCurrentTree(af.showNewickTree(nf, data).getTree());
698 } catch (IOException ex)
700 System.err.println("Couldn't add tree " + data);
701 ex.printStackTrace(System.err);
704 // TODO - load PDB structure(s) to alignment JAL-629
705 // (associate with identical sequence in alignment, or a specified
708 getFeatures = checkDasArguments(aparser);
709 if (af != null && getFeatures != null)
711 FeatureFetcher ff = startFeatureFetching(getFeatures);
714 while (!ff.allFinished() || af.operationInProgress())
716 // wait around until fetching is finished.
720 } catch (Exception e)
726 getFeatures = null; // have retrieved features - forget them now.
728 if (groovyscript != null)
730 // Execute the groovy script after we've done all the rendering stuff
731 // and before any images or figures are generated.
732 System.out.println("Executing script " + groovyscript);
733 executeGroovyScript(groovyscript, af);
734 System.out.println("CMD groovy[" + groovyscript
735 + "] executed successfully!");
738 String imageName = "unnamed.png";
739 while (aparser.getSize() > 1)
741 String outputFormat = aparser.nextValue();
742 file = aparser.nextValue();
744 if (outputFormat.equalsIgnoreCase("png"))
746 af.createPNG(new File(file));
747 imageName = (new File(file)).getName();
748 System.out.println("Creating PNG image: " + file);
751 else if (outputFormat.equalsIgnoreCase("svg"))
753 File imageFile = new File(file);
754 imageName = imageFile.getName();
755 af.createSVG(imageFile);
756 System.out.println("Creating SVG image: " + file);
759 else if (outputFormat.equalsIgnoreCase("html"))
761 File imageFile = new File(file);
762 imageName = imageFile.getName();
763 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
764 htmlSVG.exportHTML(file);
766 System.out.println("Creating HTML image: " + file);
769 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
773 System.err.println("The output html file must not be null");
778 BioJsHTMLOutput.refreshVersionInfo(
779 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
780 } catch (URISyntaxException e)
784 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
785 bjs.exportHTML(file);
787 .println("Creating BioJS MSA Viwer HTML file: " + file);
790 else if (outputFormat.equalsIgnoreCase("imgMap"))
792 af.createImageMap(new File(file), imageName);
793 System.out.println("Creating image map: " + file);
796 else if (outputFormat.equalsIgnoreCase("eps"))
798 File outputFile = new File(file);
800 "Creating EPS file: " + outputFile.getAbsolutePath());
801 af.createEPS(outputFile);
805 if (af.saveAlignment(file, format))
807 System.out.println("Written alignment in " + format
808 + " format to " + file);
812 System.out.println("Error writing file " + file + " in "
813 + format + " format!!");
818 while (aparser.getSize() > 0)
820 System.out.println("Unknown arg: " + aparser.nextValue());
824 AlignFrame startUpAlframe = null;
825 // We'll only open the default file if the desktop is visible.
827 // ////////////////////
829 if (!headless && file == null && vamsasImport == null
830 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
832 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
833 jalview.bin.Cache.getDefault("www.jalview.org",
834 "http://www.jalview.org")
835 + "/examples/exampleFile_2_7.jar");
837 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
839 // hardwire upgrade of the startup file
840 file.replace("_2_3.jar", "_2_7.jar");
841 // and remove the stale setting
842 jalview.bin.Cache.removeProperty("STARTUP_FILE");
845 protocol = DataSourceType.FILE;
847 if (file.indexOf("http:") > -1)
849 protocol = DataSourceType.URL;
852 if (file.endsWith(".jar"))
854 format = FileFormat.Jalview;
860 format = new IdentifyFile().identify(file, protocol);
861 } catch (FileFormatException e)
867 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
869 getFeatures = checkDasArguments(aparser);
870 // extract groovy arguments before anything else.
872 // If the user has specified features to be retrieved,
873 // or a groovy script to be executed, do them if they
874 // haven't been done already
875 // fetch features for the default alignment
876 if (getFeatures != null)
878 if (startUpAlframe != null)
880 startFeatureFetching(getFeatures);
883 // Once all other stuff is done, execute any groovy scripts (in order)
884 if (groovyscript != null)
886 if (Cache.groovyJarsPresent())
888 System.out.println("Executing script " + groovyscript);
889 executeGroovyScript(groovyscript, startUpAlframe);
894 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
898 // and finally, turn off batch mode indicator - if the desktop still exists
903 desktop.setProgressBar(null, progress);
905 desktop.setInBatchMode(false);
909 private static void showUsage()
912 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
913 + "-nodisplay\tRun Jalview without User Interface.\n"
914 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
915 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
916 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
917 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
918 + "-features FILE\tUse the given file to mark features on the alignment.\n"
919 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
920 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
921 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
922 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
923 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
924 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
925 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
926 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
927 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
928 + "-png FILE\tCreate PNG image FILE from alignment.\n"
929 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
930 + "-html FILE\tCreate HTML file from alignment.\n"
931 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
932 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
933 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
934 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
935 + "-noquestionnaire\tTurn off questionnaire check.\n"
936 + "-nonews\tTurn off check for Jalview news.\n"
937 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
938 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
940 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
941 // after all other properties files have been read\n\t
942 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
943 // passed in correctly)"
944 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
945 + "-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"
946 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
947 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
948 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
950 // "-vdoc vamsas-document\tImport vamsas document into new
951 // session or join existing session with same URN\n"
952 // + "-vses vamsas-session\tJoin session with given URN\n"
953 + "-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"
954 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
957 private static void startUsageStats(final Desktop desktop)
960 * start a User Config prompt asking if we can log usage statistics.
962 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
963 "USAGESTATS", "Jalview Usage Statistics",
964 "Do you want to help make Jalview better by enabling "
965 + "the collection of usage statistics with Google Analytics ?"
966 + "\n\n(you can enable or disable usage tracking in the preferences)",
973 "Initialising googletracker for usage stats.");
974 Cache.initGoogleTracker();
975 Cache.log.debug("Tracking enabled.");
982 Cache.log.debug("Not enabling Google Tracking.");
985 desktop.addDialogThread(prompter);
989 * Locate the given string as a file and pass it to the groovy interpreter.
991 * @param groovyscript
992 * the script to execute
993 * @param jalviewContext
994 * the Jalview Desktop object passed in to the groovy binding as the
997 private void executeGroovyScript(String groovyscript, AlignFrame af)
1000 * for scripts contained in files
1007 if (groovyscript.trim().equals("STDIN"))
1009 // read from stdin into a tempfile and execute it
1012 tfile = File.createTempFile("jalview", "groovy");
1013 PrintWriter outfile = new PrintWriter(
1014 new OutputStreamWriter(new FileOutputStream(tfile)));
1015 BufferedReader br = new BufferedReader(
1016 new InputStreamReader(System.in));
1018 while ((line = br.readLine()) != null)
1020 outfile.write(line + "\n");
1026 } catch (Exception ex)
1028 System.err.println("Failed to read from STDIN into tempfile "
1029 + ((tfile == null) ? "(tempfile wasn't created)"
1030 : tfile.toString()));
1031 ex.printStackTrace();
1036 sfile = tfile.toURI().toURL();
1037 } catch (Exception x)
1040 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1042 x.printStackTrace();
1050 sfile = new URI(groovyscript).toURL();
1051 } catch (Exception x)
1053 tfile = new File(groovyscript);
1054 if (!tfile.exists())
1056 System.err.println("File '" + groovyscript + "' does not exist.");
1059 if (!tfile.canRead())
1061 System.err.println("File '" + groovyscript + "' cannot be read.");
1064 if (tfile.length() < 1)
1066 System.err.println("File '" + groovyscript + "' is empty.");
1071 sfile = tfile.getAbsoluteFile().toURI().toURL();
1072 } catch (Exception ex)
1074 System.err.println("Failed to create a file URL for "
1075 + tfile.getAbsoluteFile());
1082 Map<String, Object> vbinding = new HashMap<>();
1083 vbinding.put("Jalview", this);
1086 vbinding.put("currentAlFrame", af);
1088 Binding gbinding = new Binding(vbinding);
1089 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1090 gse.run(sfile.toString(), gbinding);
1091 if ("STDIN".equals(groovyscript))
1093 // delete temp file that we made -
1094 // only if it was successfully executed
1097 } catch (Exception e)
1099 System.err.println("Exception Whilst trying to execute file " + sfile
1100 + " as a groovy script.");
1101 e.printStackTrace(System.err);
1107 * Check commandline for any das server definitions or any fetchfrom switches
1109 * @return vector of DAS source nicknames to retrieve from
1111 private static Vector<String> checkDasArguments(ArgsParser aparser)
1113 Vector<String> source = null;
1115 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
1116 while ((data = aparser.getValue("dasserver", true)) != null)
1118 String nickname = null;
1120 int pos = data.indexOf('=');
1121 // determine capabilities
1124 nickname = data.substring(0, pos);
1126 url = data.substring(pos + 1);
1127 if (url != null && (url.startsWith("http:")
1128 || url.startsWith("sequence:http:")))
1130 if (nickname == null)
1134 if (locsources == null)
1142 locsources = locsources + nickname + "|" + url;
1144 "NOTE! dasserver parameter not yet really supported (got args of "
1145 + nickname + "|" + url);
1148 source = new Vector<>();
1150 source.addElement(nickname);
1153 "CMD [-dasserver " + data + "] executed successfully!");
1154 } // loop until no more server entries are found.
1155 if (locsources != null && locsources.indexOf('|') > -1)
1157 Cache.log.debug("Setting local source list in properties file to:\n"
1159 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
1161 while ((data = aparser.getValue("fetchfrom", true)) != null)
1163 System.out.println("adding source '" + data + "'");
1166 source = new Vector<>();
1168 source.addElement(data);
1174 * start a feature fetcher for every alignment frame
1178 private FeatureFetcher startFeatureFetching(
1179 final Vector<String> dasSources)
1181 FeatureFetcher ff = new FeatureFetcher();
1182 AlignFrame afs[] = Desktop.getAlignFrames();
1183 if (afs == null || afs.length == 0)
1187 for (int i = 0; i < afs.length; i++)
1189 ff.addFetcher(afs[i], dasSources);
1194 public static boolean isHeadlessMode()
1196 String isheadless = System.getProperty("java.awt.headless");
1197 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1204 public AlignFrame[] getAlignFrames()
1206 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1207 : Desktop.getAlignFrames();
1212 * Quit method delegates to Desktop.quit - unless running in headless mode
1213 * when it just ends the JVM
1217 if (desktop != null)
1227 public static AlignFrame getCurrentAlignFrame()
1229 return Jalview.currentAlignFrame;
1232 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1234 Jalview.currentAlignFrame = currentAlignFrame;