JAL-1183 use dialog queue for usage statistics prompt
[jalview.git] / src / jalview / bin / Jalview.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, 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
254                   .checkProtocol(vamsasImport);
255           if (viprotocol == jalview.io.FormatAdapter.FILE)
256           {
257             inSession = desktop.vamsasImport(new File(vamsasImport));
258           }
259           else if (viprotocol == jalview.io.FormatAdapter.URL)
260           {
261             inSession = desktop.vamsasImport(new URL(vamsasImport));
262           }
263
264         } catch (Exception e)
265         {
266           System.err.println("Exeption when importing " + vamsasImport
267                   + " as a vamsas document.");
268           e.printStackTrace();
269         }
270         if (!inSession)
271         {
272           System.err.println("Failed to import " + vamsasImport
273                   + " as a vamsas document.");
274         }
275         else
276         {
277           System.out.println("Imported Successfully into new session "
278                   + desktop.getVamsasApplication().getCurrentSession());
279         }
280       }
281       if (vamsasSession != null)
282       {
283         if (vamsasImport != null)
284         {
285           // close the newly imported session and import the Jalview specific
286           // remnants into the new session later on.
287           desktop.vamsasStop_actionPerformed(null);
288         }
289         // now join the new session
290         try
291         {
292           if (desktop.joinVamsasSession(vamsasSession))
293           {
294             System.out.println("Successfully joined vamsas session "
295                     + vamsasSession);
296           }
297           else
298           {
299             System.err.println("WARNING: Failed to join vamsas session "
300                     + vamsasSession);
301           }
302         } catch (Exception e)
303         {
304           System.err.println("ERROR: Failed to join vamsas session "
305                   + vamsasSession);
306           e.printStackTrace();
307         }
308         if (vamsasImport != null)
309         {
310           // the Jalview specific remnants can now be imported into the new
311           // session at the user's leisure.
312           Cache.log
313                   .info("Skipping Push for import of data into existing vamsas session."); // TODO:
314           // enable
315           // this
316           // when
317           // debugged
318           // desktop.getVamsasApplication().push_update();
319         }
320       }
321     }
322     long progress = -1;
323     // Finally, deal with the remaining input data.
324     if (file != null)
325     {
326       if (!headless)
327       {
328         desktop.setProgressBar("Processing commandline arguments...",
329                 progress = System.currentTimeMillis());
330       }
331       System.out.println("Opening file: " + file);
332
333       if (!file.startsWith("http://"))
334       {
335         if (!(new java.io.File(file)).exists())
336         {
337           System.out.println("Can't find " + file);
338           if (headless)
339           {
340             System.exit(1);
341           }
342         }
343       }
344
345       protocol = jalview.io.AppletFormatAdapter.checkProtocol(file);
346
347       format = new jalview.io.IdentifyFile().Identify(file, protocol);
348
349       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
350               format);
351       if (af == null)
352       {
353         System.out.println("error");
354       }
355       else
356       {
357
358         data = aparser.getValue("colour", true);
359         if (data != null)
360         {
361           data.replaceAll("%20", " ");
362
363           jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
364                   .getColour(af.getViewport().getAlignment(), data);
365
366           if (cs == null)
367           {
368             jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
369                     "white");
370             ucs.parseAppletParameter(data);
371             cs = ucs;
372           }
373
374           System.out.println("colour is " + data);
375           af.changeColour(cs);
376         }
377
378         // Must maintain ability to use the groups flag
379         data = aparser.getValue("groups", true);
380         if (data != null)
381         {
382           af.parseFeaturesFile(data,
383                   jalview.io.AppletFormatAdapter.checkProtocol(data));
384           System.out.println("Added " + data);
385         }
386         data = aparser.getValue("features", true);
387         if (data != null)
388         {
389           af.parseFeaturesFile(data,
390                   jalview.io.AppletFormatAdapter.checkProtocol(data));
391           System.out.println("Added " + data);
392         }
393
394         data = aparser.getValue("annotations", true);
395         if (data != null)
396         {
397           af.loadJalviewDataFile(data, null, null, null);
398           System.out.println("Added " + data);
399         }
400         // set or clear the sortbytree flag.
401         if (aparser.contains("sortbytree"))
402         {
403           af.getViewport().setSortByTree(true);
404         }
405         if (aparser.contains("nosortbytree"))
406         {
407           af.getViewport().setSortByTree(false);
408         }
409         data = aparser.getValue("tree", true);
410         if (data != null)
411         {
412           jalview.io.NewickFile fin = null;
413           try
414           {
415             fin = new jalview.io.NewickFile(data,
416                     jalview.io.AppletFormatAdapter.checkProtocol(data));
417             if (fin != null)
418             {
419               af.getViewport().setCurrentTree(
420                       af.ShowNewickTree(fin, data).getTree());
421               System.out.println("Added tree " + data);
422             }
423           } catch (IOException ex)
424           {
425             System.err.println("Couldn't add tree " + data);
426             ex.printStackTrace(System.err);
427           }
428         }
429         // TODO - load PDB structure(s) to alignment JAL-629
430         // (associate with identical sequence in alignment, or a specified
431         // sequence)
432
433         getFeatures = checkDasArguments(aparser);
434         if (af != null && getFeatures != null)
435         {
436           FeatureFetcher ff = startFeatureFetching(getFeatures);
437           if (ff != null)
438             while (!ff.allFinished() || af.operationInProgress())
439             {
440               // wait around until fetching is finished.
441               try
442               {
443                 Thread.sleep(100);
444               } catch (Exception e)
445               {
446
447               }
448             }
449           getFeatures = null; // have retrieved features - forget them now.
450         }
451         if (groovyscript != null)
452         {
453           // Execute the groovy script after we've done all the rendering stuff
454           // and before any images or figures are generated.
455           if (jalview.bin.Cache.groovyJarsPresent())
456           {
457             System.out.println("Executing script " + groovyscript);
458             executeGroovyScript(groovyscript, new Object[]
459             { desktop, af });
460           }
461           else
462           {
463             System.err
464                     .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
465                             + groovyscript);
466           }
467           groovyscript = null;
468         }
469         String imageName = "unnamed.png";
470         while (aparser.getSize() > 1)
471         {
472           format = aparser.nextValue();
473           file = aparser.nextValue();
474
475           if (format.equalsIgnoreCase("png"))
476           {
477             af.createPNG(new java.io.File(file));
478             imageName = (new java.io.File(file)).getName();
479             System.out.println("Creating PNG image: " + file);
480             continue;
481           }
482           else if (format.equalsIgnoreCase("imgMap"))
483           {
484             af.createImageMap(new java.io.File(file), imageName);
485             System.out.println("Creating image map: " + file);
486             continue;
487           }
488           else if (format.equalsIgnoreCase("eps"))
489           {
490             System.out.println("Creating EPS file: " + file);
491             af.createEPS(new java.io.File(file));
492             continue;
493           }
494
495           if (af.saveAlignment(file, format))
496           {
497             System.out.println("Written alignment in " + format
498                     + " format to " + file);
499           }
500           else
501           {
502             System.out.println("Error writing file " + file + " in "
503                     + format + " format!!");
504           }
505
506         }
507
508         while (aparser.getSize() > 0)
509         {
510           System.out.println("Unknown arg: " + aparser.nextValue());
511         }
512       }
513     }
514     AlignFrame startUpAlframe = null;
515     // We'll only open the default file if the desktop is visible.
516     // And the user
517     // ////////////////////
518     if (!headless && file == null && vamsasImport == null
519             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
520     {
521       file = jalview.bin.Cache.getDefault(
522               "STARTUP_FILE",
523               jalview.bin.Cache.getDefault("www.jalview.org",
524                       "http://www.jalview.org")
525                       + "/examples/exampleFile_2_7.jar");
526       if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar"))
527       {
528         // hardwire upgrade of the startup file
529         file.replace("_2_3.jar", "_2_7.jar");
530         // and remove the stale setting
531         jalview.bin.Cache.removeProperty("STARTUP_FILE");
532       }
533
534       protocol = "File";
535
536       if (file.indexOf("http:") > -1)
537       {
538         protocol = "URL";
539       }
540
541       if (file.endsWith(".jar"))
542       {
543         format = "Jalview";
544       }
545       else
546       {
547         format = new jalview.io.IdentifyFile().Identify(file, protocol);
548       }
549
550       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
551               format);
552       getFeatures = checkDasArguments(aparser);
553       // extract groovy arguments before anything else.
554     }
555     // If the user has specified features to be retrieved,
556     // or a groovy script to be executed, do them if they
557     // haven't been done already
558     // fetch features for the default alignment
559     if (getFeatures != null)
560     {
561       if (startUpAlframe != null)
562       {
563         startFeatureFetching(getFeatures);
564       }
565     }
566     // Once all other stuff is done, execute any groovy scripts (in order)
567     if (groovyscript != null)
568     {
569       if (jalview.bin.Cache.groovyJarsPresent())
570       {
571         System.out.println("Executing script " + groovyscript);
572         executeGroovyScript(groovyscript, new Object[]
573         { desktop, startUpAlframe });
574       }
575       else
576       {
577         System.err
578                 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
579                         + groovyscript);
580       }
581     }
582     // and finally, turn off batch mode indicator - if the desktop still exists
583     if (desktop != null)
584     {
585       if (progress != -1)
586       {
587         desktop.setProgressBar(null, progress);
588       }
589       desktop.setInBatchMode(false);
590     }
591   }
592
593   private static void startUsageStats(final Desktop desktop)
594   {
595     /**
596      * start a User Config prompt asking if we can log usage statistics.
597      */
598     jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
599             desktop.desktop,
600             "USAGESTATS",
601             "Jalview Usage Statistics",
602             "Do you want to help make Jalview better by enabling "
603                     + "the collection of usage statistics with Google Analytics ?"
604                     + "\n\n(you can enable or disable usage tracking in the preferences)",
605             new Runnable()
606             {
607               public void run()
608               {
609                 Cache.log
610                         .info("Initialising googletracker for usage stats.");
611                 Cache.initGoogleTracker();
612                 Cache.log.debug("Tracking enabled.");
613               }
614             }, new Runnable()
615             {
616               public void run()
617               {
618                 Cache.log.info("Not enabling Google Tracking.");
619               }
620             }, null, true);
621     desktop.addDialogThread(prompter);
622   }
623
624   /**
625    * Locate the given string as a file and pass it to the groovy interpreter.
626    * 
627    * @param groovyscript
628    *          the script to execute
629    * @param jalviewContext
630    *          the Jalview Desktop object passed in to the groovy binding as the
631    *          'Jalview' object.
632    */
633   private static void executeGroovyScript(String groovyscript,
634           Object[] jalviewContext)
635   {
636     if (jalviewContext == null)
637     {
638       System.err
639               .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
640     }
641     /**
642      * for scripts contained in files
643      */
644     File tfile = null;
645     /**
646      * script's URI
647      */
648     URL sfile = null;
649     if (groovyscript.trim().equals("STDIN"))
650     {
651       // read from stdin into a tempfile and execute it
652       try
653       {
654         tfile = File.createTempFile("jalview", "groovy");
655         PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
656                 new FileOutputStream(tfile)));
657         BufferedReader br = new BufferedReader(
658                 new java.io.InputStreamReader(System.in));
659         String line = null;
660         while ((line = br.readLine()) != null)
661         {
662           outfile.write(line + "\n");
663         }
664         br.close();
665         outfile.flush();
666         outfile.close();
667
668       } catch (Exception ex)
669       {
670         System.err.println("Failed to read from STDIN into tempfile "
671                 + ((tfile == null) ? "(tempfile wasn't created)" : tfile
672                         .toString()));
673         ex.printStackTrace();
674         return;
675       }
676       try
677       {
678         sfile = tfile.toURI().toURL();
679       } catch (Exception x)
680       {
681         System.err
682                 .println("Unexpected Malformed URL Exception for temporary file created from STDIN: "
683                         + tfile.toURI());
684         x.printStackTrace();
685         return;
686       }
687     }
688     else
689     {
690       try
691       {
692         sfile = new URI(groovyscript).toURL();
693       } catch (Exception x)
694       {
695         tfile = new File(groovyscript);
696         if (!tfile.exists())
697         {
698           System.err.println("File '" + groovyscript + "' does not exist.");
699           return;
700         }
701         if (!tfile.canRead())
702         {
703           System.err.println("File '" + groovyscript + "' cannot be read.");
704           return;
705         }
706         if (tfile.length() < 1)
707         {
708           System.err.println("File '" + groovyscript + "' is empty.");
709           return;
710         }
711         try
712         {
713           sfile = tfile.getAbsoluteFile().toURI().toURL();
714         } catch (Exception ex)
715         {
716           System.err.println("Failed to create a file URL for "
717                   + tfile.getAbsoluteFile());
718           return;
719         }
720       }
721     }
722     boolean success = false;
723     try
724     {
725       /*
726        * The following code performs the GroovyScriptEngine invocation using
727        * reflection, and is equivalent to this fragment from the embedding
728        * groovy documentation on the groovy site: <code> import
729        * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
730        * 
731        * String[] roots = new String[] { "/my/groovy/script/path" };
732        * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
733        * = new Binding(); binding.setVariable("input", "world");
734        * gse.run("hello.groovy", binding); </code>
735        */
736       Class[] bspec;
737       Object[] binding;
738       int blen = ((jalviewContext[0] == null) ? 0 : 1)
739               + ((jalviewContext[1] == null) ? 0 : 1);
740       String cnames[] = new String[]
741       { "Jalview", "currentAlFrame" };
742       bspec = new Class[blen * 2];
743       binding = new Object[blen * 2];
744       blen = 0;
745       ClassLoader cl = null;
746       Map vbinding = new Hashtable();
747       for (int jc = 0; jc < jalviewContext.length; jc++)
748       {
749         if (jalviewContext[jc] != null)
750         {
751           if (cl == null)
752           {
753             cl = jalviewContext[jc].getClass().getClassLoader();
754           }
755           bspec[blen * 2] = String.class;
756           bspec[blen * 2 + 1] = Object.class;
757           binding[blen * 2] = cnames[jc];
758           binding[blen * 2 + 1] = jalviewContext[jc];
759           vbinding.put(cnames[jc], jalviewContext[jc]);
760           blen++;
761         }
762       }
763       Class gbindingc = cl.loadClass("groovy.lang.Binding");
764       Constructor gbcons;
765       Object gbinding;
766       try
767       {
768         gbcons = gbindingc.getConstructor(Map.class);
769         gbinding = gbcons.newInstance(vbinding);
770       } catch (NoSuchMethodException x)
771       {
772         // old style binding config - using series of string/object values to
773         // setVariable.
774         gbcons = gbindingc.getConstructor(null);
775         gbinding = gbcons.newInstance(null);
776         java.lang.reflect.Method setvar = gbindingc.getMethod(
777                 "setVariable", bspec);
778         setvar.invoke(gbinding, binding);
779       }
780       ;
781       Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
782       Constructor gseccons = gsec.getConstructor(new Class[]
783       { URL[].class }); // String[].class });
784       Object gse = gseccons.newInstance(new Object[]
785       { new URL[]
786       { sfile } }); // .toString() } });
787       java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
788       { String.class, gbindingc });
789       run.invoke(gse, new Object[]
790       { sfile.toString(), gbinding });
791       success = true;
792     } catch (Exception e)
793     {
794       System.err.println("Exception Whilst trying to execute file " + sfile
795               + " as a groovy script.");
796       e.printStackTrace(System.err);
797
798     }
799     if (success && groovyscript.equals("STDIN"))
800     {
801       // delete temp file that we made - but only if it was successfully
802       // executed
803       tfile.delete();
804     }
805   }
806
807   /**
808    * Check commandline for any das server definitions or any fetchfrom switches
809    * 
810    * @return vector of DAS source nicknames to retrieve from
811    */
812   private static Vector checkDasArguments(ArgsParser aparser)
813   {
814     Vector source = null;
815     String data;
816     String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
817     while ((data = aparser.getValue("dasserver", true)) != null)
818     {
819       String nickname = null;
820       String url = null;
821       boolean seq = false, feat = true;
822       int pos = data.indexOf('=');
823       // determine capabilities
824       if (pos > 0)
825       {
826         nickname = data.substring(0, pos);
827       }
828       url = data.substring(pos + 1);
829       if (url != null
830               && (url.startsWith("http:") || url
831                       .startsWith("sequence:http:")))
832       {
833         if (nickname == null)
834         {
835           nickname = url;
836         }
837         if (locsources == null)
838         {
839           locsources = "";
840         }
841         else
842         {
843           locsources += "\t";
844         }
845         locsources = locsources + nickname + "|" + url;
846         System.err
847                 .println("NOTE! dasserver parameter not yet really supported (got args of "
848                         + nickname + "|" + url);
849         if (source == null)
850         {
851           source = new Vector();
852         }
853         source.addElement(nickname);
854       }
855     } // loop until no more server entries are found.
856     if (locsources != null && locsources.indexOf('|') > -1)
857     {
858       Cache.log.debug("Setting local source list in properties file to:\n"
859               + locsources);
860       Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
861     }
862     while ((data = aparser.getValue("fetchfrom", true)) != null)
863     {
864       System.out.println("adding source '" + data + "'");
865       if (source == null)
866       {
867         source = new Vector();
868       }
869       source.addElement(data);
870     }
871     return source;
872   }
873
874   /**
875    * start a feature fetcher for every alignment frame
876    * 
877    * @param dasSources
878    */
879   private static FeatureFetcher startFeatureFetching(final Vector dasSources)
880   {
881     FeatureFetcher ff = new FeatureFetcher();
882     AlignFrame afs[] = Desktop.getAlignframes();
883     if (afs == null || afs.length == 0)
884     {
885       return null;
886     }
887     for (int i = 0; i < afs.length; i++)
888     {
889       ff.addFetcher(afs[i], dasSources);
890     }
891     return ff;
892   }
893 }
894
895 /**
896  * Notes: this argParser does not distinguish between parameter switches,
897  * parameter values and argument text. If an argument happens to be identical to
898  * a parameter, it will be taken as such (even though it didn't have a '-'
899  * prefixing it).
900  * 
901  * @author Andrew Waterhouse and JBP documented.
902  * 
903  */
904 class ArgsParser
905 {
906   Vector vargs = null;
907
908   public ArgsParser(String[] args)
909   {
910     vargs = new Vector();
911     for (int i = 0; i < args.length; i++)
912     {
913       String arg = args[i].trim();
914       if (arg.charAt(0) == '-')
915       {
916         arg = arg.substring(1);
917       }
918       vargs.addElement(arg);
919     }
920   }
921
922   /**
923    * check for and remove first occurence of arg+parameter in arglist.
924    * 
925    * @param arg
926    * @return return the argument following the given arg if arg was in list.
927    */
928   public String getValue(String arg)
929   {
930     return getValue(arg, false);
931   }
932
933   public String getValue(String arg, boolean utf8decode)
934   {
935     int index = vargs.indexOf(arg);
936     String dc = null, ret = null;
937     if (index != -1)
938     {
939       ret = vargs.elementAt(index + 1).toString();
940       vargs.removeElementAt(index);
941       vargs.removeElementAt(index);
942       if (utf8decode && ret != null)
943       {
944         try
945         {
946           dc = URLDecoder.decode(ret, "UTF-8");
947           ret = dc;
948         } catch (Exception e)
949         {
950           // TODO: log failure to decode
951         }
952       }
953     }
954     return ret;
955   }
956
957   /**
958    * check for and remove first occurence of arg in arglist.
959    * 
960    * @param arg
961    * @return true if arg was present in argslist.
962    */
963   public boolean contains(String arg)
964   {
965     if (vargs.contains(arg))
966     {
967       vargs.removeElement(arg);
968       return true;
969     }
970     else
971     {
972       return false;
973     }
974   }
975
976   public String nextValue()
977   {
978     return vargs.remove(0).toString();
979   }
980
981   public int getSize()
982   {
983     return vargs.size();
984   }
985
986 }
987
988 /**
989  * keep track of feature fetching tasks.
990  * 
991  * @author JimP
992  * 
993  */
994 class FeatureFetcher
995 {
996   /*
997    * TODO: generalise to track all jalview events to orchestrate batch
998    * processing events.
999    */
1000
1001   private int queued = 0;
1002
1003   private int running = 0;
1004
1005   public FeatureFetcher()
1006   {
1007
1008   }
1009
1010   public void addFetcher(final AlignFrame af, final Vector dasSources)
1011   {
1012     final long id = System.currentTimeMillis();
1013     queued++;
1014     final FeatureFetcher us = this;
1015     new Thread(new Runnable()
1016     {
1017
1018       public void run()
1019       {
1020         synchronized (us)
1021         {
1022           queued--;
1023           running++;
1024         }
1025
1026         af.setProgressBar("DAS features being retrieved...", id);
1027         af.featureSettings_actionPerformed(null);
1028         af.featureSettings.fetchDasFeatures(dasSources, true);
1029         af.setProgressBar(null, id);
1030         synchronized (us)
1031         {
1032           running--;
1033         }
1034       }
1035     }).start();
1036   }
1037
1038   public synchronized boolean allFinished()
1039   {
1040     return queued == 0 && running == 0;
1041   }
1042 };