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