Saturday, December 10, 2011

Gretty - example - web-service



import org.mbte.gretty.httpserver.* 

@GrabResolver(name='gretty', 
  root='http://groovypp.artifactoryonline.com/groovypp/libs-releases-local')
@Grab('org.mbte.groovypp:gretty:0.4.279') 

GrettyServer server = [] 
server.groovy = [ 
    localAddress: new InetSocketAddress("localhost", 8080), 
    defaultHandler: { 
        response.redirect "/" 
    }, 
    "/:name": {
        get {
            response.text = "Hello ${request.parameters['name']}"
        } 
    } 
] 
server.start()
What this program does -

I created a server listening on port 8080, then set up a simple root endpoint containing the parameter name. Any request to some other endpoint will be routed back to / via the defaultHandler. The handler basically sends the requesting client an HTTP 301 "moved permanently" code, with the location of /. All requests will receive a response (with the content-type set to text/plain) containing the string "Hello" along with the value of any parameter passed; for instance, /Andy would yield "Hello Andy."

required librabies -

Groovy 1.8
gretty 0.4.279 and its dependent librabies downloaded by Grape


Execute -

groovy server.groovy

Making content type text/html -


"/:name": {
 get {
  response.html = "Hello ${request.parameters['name']}"
 } 
} 
Using a template -
<html> <head>
  <title>Hello!</title>
 </head>
 <body>
  <p>${message}</p>
 </body>
</html>
Using the template in response -

"/:name" {  get {
   response.html = template("index.gpptl", 
     [message: "Hello ${request.parameters['name']}"])
  }
}
Accessing Mongo DB- use Morphia



@GrabResolver(name='morphia', root='http://morphia.googlecode.com/svn/mavenrepo/')
@Grab(group='com.google.code.morphia', artifactId='morphia', module="morphia", 
  version='0.99')

Anyone's guess that this is a pure restful service - So this brings us to the question on when to use a restful service vs a soap based service. A quick read REST vs SOAP service




Also Read
An actor framework for Java concurrency
Instrumentation - Querying the memory usage of a Java object
10 things you didn't know about java performance monitoring
The Clean Coder

No comments: