Friday, April 22, 2011

Invoking a groovy script from a Java class

Here is a small script to send an email as \util\SendEmail.groovy
//Read properties
def emailHost = config['email.host']
def email = config['monitor.fromAddress']

//Sending an email notification
new AntBuilder().mail(mailhost:"${emailHost}", messagemimetype:'text/html',
            subject:"${sub}"){
          from(address:"${email}")
          to(address:"${email}")
          message("${content}")
      }

Now we need to invoke the script by injecting the properties into the script.
Here is the Java logic to invoke the script. There few other alternative way to invoke the script but this is one of them...



      /**
       *
       * @param message
       */
      private static void emailException(String message) {
            try {
                  GroovyScriptEngine gse = new GroovyScriptEngine(".\\util");
                  Binding binding = new Binding();
                  binding.setVariable("sub", "An exception notification - " + InetAddress.getLocalHost().getHostName());
                  binding.setVariable("content", message);
                  binding.setVariable("config", PropertyMgr.getInstance()); //this is illustrate injecting a Java object instance.
                  gse.run("SendEmail.groovy", binding);
           
            } catch (IOException e1) {
                  e1.printStackTrace();
                  logger.error(e1);
            } catch (ResourceException e1) {
                  e1.printStackTrace();
                  logger.error(e1);
            } catch (ScriptException e1) {
                  e1.printStackTrace();
                  logger.error(e1);
            }
      }

Share you comments!!

No comments: