Resourcegroovy

The following is a resource written in Groovy using Jersey and the 311 API:

@UriTemplate("/test")
@ProduceMime(["text/html"])
public class MyResource {

    @HttpContext UriInfo uriInfo;
    
    @HttpMethod
    def getString() {
        def writer = new StringWriter()         
        def html = new MarkupBuilder(writer)
        html.html {
            head {
                title("Groovy resource with 311 and Jersey")
            }
            body {
                h1("URI: " + uriInfo.getURI())
            }
        }
        return writer.toString()
    }

    @UriTemplate("subresource")
    @HttpMethod
    def getSubResourceString() {
        def writer = new StringWriter()         
        def html = new MarkupBuilder(writer)
        html.html {
            head {
                title("Sub-resource")
            }
            body {
                h1("URI of sub-resource: " + uriInfo.getURI())
            }
        }
        return writer.toString()
    }
}

Groovy 1-1-beta-1 supports Java annotations on classes, fields and methods, but not yet on method parameters (I could not get it to work so that the field uriInfo is an annotated method parameter instead). The above example combines 311 annotated methods with the Groovy markup builder to spit out HTML.

I wrote another Groovy class to deploy MyResource using the Light Weight HTTP server:

 public class Main {
    static void main(String[] args) {
        def handler =  ContainerFactory.createContainer(

            HttpHandler.class, 
            MyResource.class);
        def server = HttpServer.create(

            new InetSocketAddress(9998), 0);
        server.createContext("/service", handler);
        server.setExecutor(null);
        server.start();
        System.in.read();
    }
}

So just like with Scala it is possible to use Jersey with Groovy on the Java Virtual Machine.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

sandoz

Search

Archives
« August 2015
SunMonTueWedThuFriSat
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
     
Today