fetch groovy script from URL (JAL-899) and show progress bar when handling CLI comman...
[jalview.git] / src / jalview / bin / Jalview.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3  * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
4  * 
5  * This file is part of Jalview.
6  * 
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.bin;
19
20 import java.io.BufferedReader;
21 import java.io.File;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStreamWriter;
25 import java.io.PrintWriter;
26 import java.lang.reflect.Constructor;
27 import java.net.MalformedURLException;
28 import java.net.URI;
29 import java.net.URL;
30 import java.net.URLDecoder;
31 import java.security.AllPermission;
32 import java.security.CodeSource;
33 import java.security.PermissionCollection;
34 import java.security.Permissions;
35 import java.security.Policy;
36 import java.util.*;
37
38 import javax.swing.*;
39
40 import jalview.gui.*;
41 import jalview.util.Platform;
42
43 /**
44  * Main class for Jalview Application <br>
45  * <br>
46  * start with java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview
47  * 
48  * @author $author$
49  * @version $Revision$
50  */
51 public class Jalview
52 {
53   static
54   {
55     // grab all the rights we can the JVM
56     Policy.setPolicy(new Policy()
57     {
58       public PermissionCollection getPermissions(CodeSource codesource)
59       {
60         Permissions perms = new Permissions();
61         perms.add(new AllPermission());
62         return (perms);
63       }
64
65       public void refresh()
66       {
67       }
68     });
69   }
70
71   /**
72    * main class for Jalview application
73    * 
74    * @param args
75    *          open <em>filename</em>
76    */
77   public static void main(String[] args)
78   {
79     System.out.println("Java version: "
80             + System.getProperty("java.version"));
81     System.out.println(System.getProperty("os.arch") + " "
82             + System.getProperty("os.name") + " "
83             + System.getProperty("os.version"));
84     if (new Platform().isAMac())
85     {
86       System.setProperty("com.apple.mrj.application.apple.menu.about.name",
87               "Jalview");
88       System.setProperty("apple.laf.useScreenMenuBar", "true");
89     }
90
91     ArgsParser aparser = new ArgsParser(args);
92     boolean headless = false;
93
94     if (aparser.contains("help") || aparser.contains("h"))
95     {
96       System.out
97               .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
98                       + "-nodisplay\tRun Jalview without User Interface.\n"
99                       + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
100                       + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
101                       + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
102                       + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
103                       + "-features FILE\tUse the given file to mark features on the alignment.\n"
104                       + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
105                       + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
106                       + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
107                       + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
108                       + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
109                       + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
110                       + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
111                       + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
112                       + "-png FILE\tCreate PNG image FILE from alignment.\n"
113                       + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
114                       + "-eps FILE\tCreate EPS file FILE from alignment.\n"
115                       + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
116                       + "-noquestionnaire\tTurn off questionnaire check.\n"
117                       + "-nousagestats\tTurn off google analytics tracking for this session.\n"
118                       + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
119                       // +
120                       // "-setprop PROPERTY=VALUE\tSet the given Jalview property, after all other properties files have been read\n\t (quote the 'PROPERTY=VALUE' pair to ensure spaces are passed in correctly)"
121                       + "-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"
122                       + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
123                       + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
124                       + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
125                       // +
126                       // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
127                       // + "-vses vamsas-session\tJoin session with given URN\n"
128                       + "-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"
129                       + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
130       System.exit(0);
131     }
132     Cache.loadProperties(aparser.getValue("props")); // must do this before
133     // anything else!
134     String defs = aparser.getValue("setprop");
135     while (defs != null)
136     {
137       int p = defs.indexOf('=');
138       if (p == -1)
139       {
140         System.err.println("Ignoring invalid setprop argument : " + defs);
141       }
142       else
143       {
144         System.out.println("Executing setprop argument: " + defs);
145         // DISABLED FOR SECURITY REASONS
146         // TODO: add a property to allow properties to be overriden by cli args
147         // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
148       }
149       defs = aparser.getValue("setprop");
150     }
151     if (aparser.contains("nodisplay"))
152     {
153       System.setProperty("java.awt.headless", "true");
154     }
155     if (System.getProperty("java.awt.headless") != null
156             && System.getProperty("java.awt.headless").equals("true"))
157     {
158       headless = true;
159     }
160
161     try
162     {
163       Cache.initLogger();
164     } catch (java.lang.NoClassDefFoundError error)
165     {
166       error.printStackTrace();
167       System.out
168               .println("\nEssential logging libraries not found."
169                       + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
170       System.exit(0);
171     }
172
173     Desktop desktop = null;
174
175     try
176     {
177       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
178     } catch (Exception ex)
179     {
180     }
181
182     if (!headless)
183     {
184       desktop = new Desktop();
185       desktop.setInBatchMode(true); // indicate we are starting up
186       desktop.setVisible(true);
187       desktop.startServiceDiscovery();
188       if (!aparser.contains("nousagestats"))
189       {
190         startUsageStats(desktop);
191       }
192       if (!aparser.contains("noquestionnaire"))
193       {
194         String url = aparser.getValue("questionnaire");
195         if (url != null)
196         {
197           // Start the desktop questionnaire prompter with the specified
198           // questionnaire
199           Cache.log.debug("Starting questionnaire url at " + url);
200           desktop.checkForQuestionnaire(url);
201         }
202         else
203         {
204           if (Cache.getProperty("NOQUESTIONNAIRES") == null)
205           {
206             // Start the desktop questionnaire prompter with the specified
207             // questionnaire
208             // String defurl =
209             // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
210             // //
211             String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
212             Cache.log.debug("Starting questionnaire with default url: "
213                     + defurl);
214             desktop.checkForQuestionnaire(defurl);
215
216           }
217         }
218       }
219     }
220
221     String file = null, protocol = null, format = null, data = null;
222     jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
223     Vector getFeatures = null; // vector of das source nicknames to fetch
224     // features from
225     // loading is done.
226     String groovyscript = null; // script to execute after all loading is
227     // completed one way or another
228     // extract groovy argument and execute if necessary
229     groovyscript = aparser.getValue("groovy", true);
230     file = aparser.getValue("open", true);
231
232     if (file == null && desktop == null)
233     {
234       System.out.println("No files to open!");
235       System.exit(1);
236     }
237     String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
238             .getValue("vsess");
239     if (vamsasImport != null || vamsasSession != null)
240     {
241       if (desktop == null || headless)
242       {
243         System.out
244                 .println("Headless vamsas sessions not yet supported. Sorry.");
245         System.exit(1);
246       }
247       // if we have a file, start a new session and import it.
248       boolean inSession = false;
249       if (vamsasImport != null)
250       {
251         try
252         {
253           String viprotocol = jalview.io.AppletFormatAdapter.checkProtocol(vamsasImport);
254           if (viprotocol == jalview.io.FormatAdapter.FILE)
255           {
256             inSession = desktop.vamsasImport(new File(vamsasImport));
257           }
258           else if (viprotocol == jalview.io.FormatAdapter.URL)
259           {
260             inSession = desktop.vamsasImport(new URL(vamsasImport));
261           }
262
263         } catch (Exception e)
264         {
265           System.err.println("Exeption when importing " + vamsasImport
266                   + " as a vamsas document.");
267           e.printStackTrace();
268         }
269         if (!inSession)
270         {
271           System.err.println("Failed to import " + vamsasImport
272                   + " as a vamsas document.");
273         }
274         else
275         {
276           System.out.println("Imported Successfully into new session "
277                   + desktop.getVamsasApplication().getCurrentSession());
278         }
279       }
280       if (vamsasSession != null)
281       {
282         if (vamsasImport != null)
283         {
284           // close the newly imported session and import the Jalview specific
285           // remnants into the new session later on.
286           desktop.vamsasStop_actionPerformed(null);
287         }
288         // now join the new session
289         try
290         {
291           if (desktop.joinVamsasSession(vamsasSession))
292           {
293             System.out.println("Successfully joined vamsas session "
294                     + vamsasSession);
295           }
296           else
297           {
298             System.err.println("WARNING: Failed to join vamsas session "
299                     + vamsasSession);
300           }
301         } catch (Exception e)
302         {
303           System.err.println("ERROR: Failed to join vamsas session "
304                   + vamsasSession);
305           e.printStackTrace();
306         }
307         if (vamsasImport != null)
308         {
309           // the Jalview specific remnants can now be imported into the new
310           // session at the user's leisure.
311           Cache.log
312                   .info("Skipping Push for import of data into existing vamsas session."); // TODO:
313           // enable
314           // this
315           // when
316           // debugged
317           // desktop.getVamsasApplication().push_update();
318         }
319       }
320     }
321     // Finally, deal with the remaining input data.
322     if (file != null)
323     {
324       System.out.println("Opening file: " + file);
325
326       if (!file.startsWith("http://"))
327       {
328         if (!(new java.io.File(file)).exists())
329         {
330           System.out.println("Can't find " + file);
331           if (headless)
332           {
333             System.exit(1);
334           }
335         }
336       }
337       if (!headless)
338       {
339         desktop.setProgressBar("Processing commandline arguments...", Jalview.class.hashCode());
340       }
341
342       protocol = jalview.io.AppletFormatAdapter.checkProtocol(file);
343
344       format = new jalview.io.IdentifyFile().Identify(file, protocol);
345
346       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
347               format);
348       if (af == null)
349       {
350         System.out.println("error");
351         return;
352       }
353
354       data = aparser.getValue("colour", true);
355       if (data != null)
356       {
357         data.replaceAll("%20", " ");
358
359         jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
360                 .getColour(af.getViewport().getAlignment(), data);
361
362         if (cs == null)
363         {
364           jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
365                   "white");
366           ucs.parseAppletParameter(data);
367           cs = ucs;
368         }
369
370         System.out.println("colour is " + data);
371         af.changeColour(cs);
372       }
373
374       // Must maintain ability to use the groups flag
375       data = aparser.getValue("groups", true);
376       if (data != null)
377       {
378         af.parseFeaturesFile(data, jalview.io.AppletFormatAdapter.checkProtocol(data));
379         System.out.println("Added " + data);
380       }
381       data = aparser.getValue("features", true);
382       if (data != null)
383       {
384         af.parseFeaturesFile(data, jalview.io.AppletFormatAdapter.checkProtocol(data));
385         System.out.println("Added " + data);
386       }
387
388       data = aparser.getValue("annotations", true);
389       if (data != null)
390       {
391         af.loadJalviewDataFile(data, null, null, null);
392         System.out.println("Added " + data);
393       }
394       // set or clear the sortbytree flag.
395       if (aparser.contains("sortbytree"))
396       {
397         af.getViewport().setSortByTree(true);
398       }
399       if (aparser.contains("nosortbytree"))
400       {
401         af.getViewport().setSortByTree(false);
402       }
403       data = aparser.getValue("tree", true);
404       if (data != null)
405       {
406         jalview.io.NewickFile fin = null;
407         try
408         {
409           fin = new jalview.io.NewickFile(data, jalview.io.AppletFormatAdapter.checkProtocol(data));
410           if (fin != null)
411           {
412             af.getViewport().setCurrentTree(
413                     af.ShowNewickTree(fin, data).getTree());
414             System.out.println("Added tree " + data);
415           }
416         } catch (IOException ex)
417         {
418           System.err.println("Couldn't add tree " + data);
419           ex.printStackTrace(System.err);
420         }
421       }
422       // TODO - load PDB structure(s) to alignment JAL-629
423       // (associate with identical sequence in alignment, or a specified
424       // sequence)
425
426       getFeatures = checkDasArguments(aparser);
427       if (af != null && getFeatures != null)
428       {
429         FeatureFetcher ff = startFeatureFetching(getFeatures);
430         if (ff != null)
431           while (!ff.allFinished() || af.operationInProgress())
432           {
433             // wait around until fetching is finished.
434             try
435             {
436               Thread.sleep(100);
437             } catch (Exception e)
438             {
439
440             }
441           }
442         getFeatures = null; // have retrieved features - forget them now.
443       }
444       if (groovyscript != null)
445       {
446         // Execute the groovy script after we've done all the rendering stuff
447         // and before any images or figures are generated.
448         if (jalview.bin.Cache.groovyJarsPresent())
449         {
450           System.out.println("Executing script " + groovyscript);
451           executeGroovyScript(groovyscript, new Object[] {desktop,af});
452         }
453         else
454         {
455           System.err
456                   .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
457                           + groovyscript);
458         }
459         groovyscript = null;
460       }
461       String imageName = "unnamed.png";
462       while (aparser.getSize() > 1)
463       {
464         format = aparser.nextValue();
465         file = aparser.nextValue();
466
467         if (format.equalsIgnoreCase("png"))
468         {
469           af.createPNG(new java.io.File(file));
470           imageName = (new java.io.File(file)).getName();
471           System.out.println("Creating PNG image: " + file);
472           continue;
473         }
474         else if (format.equalsIgnoreCase("imgMap"))
475         {
476           af.createImageMap(new java.io.File(file), imageName);
477           System.out.println("Creating image map: " + file);
478           continue;
479         }
480         else if (format.equalsIgnoreCase("eps"))
481         {
482           System.out.println("Creating EPS file: " + file);
483           af.createEPS(new java.io.File(file));
484           continue;
485         }
486
487         if (af.saveAlignment(file, format))
488         {
489           System.out.println("Written alignment in " + format
490                   + " format to " + file);
491         }
492         else
493         {
494           System.out.println("Error writing file " + file + " in " + format
495                   + " format!!");
496         }
497
498       }
499
500       while (aparser.getSize() > 0)
501       {
502         System.out.println("Unknown arg: " + aparser.nextValue());
503       }
504     }
505     AlignFrame startUpAlframe = null;
506     // We'll only open the default file if the desktop is visible.
507     // And the user
508     // ////////////////////
509     if (!headless && file == null && vamsasImport == null
510             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
511     {
512       file = jalview.bin.Cache.getDefault("STARTUP_FILE",
513               jalview.bin.Cache.getDefault("www.jalview.org", "http://www.jalview.org")+"/examples/exampleFile_2_3.jar");
514
515       protocol = "File";
516
517       if (file.indexOf("http:") > -1)
518       {
519         protocol = "URL";
520       }
521
522       if (file.endsWith(".jar"))
523       {
524         format = "Jalview";
525       }
526       else
527       {
528         format = new jalview.io.IdentifyFile().Identify(file, protocol);
529       }
530
531       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
532               format);
533       getFeatures = checkDasArguments(aparser);
534       // extract groovy arguments before anything else.
535     }
536     // If the user has specified features to be retrieved,
537     // or a groovy script to be executed, do them if they
538     // haven't been done already
539     // fetch features for the default alignment
540     if (getFeatures != null)
541     {
542       if (startUpAlframe != null)
543       {
544         startFeatureFetching(getFeatures);
545       }
546     }
547     // Once all other stuff is done, execute any groovy scripts (in order)
548     if (groovyscript != null)
549     {
550       if (jalview.bin.Cache.groovyJarsPresent())
551       {
552         System.out.println("Executing script " + groovyscript);
553         executeGroovyScript(groovyscript, new Object[] { desktop, startUpAlframe});
554       }
555       else
556       {
557         System.err
558                 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
559                         + groovyscript);
560       }
561     }
562     // and finally, turn off batch mode indicator - if the desktop still exists
563     if (desktop != null)
564     {
565       desktop.setProgressBar(null, Jalview.class.hashCode());
566       desktop.setInBatchMode(false);
567     }
568   }
569
570   private static void startUsageStats(final Desktop desktop)
571   {
572     /**
573      * start a User Config prompt asking if we can log usage statistics.
574      */
575     jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
576             desktop.desktop,
577             "USAGESTATS",
578             "Jalview Usage Statistics",
579             "Do you want to help make Jalview better by enabling "
580                     + "the collection of usage statistics with Google Analytics ?"
581                     + "\n\n(you can enable or disable usage tracking in the preferences)",
582             new Runnable()
583             {
584               public void run()
585               {
586                 Cache.log
587                         .info("Initialising googletracker for usage stats.");
588                 Cache.initGoogleTracker();
589                 Cache.log.debug("Tracking enabled.");
590               }
591             }, new Runnable()
592             {
593               public void run()
594               {
595                 Cache.log.info("Not enabling Google Tracking.");
596               }
597             }, null, true);
598     SwingUtilities.invokeLater(prompter);
599   }
600
601   /**
602    * Locate the given string as a file and pass it to the groovy interpreter.
603    * 
604    * @param groovyscript
605    *          the script to execute
606    * @param jalviewContext
607    *          the Jalview Desktop object passed in to the groovy binding as the
608    *          'Jalview' object.
609    */
610   private static void executeGroovyScript(String groovyscript,
611           Object[] jalviewContext)
612   {
613     if (jalviewContext == null)
614     {
615       System.err
616               .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
617     }
618     /**
619      * for scripts contained in files
620      */
621     File tfile = null;
622     /**
623      * script's URI
624      */
625     URL sfile = null;
626     if (groovyscript.trim().equals("STDIN"))
627     {
628       // read from stdin into a tempfile and execute it
629       try
630       {
631         tfile = File.createTempFile("jalview", "groovy");
632         PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
633                 new FileOutputStream(tfile)));
634         BufferedReader br = new BufferedReader(
635                 new java.io.InputStreamReader(System.in));
636         String line = null;
637         while ((line = br.readLine()) != null)
638         {
639           outfile.write(line + "\n");
640         }
641         br.close();
642         outfile.flush();
643         outfile.close();
644
645       } catch (Exception ex)
646       {
647         System.err.println("Failed to read from STDIN into tempfile "
648                 + ((tfile == null) ? "(tempfile wasn't created)" : tfile
649                         .toString()));
650         ex.printStackTrace();
651         return;
652       }
653       try {
654         sfile = tfile.toURI().toURL();
655       } catch (Exception x)
656       {
657         System.err.println("Unexpected Malformed URL Exception for temporary file created from STDIN: "+tfile.toURI());
658         x.printStackTrace();
659         return;
660       }
661     }
662     else
663     {
664       try
665       {
666         sfile = new URI(groovyscript).toURL();
667       } catch (Exception x)
668       {
669         tfile = new File(groovyscript);
670         if (!tfile.exists())
671         {
672           System.err.println("File '" + groovyscript + "' does not exist.");
673           return;
674         }
675         if (!tfile.canRead())
676         {
677           System.err.println("File '" + groovyscript + "' cannot be read.");
678           return;
679         }
680         if (tfile.length() < 1)
681         {
682           System.err.println("File '" + groovyscript + "' is empty.");
683           return;
684         }
685         try {
686         sfile = tfile.getAbsoluteFile().toURI().toURL();
687         } catch (Exception ex)
688         {
689           System.err.println("Failed to create a file URL for "+tfile.getAbsoluteFile());
690           return;
691         }
692       }
693     }
694     boolean success = false;
695     try
696     {
697       /*
698        * The following code performs the GroovyScriptEngine invocation using
699        * reflection, and is equivalent to this fragment from the embedding
700        * groovy documentation on the groovy site: <code> import
701        * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
702        * 
703        * String[] roots = new String[] { "/my/groovy/script/path" };
704        * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
705        * = new Binding(); binding.setVariable("input", "world");
706        * gse.run("hello.groovy", binding); </code>
707        */
708       Class[] bspec;
709       Object[] binding;
710       int blen = ((jalviewContext[0] == null) ? 0 : 1)
711               + ((jalviewContext[1] == null) ? 0 : 1);
712       String cnames[] = new String[]
713       { "Jalview", "currentAlFrame" };
714       bspec = new Class[blen * 2];
715       binding = new Object[blen * 2];
716       blen = 0;
717       ClassLoader cl = null;
718       Map vbinding = new Hashtable();
719       for (int jc = 0; jc < jalviewContext.length; jc++)
720       {
721         if (jalviewContext[jc] != null)
722         {
723           if (cl == null)
724           {
725             cl = jalviewContext[jc].getClass().getClassLoader();
726           }
727           bspec[blen * 2] = String.class;
728           bspec[blen * 2 + 1] = Object.class;
729           binding[blen * 2] = cnames[jc];
730           binding[blen * 2 + 1] = jalviewContext[jc];
731           vbinding.put(cnames[jc], jalviewContext[jc]);
732           blen++;
733         }
734       }
735       Class gbindingc = cl.loadClass("groovy.lang.Binding");
736       Constructor gbcons;
737       Object gbinding;
738       try
739       {
740         gbcons = gbindingc.getConstructor(Map.class);
741         gbinding = gbcons.newInstance(vbinding);
742       } catch (NoSuchMethodException x)
743       {
744         // old style binding config - using series of string/object values to
745         // setVariable.
746         gbcons = gbindingc.getConstructor(null);
747         gbinding = gbcons.newInstance(null);
748         java.lang.reflect.Method setvar = gbindingc.getMethod(
749                 "setVariable", bspec);
750         setvar.invoke(gbinding, binding);
751       }
752       ;
753       Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
754       Constructor gseccons = gsec.getConstructor(new Class[]
755       { URL[].class }); // String[].class });
756       Object gse = gseccons.newInstance(new Object[]
757       { new URL[]
758       { sfile } }); // .toString() } });
759       java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
760       { String.class, gbindingc });
761       run.invoke(gse, new Object[]
762       { sfile.toString(), gbinding });
763       success = true;
764     } catch (Exception e)
765     {
766       System.err.println("Exception Whilst trying to execute file " + sfile
767               + " as a groovy script.");
768       e.printStackTrace(System.err);
769
770     }
771     if (success && groovyscript.equals("STDIN"))
772     {
773       // delete temp file that we made - but only if it was successfully
774       // executed
775       tfile.delete();
776     }
777   }
778
779   /**
780    * Check commandline for any das server definitions or any fetchfrom switches
781    * 
782    * @return vector of DAS source nicknames to retrieve from
783    */
784   private static Vector checkDasArguments(ArgsParser aparser)
785   {
786     Vector source = null;
787     String data;
788     String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
789     while ((data = aparser.getValue("dasserver", true)) != null)
790     {
791       String nickname = null;
792       String url = null;
793       boolean seq = false, feat = true;
794       int pos = data.indexOf('=');
795       // determine capabilities
796       if (pos > 0)
797       {
798         nickname = data.substring(0, pos);
799       }
800       url = data.substring(pos + 1);
801       if (url != null
802               && (url.startsWith("http:") || url
803                       .startsWith("sequence:http:")))
804       {
805         if (nickname == null)
806         {
807           nickname = url;
808         }
809         if (locsources == null)
810         {
811           locsources = "";
812         }
813         else
814         {
815           locsources += "\t";
816         }
817         locsources = locsources + nickname + "|" + url;
818         System.err
819                 .println("NOTE! dasserver parameter not yet really supported (got args of "
820                         + nickname + "|" + url);
821         if (source == null)
822         {
823           source = new Vector();
824         }
825         source.addElement(nickname);
826       }
827     } // loop until no more server entries are found.
828     if (locsources != null && locsources.indexOf('|') > -1)
829     {
830       Cache.log.debug("Setting local source list in properties file to:\n"
831               + locsources);
832       Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
833     }
834     while ((data = aparser.getValue("fetchfrom", true)) != null)
835     {
836       System.out.println("adding source '" + data + "'");
837       if (source == null)
838       {
839         source = new Vector();
840       }
841       source.addElement(data);
842     }
843     return source;
844   }
845
846   /**
847    * start a feature fetcher for every alignment frame
848    * 
849    * @param dasSources
850    */
851   private static FeatureFetcher startFeatureFetching(final Vector dasSources)
852   {
853     FeatureFetcher ff = new FeatureFetcher();
854     AlignFrame afs[] = Desktop.getAlignframes();
855     if (afs == null || afs.length == 0)
856     {
857       return null;
858     }
859     for (int i = 0; i < afs.length; i++)
860     {
861       ff.addFetcher(afs[i], dasSources);
862     }
863     return ff;
864   }
865 }
866
867 /**
868  * Notes: this argParser does not distinguish between parameter switches,
869  * parameter values and argument text. If an argument happens to be identical to
870  * a parameter, it will be taken as such (even though it didn't have a '-'
871  * prefixing it).
872  * 
873  * @author Andrew Waterhouse and JBP documented.
874  * 
875  */
876 class ArgsParser
877 {
878   Vector vargs = null;
879
880   public ArgsParser(String[] args)
881   {
882     vargs = new Vector();
883     for (int i = 0; i < args.length; i++)
884     {
885       String arg = args[i].trim();
886       if (arg.charAt(0) == '-')
887       {
888         arg = arg.substring(1);
889       }
890       vargs.addElement(arg);
891     }
892   }
893
894   /**
895    * check for and remove first occurence of arg+parameter in arglist.
896    * 
897    * @param arg
898    * @return return the argument following the given arg if arg was in list.
899    */
900   public String getValue(String arg)
901   {
902     return getValue(arg, false);
903   }
904
905   public String getValue(String arg, boolean utf8decode)
906   {
907     int index = vargs.indexOf(arg);
908     String dc = null, ret = null;
909     if (index != -1)
910     {
911       ret = vargs.elementAt(index + 1).toString();
912       vargs.removeElementAt(index);
913       vargs.removeElementAt(index);
914       if (utf8decode && ret != null)
915       {
916         try
917         {
918           dc = URLDecoder.decode(ret, "UTF-8");
919           ret = dc;
920         } catch (Exception e)
921         {
922           // TODO: log failure to decode
923         }
924       }
925     }
926     return ret;
927   }
928
929   /**
930    * check for and remove first occurence of arg in arglist.
931    * 
932    * @param arg
933    * @return true if arg was present in argslist.
934    */
935   public boolean contains(String arg)
936   {
937     if (vargs.contains(arg))
938     {
939       vargs.removeElement(arg);
940       return true;
941     }
942     else
943     {
944       return false;
945     }
946   }
947
948   public String nextValue()
949   {
950     return vargs.remove(0).toString();
951   }
952
953   public int getSize()
954   {
955     return vargs.size();
956   }
957
958 }
959
960 /**
961  * keep track of feature fetching tasks.
962  * 
963  * @author JimP
964  * 
965  */
966 class FeatureFetcher
967 {
968   /*
969    * TODO: generalise to track all jalview events to orchestrate batch
970    * processing events.
971    */
972
973   private int queued = 0;
974
975   private int running = 0;
976
977   public FeatureFetcher()
978   {
979
980   }
981
982   public void addFetcher(final AlignFrame af, final Vector dasSources)
983   {
984     final long id = System.currentTimeMillis();
985     queued++;
986     final FeatureFetcher us = this;
987     new Thread(new Runnable()
988     {
989
990       public void run()
991       {
992         synchronized (us)
993         {
994           queued--;
995           running++;
996         }
997
998         af.setProgressBar("DAS features being retrieved...", id);
999         af.featureSettings_actionPerformed(null);
1000         af.featureSettings.fetchDasFeatures(dasSources, true);
1001         af.setProgressBar(null, id);
1002         synchronized (us)
1003         {
1004           running--;
1005         }
1006       }
1007     }).start();
1008   }
1009
1010   public synchronized boolean allFinished()
1011   {
1012     return queued == 0 && running == 0;
1013   }
1014 };