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