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