@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
REST simples com CDI
Definir um serviço REST é bastante fácil, basta adicionar a anotação @Path a uma
classe define então nos métodos o método HTTP a ser usado (@GET, @POST,…).
Serviço REST: @Path, @Produces, @Consumes
Aqui nós temos um REST simples, anotamos a classe com @Path("/greeting") para indicar a rota correspondente a classe GreetingService. Definimos message() como @GET e lowerCase() como @POST para esta rota /greeting e fazemos a injeçao da classe Greeting usando a anotação @Inject. Pronto, temos um serviço! Simples não?
Atual linhas:
são opcionais, pois é a configuração padrão. E essas linhas podem também seja configurado pelo método se você precisar ser mais preciso.
@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;
}
}
}
Teste para o serviço JAXRS
Usamos o Arquillian com o adaptador TomEE embedded, assim o serviço REST roda em um TomEE real.
O método @Deployment cria a aplicação web a ser implantada com as classes deste exemplo. O beans.xml com bean-discovery-mode="all" torna Greeting um bean CDI, que pode ser injetado em GreetingService. testable = false executa os métodos de teste como cliente da aplicação implantada, e @ArquillianResource injeta a URL base dela.
Finalmente para testar nós usamos o client API do cfx para chamar o serviço REST nos métodos get() e post().
O contêiner é configurado em src/test/resources/arquillian.xml: httpPort com valor -1 inicia o TomEE em uma porta aleatória.
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);
}
}
Executando
A execução do exemplo é bastante simples. No diretório rest-cdi, execute:
$ mvn clean install
O que deve criar uma saída como a seguir.
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