Monday, March 28, 2016

A simple, simple json and rest demo

I created a simple demonstration of a Rest - application, based on the examples from the Java EE Tutorial.

My demo just returns a Json object.

I used IntelliJ, configuring module facets for library dependencies.

I did not use any maven for build or dependency management.

Deployment is done on a local Glassfish instance.

Project configuration IntelliJ

Project settings use the facets EJB, Web and Java EE application. Libraries : ejb 3.2, javax.json.processing-1.0, JAX-RS.

Code

Code consists of 2 classes : one application - Class (that inherits from javax.ws.rs.core.Application), and one implementation class, where the json processing takes place, and with the rest annotations.

Application class

package org.nstern.demos.rest;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/demoRest")
  public class RestDemoApplication extends Application {
}

Implementing class

package org.nstern.demos.rest;

import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

@Path("/demo")
public class RestDemoResource {

    @Context    private UriInfo context;

    public RestDemoResource(){}

    @GET    
    @Path("test")
    @Produces({MediaType.APPLICATION_JSON})
    public String testBean() {
        return "123456789";
    }

    @GET    
    @Path("testJson")
    @Produces({MediaType.APPLICATION_JSON})
    public JsonObject testJson() {

        JsonObject model = Json.createObjectBuilder()
                .add("firstName", "Duke")
                .add("lastName", "Java")
                .build();

        return model;
    }
}

Deployment and calling the Rest methods

Artefact is configured in IntelliJ in the Glassfish config (war exploded). I defined a custom context root to avoid cumbersome URLs.

I call the rest method using Chrome advanced rest client:

The two urls are :
http://localhost:8080/demoRest/demo/test
http://localhost:8080/demoRest/demo/testJson

Summary, remarks

I had to struggle before finding out that if I don't define a custom context root, the application will use a strange root URL  - like "http://localhost:8080/demoBean_war_exploded/etc.*"

I found a useful hint about generating artefacts (*.war file) on this blog. (This is pure handling of IntelliJ).

Not that this application has no web.xml