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