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