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