safer retrieval of groovy scripts from URLs
[jalview.git] / src / jalview / bin / Jalview.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.bin;
20
21 import java.io.BufferedReader;
22 import java.io.File;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.OutputStreamWriter;
26 import java.io.PrintWriter;
27 import java.lang.reflect.Constructor;
28 import java.net.URL;
29 import java.util.*;
30
31 import javax.swing.*;
32
33 import jalview.gui.*;
34 import jalview.io.AppletFormatAdapter;
35
36 /**
37  * Main class for Jalview Application <br>
38  * <br>
39  * start with java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview
40  * 
41  * @author $author$
42  * @version $Revision$
43  */
44 public class Jalview
45 {
46
47   /**
48    * main class for Jalview application
49    * 
50    * @param args
51    *                open <em>filename</em>
52    */
53   public static void main(String[] args)
54   {
55     System.out.println("Java version: "
56             + System.getProperty("java.version"));
57     System.out.println(System.getProperty("os.arch") + " "
58             + System.getProperty("os.name") + " "
59             + System.getProperty("os.version"));
60
61     ArgsParser aparser = new ArgsParser(args);
62     boolean headless = false;
63
64     if (aparser.contains("help") || aparser.contains("h"))
65     {
66       System.out
67               .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
68                       + "-nodisplay\tRun Jalview without User Interface.\n"
69                       + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
70                       + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
71                       + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
72                       + "-features FILE\tUse the given file to mark features on the alignment.\n"
73                       + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
74                       + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
75                       + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
76                       + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
77                       + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
78                       + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
79                       + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
80                       + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
81                       + "-png FILE\tCreate PNG image FILE from alignment.\n"
82                       + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
83                       + "-eps FILE\tCreate EPS file FILE from alignment."
84                       + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires."
85                       + "-noquestionnaire\tTurn off questionnaire check."
86                       + "-dasserver nickname=URL\tAdd and enable a das server with given nickname (alphanumeric or underscores only) for retrieval of features for all alignments."
87                       + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them."
88                       + "-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)"
89                       + "\n\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
90       System.exit(0);
91     }
92
93     Cache.loadProperties(aparser.getValue("props")); // must do this before
94     // anything else!
95
96     if (aparser.contains("nodisplay"))
97     {
98       System.setProperty("java.awt.headless", "true");
99     }
100     if (System.getProperty("java.awt.headless") != null
101             && System.getProperty("java.awt.headless").equals("true"))
102     {
103       headless = true;
104     }
105
106     try
107     {
108       Cache.initLogger();
109     } catch (java.lang.NoClassDefFoundError error)
110     {
111       error.printStackTrace();
112       System.out
113               .println("\nEssential logging libraries not found."
114                       + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
115       System.exit(0);
116     }
117
118     Desktop desktop = null;
119
120     try
121     {
122       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()
123       // UIManager.getCrossPlatformLookAndFeelClassName()
124               // "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"
125               // "javax.swing.plaf.metal.MetalLookAndFeel"
126               // "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"
127               // "com.sun.java.swing.plaf.motif.MotifLookAndFeel"
128
129               );
130     } catch (Exception ex)
131     {
132     }
133     if (!headless)
134     {
135       desktop = new Desktop();
136       desktop.setVisible(true);
137       desktop.discoverer.start();
138       if (!aparser.contains("noquestionnaire"))
139       {
140         String url = aparser.getValue("questionnaire");
141         if (url != null)
142         {
143           // Start the desktop questionnaire prompter with the specified
144           // questionnaire
145           Cache.log.debug("Starting questionnaire url at " + url);
146           desktop.checkForQuestionnaire(url);
147         }
148         else
149         {
150           if (Cache.getProperty("NOQUESTIONNAIRES") == null)
151           {
152             // Start the desktop questionnaire prompter with the specified
153             // questionnaire
154             // String defurl =
155             // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
156             // //
157             String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
158             Cache.log.debug("Starting questionnaire with default url: "
159                     + defurl);
160             desktop.checkForQuestionnaire(defurl);
161
162           }
163         }
164       }
165     }
166
167     String file = null, protocol = null, format = null, data = null;
168     jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
169     Vector getFeatures = null; // vector of das source nicknames to fetch features from
170     // loading is done.
171     String groovyscript = null; // script to execute after all loading is completed one way or another
172     // extract groovy argument and execute if necessary
173     groovyscript = aparser.getValue("groovy");
174     file = aparser.getValue("open");
175
176     if (file == null && desktop == null)
177     {
178       System.out.println("No files to open!");
179       System.exit(1);
180     }
181
182     if (file != null)
183     {
184       System.out.println("Opening file: " + file);
185
186       if (!file.startsWith("http://"))
187       {
188         if (!(new java.io.File(file)).exists())
189         {
190           System.out.println("Can't find " + file);
191           if (headless)
192           {
193             System.exit(1);
194           }
195         }
196       }
197
198       protocol = checkProtocol(file);
199
200       format = new jalview.io.IdentifyFile().Identify(file, protocol);
201
202       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
203               format);
204
205       if (af == null)
206       {
207         System.out.println("error");
208         return;
209       }
210
211       data = aparser.getValue("colour");
212       if (data != null)
213       {
214         data.replaceAll("%20", " ");
215
216         jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
217                 .getColour(af.getViewport().getAlignment(), data);
218
219         if (cs == null)
220         {
221           jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
222                   "white");
223           ucs.parseAppletParameter(data);
224           cs = ucs;
225         }
226
227         System.out.println("colour is " + data);
228         af.changeColour(cs);
229       }
230
231       // Must maintain ability to use the groups flag
232       data = aparser.getValue("groups");
233       if (data != null)
234       {
235         af.parseFeaturesFile(data, checkProtocol(data));
236         System.out.println("Added " + data);
237       }
238       data = aparser.getValue("features");
239       if (data != null)
240       {
241         af.parseFeaturesFile(data, checkProtocol(data));
242         System.out.println("Added " + data);
243       }
244
245       data = aparser.getValue("annotations");
246       if (data != null)
247       {
248         af.loadJalviewDataFile(data);
249         System.out.println("Added " + data);
250       }
251       data = aparser.getValue("tree");
252       if (data != null)
253       {
254         jalview.io.NewickFile fin = null;
255         try
256         {
257           fin = new jalview.io.NewickFile(data, checkProtocol(data));
258           if (fin != null)
259           {
260             af.getViewport().setCurrentTree(
261                     af.ShowNewickTree(fin, data).getTree());
262             System.out.println("Added tree " + data);
263           }
264         } catch (IOException ex)
265         {
266           System.err.println("Couldn't add tree " + data);
267           ex.printStackTrace(System.err);
268         }
269       }
270       getFeatures = checkDasArguments(aparser);
271       if (af != null && getFeatures!=null)
272       {
273         startFeatureFetching(getFeatures); 
274         // need to block until fetching is complete.
275         while (af.operationInProgress())
276         {
277           // wait around until fetching is finished.
278           try {
279             Thread.sleep(10);
280           } catch (Exception e)
281           {
282             
283           }
284         }
285       }
286       if (groovyscript!=null)
287       {
288         // Execute the groovy script after we've  done all the rendering stuff
289         // and before any images or figures are generated.
290         if (jalview.bin.Cache.groovyJarsPresent())
291         {
292           System.out.println("Executing script "+groovyscript);
293           executeGroovyScript(groovyscript, desktop);
294         } else {
295           System.err.println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "+groovyscript);
296         }
297         groovyscript = null;
298       }
299       String imageName = "unnamed.png";
300       while (aparser.getSize() > 1)
301       {
302         format = aparser.nextValue();
303         file = aparser.nextValue();
304
305         if (format.equalsIgnoreCase("png"))
306         {
307           af.createPNG(new java.io.File(file));
308           imageName = (new java.io.File(file)).getName();
309           System.out.println("Creating PNG image: " + file);
310           continue;
311         }
312         else if (format.equalsIgnoreCase("imgMap"))
313         {
314           af.createImageMap(new java.io.File(file), imageName);
315           System.out.println("Creating image map: " + file);
316           continue;
317         }
318         else if (format.equalsIgnoreCase("eps"))
319         {
320           System.out.println("Creating EPS file: " + file);
321           af.createEPS(new java.io.File(file));
322           continue;
323         }
324
325         if (af.saveAlignment(file, format))
326         {
327           System.out.println("Written alignment in " + format
328                   + " format to " + file);
329         }
330         else
331         {
332           System.out.println("Error writing file " + file + " in " + format
333                   + " format!!");
334         }
335
336       }
337
338       while (aparser.getSize() > 0)
339       {
340         System.out.println("Unknown arg: " + aparser.nextValue());
341       }
342     }
343     AlignFrame startUpAlframe = null;
344     // We'll only open the default file if the desktop is visible.
345     // And the user
346     // ////////////////////
347     if (!headless && file == null
348             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
349     {
350       file = jalview.bin.Cache.getDefault("STARTUP_FILE",
351               "http://www.jalview.org/examples/exampleFile_2_3.jar");
352
353       protocol = "File";
354
355       if (file.indexOf("http:") > -1)
356       {
357         protocol = "URL";
358       }
359
360       if (file.endsWith(".jar"))
361       {
362         format = "Jalview";
363       }
364       else
365       {
366         format = new jalview.io.IdentifyFile().Identify(file, protocol);
367       }
368
369       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
370               format);
371       getFeatures = checkDasArguments(aparser);
372       // extract groovy arguments before anything else.
373     }
374     // Once all loading is done. Retrieve features.
375     if (getFeatures!=null)
376     {
377       if (startUpAlframe!=null)
378       {
379         startFeatureFetching(getFeatures);
380       }
381     }
382     if (groovyscript!=null)
383     {
384       if (jalview.bin.Cache.groovyJarsPresent())
385       {
386         System.out.println("Executing script "+groovyscript);
387         executeGroovyScript(groovyscript, desktop);
388       } else {
389         System.err.println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "+groovyscript);
390       }
391     }
392
393     // Once all other stuff is done, execute any groovy scripts (in order)
394   }
395   /**
396    * Locate the given string as a file and pass it to the groovy interpreter.
397    * @param groovyscript the script to execute
398    * @param jalviewContext the Jalview Desktop object passed in to the groovy binding as the 'Jalview' object.
399    */
400   private static void executeGroovyScript(String groovyscript, Object jalviewContext)
401   {
402     if (jalviewContext==null)
403     {
404       System.err.println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
405     }
406     File sfile = null;
407     if (groovyscript.trim().equals("STDIN"))
408     {
409       // read from stdin into a tempfile and execute it
410       try {
411         sfile = File.createTempFile("jalview", "groovy");
412         PrintWriter outfile = new PrintWriter(new OutputStreamWriter(new FileOutputStream(sfile)));
413         BufferedReader br = new BufferedReader(new java.io.InputStreamReader(System.in));
414         String line=null;
415         while ((line=br.readLine())!=null)
416         {
417           outfile.write(line+"\n");
418         }
419         br.close();
420         outfile.flush();
421         outfile.close();
422         
423       } catch (Exception ex)
424       {
425         System.err.println("Failed to read from STDIN into tempfile "+((sfile==null) ? "(tempfile wasn't created)" : sfile.toString()));
426         ex.printStackTrace();
427         return;
428       }
429     } else {
430       sfile = new File(groovyscript);
431     }
432     if (!sfile.exists())
433     {
434       System.err.println("File '"+groovyscript+"' does not exist.");
435       return;
436     }
437     if (!sfile.canRead())
438     {
439       System.err.println("File '"+groovyscript+"' cannot be read.");
440       return;
441     }
442     if (sfile.length()<1)
443     {
444       System.err.println("File '"+groovyscript+"' is empty.");
445       return;
446     }
447     boolean success = false;
448     try {
449       /* The following code performs the GroovyScriptEngine invocation using reflection,
450        * and is equivalent to this fragment from the embedding groovy documentation on 
451        * the groovy site:
452        * <code>
453          import groovy.lang.Binding;
454          import groovy.util.GroovyScriptEngine;
455         
456          String[] roots = new String[] { "/my/groovy/script/path" };
457          GroovyScriptEngine gse = new GroovyScriptEngine(roots);
458          Binding binding = new Binding();
459          binding.setVariable("input", "world");
460          gse.run("hello.groovy", binding);
461          * </code>
462          */
463         ClassLoader cl = jalviewContext.getClass().getClassLoader();
464         Class   gbindingc = cl.loadClass("groovy.lang.Binding");
465         Constructor gbcons = gbindingc.getConstructor(null);
466         Object gbinding = gbcons.newInstance(null);
467         java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable", new Class[] { String.class, Object.class} );
468         setvar.invoke(gbinding, new Object[] { "Jalview", jalviewContext});
469         Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
470         Constructor gseccons = gsec.getConstructor(new Class[] { URL[].class } ); // String[].class });
471         Object gse = gseccons.newInstance(new Object[] { new URL[] { sfile.toURL() } }); // .toString() } });
472         java.lang.reflect.Method run = gsec.getMethod("run", new Class[]{ String.class, gbindingc });
473         run.invoke(gse, new Object[] { sfile.getName(), gbinding });
474         success = true;
475     } catch (Exception e)
476     {
477       System.err.println("Exception Whilst trying to execute file "+sfile+" as a groovy script.");
478       e.printStackTrace(System.err);
479       
480     }
481     if (success && groovyscript.equals("STDIN"))
482     {
483       // delete temp file that we made - but only if it was successfully executed
484       sfile.delete();
485     }
486   }
487   /**
488    * Check commandline for any das server definitions or any fetchfrom switches
489    * @return vector of DAS source nicknames to retrieve from
490    */
491   private static Vector checkDasArguments(ArgsParser aparser)
492   {
493     Vector source=null;
494     String data;
495     String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
496     while ((data = aparser.getValue("dasserver"))!=null)
497     {
498       String nickname = null;
499       String url = null;
500       int pos = data.indexOf('=');
501       if (pos > 0)
502       {
503         nickname = data.substring(0, pos);
504       }
505       url = data.substring(pos + 1);
506       if (url != null && url.startsWith("http:"))
507       {
508         if (nickname == null)
509         {
510           nickname = url;
511         }
512         if (locsources==null)
513         {
514           locsources="";
515         } else {
516           locsources+="\t";
517         }
518         locsources=locsources+nickname+"|"+url;
519         System.err
520                 .println("NOTE! dasserver parameter not yet really supported (got args of "
521                         + nickname + "|" + url);
522         if (source==null)
523         {
524           source = new Vector();
525         }
526         source.addElement(nickname);
527       }
528     } // loop until no more server entries are found.
529     if (locsources!=null && locsources.indexOf('|')>-1)
530     {
531       Cache.log.debug("Setting local source list in properties file to:\n"+locsources);
532       Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
533     }
534     while ((data = aparser.getValue("fetchfrom"))!=null)
535     {
536       System.out.println("adding source '"+data+"'");
537       if (source==null)
538       {
539         source = new Vector();
540       }
541       source.addElement(data);
542     }
543     return source;
544   }
545   /**
546    * start a feature fetcher for every alignment frame
547    * @param dasSources
548    */
549   private static void startFeatureFetching(final Vector dasSources)
550   {
551     AlignFrame afs[] = Desktop.getAlignframes();
552     if (afs==null || afs.length==0)
553     {
554       return;
555     }
556     for (int i = 0; i<afs.length; i++)
557     {
558       final AlignFrame af = afs[i];
559       SwingUtilities.invokeLater(new Runnable() {
560
561         public void run()
562         { 
563           af.featureSettings_actionPerformed(null);
564           af.featureSettings.fetchDasFeatures(dasSources);
565         }
566       });
567     }
568   }
569
570   private static String checkProtocol(String file)
571   {
572     String protocol = jalview.io.FormatAdapter.FILE;
573
574     if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
575     {
576       protocol = jalview.io.FormatAdapter.URL;
577     }
578     return protocol;
579   }
580 }
581
582 /**
583  * Notes: this argParser does not distinguish between parameter switches,
584  * parameter values and argument text. If an argument happens to be identical
585  * to a parameter, it will be taken as such (even though it didn't have a '-' prefixing it).
586  * 
587  * @author Andrew Waterhouse and JBP documented.
588  *
589  */
590 class ArgsParser
591 {
592   Vector vargs = null;
593
594   public ArgsParser(String[] args)
595   {
596     vargs = new Vector();
597     for (int i = 0; i < args.length; i++)
598     {
599       String arg = args[i].trim();
600       if (arg.charAt(0) == '-')
601       {
602         arg = arg.substring(1);
603       }
604       vargs.addElement(arg);
605     }
606   }
607   /**
608    * check for and remove first occurence of arg+parameter in arglist.
609    * @param arg
610    * @return return the argument following the given arg if arg was in list.
611    */
612   public String getValue(String arg)
613   {
614     int index = vargs.indexOf(arg);
615     String ret = null;
616     if (index != -1)
617     {
618       ret = vargs.elementAt(index + 1).toString();
619       vargs.removeElementAt(index);
620       vargs.removeElementAt(index);
621     }
622     return ret;
623   }
624   /**
625    * check for and remove first occurence of arg in arglist.
626    * @param arg
627    * @return true if arg was present in argslist.
628    */
629   public boolean contains(String arg)
630   {
631     if (vargs.contains(arg))
632     {
633       vargs.removeElement(arg);
634       return true;
635     }
636     else
637     {
638       return false;
639     }
640   }
641
642   public String nextValue()
643   {
644     return vargs.remove(0).toString();
645   }
646
647   public int getSize()
648   {
649     return vargs.size();
650   }
651
652 }