Preloader image

Defining a REST service is pretty easy, simply ad @Path annotation to a class then define on methods the HTTP method to use (@GET, @POST, …).

The REST service: @Path, @Produces, @Consumes

Here we have a simple REST, we annotate the class with @Path("/greeting") to indicate the route corresponding to the GreetingService class. We define message() as @GET and lowerCase() as @POST for this /greeting route and inject the` Greeting` class using the annotation @Inject. There, we have a service! Simple isn’t it?

Actually lines:

@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })

are optional since it is the default configuration. And these lines can be configured by method too if you need to be more precise.

@Path("/greeting")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class GreetingService {

    @Inject
    Greeting greeting;

    @GET
    public Greet message() {
        return new Greet("Hi REST!");
    }

    @POST
    public Greet lowerCase(final Request message) {
        return new Greet(greeting.doSomething(message.getValue()));
    }

    @XmlRootElement // for xml only, useless for json (johnzon is the default)
    public static class Greet {
        private String message;

        public Greet(final String message) {
            this.message = message;
        }

        public Greet() {
            this(null);
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(final String message) {
            this.message = message;
        }
    }
}

Testing

Test for the JAXRS service

The test uses Arquillian with the TomEE embedded adapter, so the REST service runs in a real TomEE.

The @Deployment method creates on the fly the web application to deploy with the classes of this example. The beans.xml with bean-discovery-mode="all" makes Greeting a CDI bean, so it can be injected in GreetingService. testable = false runs the test methods as a client of the deployed application, and @ArquillianResource injects its base URL.

Finally to test it we use cxf client API to call the REST service in get() and post() methods.

The container is configured in src/test/resources/arquillian.xml: httpPort set to -1 starts TomEE on a random port.

package org.superbiz.rest;

import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.johnzon.jaxrs.JohnzonProvider;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;

import jakarta.ws.rs.core.MediaType;
import java.io.IOException;
import java.net.URL;

import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;

@RunWith(Arquillian.class)
public class GreetingServiceTest {

    @ArquillianResource
    private URL base;

    @Deployment(testable = false)
    public static WebArchive app() {
        return ShrinkWrap.create(WebArchive.class)
                .addClasses(GreetingService.class, Greeting.class, Request.class, Response.class)
                // This enables the CDI magic
                .addAsWebInfResource(new StringAsset("<beans bean-discovery-mode=\"all\"/>"), "beans.xml");
    }

    @Test
    public void getXml() throws IOException {
        final String message = WebClient.create(base.toExternalForm()).path("greeting/")
                .accept(MediaType.APPLICATION_XML_TYPE)
                .get(GreetingService.Greet.class).getMessage();
        assertEquals("Hi REST!", message);
    }

    @Test
    public void postXml() throws IOException {
        final String message = WebClient.create(base.toExternalForm()).path("greeting/")
                .accept(MediaType.APPLICATION_XML_TYPE)
                .type(MediaType.APPLICATION_XML_TYPE)
                .post(new Request("Hi REST!"), GreetingService.Greet.class).getMessage();
        assertEquals("hi rest!", message);
    }

    @Test
    public void getJson() throws IOException {
        final String message = WebClient.create(base.toExternalForm(), asList(new JohnzonProvider<GreetingService.Greet>())).path("greeting/")
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .get(GreetingService.Greet.class).getMessage();
        assertEquals("Hi REST!", message);
    }

    @Test
    public void postJson() throws IOException {
        final String message = WebClient.create(base.toExternalForm(), asList(new JohnzonProvider<GreetingService.Greet>())).path("greeting/")
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .type(MediaType.APPLICATION_JSON_TYPE)
                .post(new Request("Hi REST!"), GreetingService.Greet.class).getMessage();
        assertEquals("hi rest!", message);
    }
}

#Running

Running the example is fairly simple. In the ``rest-cdi'' directory run:

$ mvn clean install

Which should create output like the following.

Running org.superbiz.rest.GreetingServiceTest
INFO: Starting TomEE from: /tmp/arquillian-apache-tomee-22867
INFO: Starting Servlet engine: [Apache Tomcat/11.0.25]
INFO: Starting ProtocolHandler ["http-nio-52890"]
INFO: Configuring enterprise application: /path/to/tomee/examples/rest-cdi/target/tomee-embedded/0/022cf261-98dd-43e1-a5c4-921ec4c12c14
INFO: Enterprise application "/path/to/tomee/examples/rest-cdi/target/tomee-embedded/0/022cf261-98dd-43e1-a5c4-921ec4c12c14" loaded.
INFO: Deployed Application(path=/path/to/tomee/examples/rest-cdi/target/tomee-embedded/0/022cf261-98dd-43e1-a5c4-921ec4c12c14)
INFO: REST Application: http://localhost:52890/022cf261-98dd-43e1-a5c4-921ec4c12c14/         -> org.apache.openejb.server.rest.InternalApplication
INFO:      Service URI: http://localhost:52890/022cf261-98dd-43e1-a5c4-921ec4c12c14/greeting -> Pojo org.superbiz.rest.GreetingService
INFO:               GET http://localhost:52890/022cf261-98dd-43e1-a5c4-921ec4c12c14/greeting ->      Greet message()
INFO:              POST http://localhost:52890/022cf261-98dd-43e1-a5c4-921ec4c12c14/greeting ->      Greet lowerCase(Request)
INFO: Undeploying app: /path/to/tomee/examples/rest-cdi/target/tomee-embedded/0/022cf261-98dd-43e1-a5c4-921ec4c12c14
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.178 s -- in org.superbiz.rest.GreetingServiceTest
Results:

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0