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, ...).
Here we see a bean that uses the Bean-Managed Concurrency option as well as the @Startup annotation which causes the bean to be instantiated by the container when the application starts. Singleton beans with @ConcurrencyManagement(BEAN) are responsible for their own thread-safety. The bean shown is a simple properties "registry" and provides a place where options could be set and retrieved by all beans in the application.
package org.superbiz.rest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@Path("/greeting")
public class GreetingService {
@GET
public String message() {
return "Hi REST!";
}
@POST
public String lowerCase(final String message) {
return "Hi REST!".toLowerCase();
}
}
Testing
Test for the JAXRS service
The test uses the OpenEJB ApplicationComposer to make it trivial.
The idea is first to activate the jaxrs services. This is done using @EnableServices annotation.
Then we create on the fly the application simply returning an object representing the web.xml. Here we simply use it to define the context root but you can use it to define your REST Application too. And to complete the application definition we add @Classes annotation to define the set of classes to use in this app.
Finally to test it we use cxf client API to call the REST service in get() and post() methods.
package org.superbiz.rest;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.openejb.jee.SingletonBean;
import org.apache.openejb.junit.ApplicationComposer;
import org.apache.openejb.junit.EnableServices;
import org.apache.openejb.junit.Module;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
@EnableServices(value = "jaxrs")
@RunWith(ApplicationComposer.class)
public class GreetingServiceTest {
@Module
public SingletonBean app() {
return (SingletonBean) new SingletonBean(GreetingService.class).localBean();
}
@Test
public void get() throws IOException {
final String message = WebClient.create("http://localhost:4204").path("/GreetingServiceTest/greeting/").get(String.class);
assertEquals("Hi REST!", message);
}
@Test
public void post() throws IOException {
final String message = WebClient.create("http://localhost:4204").path("/GreetingServiceTest/greeting/").post("Hi REST!", String.class);
assertEquals("hi rest!", message);
}
}
Running
Running the example is fairly simple. In the "simple-rest" directory run:
$ mvn clean install
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec
Results :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
APIs Used
- javax.ws.rs.GET
- javax.ws.rs.POST
- javax.ws.rs.Path
No comments:
Post a Comment