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