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