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