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