Sunday, October 28, 2012

Posting XML request using Groovy's HttpBuilder


       

Here I would like discuss few points on how to use HttpBuilder to post xml request message onto service url.

       /**
        * Creates a User based on params.
        *
        * @param params
        * @return
        */
       def submitMessage(Map params) {
             
              def http =  HttpBuilder();
              http.post(buildRequestMap(params, buildRequestXML), processScccess);
       }
      
      
       /**
        * Method to create properties map to post over the HTTP.
        * @param reqParams
        * @param reqCreatorClosure
        * @return
        */
       Map buildRequestMap(Map reqParams, Closure reqCreatorClosure) {

              Map options = [:];
              Map h = [:];

              h.'Content-Type' = 'text/xml';
              options.'headers' = h;
              options.'uri' = "http://localhost/test/processServlet";
             
              if(null != reqCreatorClosure) {
                     Object returnVal = reqCreatorClosure.call(reqParams);
                     options.put("body", returnVal);
              }
              return options;
       }

      
       /**
        * Closure to create a request xml based on params
        */
       def buildRequestXML = { Map params ->
             
              def writer = new StringWriter()
              def xml = new MarkupBuilder(writer)
              xml.request() {
                     message(messageId: "test123") {
                        "Test Message"
                     }
              }
              return writer.toString();
       }
      
       /**
        * Closure the process a successful response.
        */
       def processScccess = { resp, xml ->
              println "My response handler got response: ${resp.statusLine}"
              println "Response = ${xml}" // print response reader
       }

Thank you..

Send an email in Groovy using AntBuilder

Purpose: How to send an email with Groovy script.
The following example shows how can we send an email using Groovy script. You can create other type email content by setting the appropriate mime type.

In this example, we are trying to send an email notification with table of available topic from the repository.

Using groovy xml markup builder, you can most of the html tags, as shown below to create such paragraphs, hyperlinks etc..

Using AntBuilder, it allows us to attach documents as an email attachments as well.
  

//preparing an email notification
def repositoryDir = "http://prolificworks.blogspot.com"
def emailHost = mailserver_host
def fromEmail = youremail
def toEmail = receipts_email

def writer = new StringWriter()
new groovy.xml.MarkupBuilder(writer).html {
    head {
        style(type:"text/css", ''' 
        .headerRow { 
        margin: 10px; 
        padding: 1px; 
        background-color: #AAAAAA
        } 
        .lineItemRow { 
        margin: 10px; 
        padding: 1px; 
        background-color: #CCCCCC
        } 
    ''') 
    }
    body {
    h3("A Sample notification email from ProlificWorks.)
        table {
            tr('class':'headerRow') {
                th('S.No'); th('Topic Name'); th('Date')
            }
            counter = 1
            fileList.findAll {
                def temp = it
                tr('class':'lineItemRow') {
                    td("${counter}")
                    td(temp.Name)
                    td(temp.CreatedTime)
                }
                counter++
            }
       }
       a(href:"${repositoryDir}", "Repository Location:")
       p("Report Generated: ${new Date()}")
       p("For more information, you can contact us.")
    }
}

//Sending an email notification
if(fileList.size() > 0) {
    def ant = new AntBuilder()
    ant.mail(mailhost:"${emailHost}", messagemimetype:'text/html',
             subject:"A Sample notification email from ProlificWorks."){
        from(address:"${fromEmail}")
        to(address:"${toEmail}")
        message(writer)
        attachments(){
           fileset(dir:"${repoDirPath}"){
             include(name:"<>")
        }
    }
    }   
}

I hoe this post helps you, you can post comment/question for more information. Thank you for reading the post. Let us explore more Groovy together.

Monday, May 14, 2012

Whats in Groovy

Get today's date in your desired format.


def today = Calendar.getInstance()
def todayFormatted = String.format('%tm/%<td/%<tY', today)
println todayFormatted


Run the Groovy Console, you will see the date as 05/15/2012 (of course if would be current date)