Anchit Agarwal
Anchit Agarwal

Reputation: 25

Groovy script to Grails app

Well I am new to Groovy/Grails. I have written a Groovy script that uses RESTClient to make HTTP POST request to JIRA server. The POST request sends a JQL query and receives the result in JSON format. Here's the full code:

import groovyx.net.http.RESTClient;
import groovyx.net.http.HttpResponseDecorator;
import org.apache.http.HttpRequest;
import org.apache.http.protocol.HttpContext;
import org.apache.http.HttpRequestInterceptor;
import groovy.json.JsonSlurper;
import static groovyx.net.http.Method.*
import static groovyx.net.http.ContentType.*

@Grab(value = 'org.codehaus.groovy:groovy-all:2.1.6', 
      initClass = false)
@Grapes([
@Grab(group = 'org.codehaus.groovy.modules.http-builder', 
      module = 'http-builder', version = '0.5.2'),
@GrabExclude('org.codehaus.groovy:groovy')
])

// connect to JIRA
def jiraApiUrl = 'http://my-jira.com/rest/api/2/'
def jiraClient = new RESTClient(jiraApiUrl);

// authentication
def basic = 'Basic ' + 'username:password'.bytes.encodeBase64().toString()
jiraClient.client.addRequestInterceptor (
new HttpRequestInterceptor() {
    void process(HttpRequest httpRequest, 
                 HttpContext httpContext) {
                      httpRequest.addHeader('Authorization', basic)
      }
    })

// http post method
def uriPath = 'search'
def param = [maxResults : 1, jql : '<jql-query>']

def Issues = jiraClient.post(requestContentType : JSON, path : uriPath, body : param)

def slurpedIssues = new JsonSlurper().parseText(Issues.data.toString())

println Issues.data.total

I need to migrate this script to a Grails app. Any suggestions as to how to do the same?

Upvotes: 1

Views: 977

Answers (3)

Motilal
Motilal

Reputation: 276

I strongly believe that the service response will be directly rendered to JSON

  //your controller 
    class AbcController{

    //your action   
    def save() {
    render(abcService.save(params) as JSON)//your service response now been rendered to JSON
        }

    }

//your service class    class AbcService {
    def save(params){
     ....
     return something
    }
}

Upvotes: 0

Nguyen Le
Nguyen Le

Reputation: 58

Putting the logic into Service object will give you the ability to do dependency injection, which is native to grails services.

Also, you should consider using AsyncHTTPBuilder if your app has many users trying to make requests.

Upvotes: 0

Armand
Armand

Reputation: 24393

  1. Define dependencies in BuildConfig (except the groovy dependency)
  2. copy script contents to a Service

Possible extension:

  1. use the grails rest plugin or grails rest-client-builder plugin instead of http-builder

Upvotes: 1

Related Questions