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