RESTEasy Tutorial Part-1: Basics
Here I am going to show you how to develop a Simple RESTful Web Services application using RESTEasy and JBossAS7.1.1.FINAL.
Step#1: Configure RESTEasy dependencies using Maven.
<project xmlns='http:maven.apache.orgPOM4.0.0' xmlns:xsi='http:www.w3.org2001XMLSchema-instance' xsi:schemaLocation='http:maven.apache.orgPOM4.0.0 http:maven.apache.orgmaven-v4_0_0.xsd'> <modelVersion>4.0.0<modelVersion> <groupId>com.sivalabs<groupId> <artifactId>resteasy-demo<artifactId> <version>0.1<version> <packaging>war<packaging> <name>resteasy-demo Maven Webapp<name> <build> <finalName>resteasy-demo<finalName> <build> <dependencies> <dependency> <groupId>junit<groupId> <artifactId>junit<artifactId> <version>4.8.2<version> <scope>test<scope> <dependency> <dependency> <groupId>org.jboss.resteasy<groupId> <artifactId>resteasy-jaxrs<artifactId> <version>2.3.2.FINAL<version> <scope>provided<scope> <dependency> <dependency> <groupId>org.jboss.resteasy<groupId> <artifactId>resteasy-jaxb-provider<artifactId> <version>2.3.2.FINAL<version> <scope>provided<scope> <dependency> <dependency> <groupId>org.jboss.resteasy<groupId> <artifactId>jaxrs-api<artifactId> <version>2.3.0.GA<version> <scope>provided<scope> <dependency> <dependency> <groupId>org.apache.httpcomponents<groupId> <artifactId>httpclient<artifactId> <version>4.1.2<version> <scope>provided<scope> <dependency> <dependencies> <project>
Step#2: Configure RESTEasy in web.xml
<web-app xmlns:xsi='http:www.w3.org2001XMLSchema-instance' xmlns='http:java.sun.comxmlnsjavaee' xmlns:web='http:java.sun.comxmlnsjavaeeweb-app_2_5.xsd' xsi:schemaLocation='http:java.sun.comxmlnsjavaee http:java.sun.comxmlnsjavaeeweb-app_3_0.xsd' id='WebApp_ID' version='3.0'> <listener> <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap<listener-class> <listener> <servlet> <servlet-name>Resteasy<servlet-name> <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher<servlet-class> <servlet> <servlet-mapping> <servlet-name>Resteasy<servlet-name> <url-pattern>rest*<url-pattern> <servlet-mapping> <context-param> <param-name>resteasy.servlet.mapping.prefix<param-name> <param-value>rest<param-value> <context-param> <context-param> <param-name>resteasy.scan<param-name> <param-value>true<param-value> <context-param> <web-app>
Step#3: Create User domain class, MockUserTable class to store User objects in-memory for testing purpose and UserResource class to expose CRUD operations on User as RESTful webservices.
package com.sivalabs.resteasydemo; import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class User { private Integer id; private String name; private String email; private Date dob; setters and getters } package com.sivalabs.resteasydemo; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.sivalabs.resteasydemo.User; public class MockUserTable { private static Map<Integer, User> USER_MAP = new HashMap<Integer, User>(); static { USER_MAP.put(1, new User(1,'admin','admin@gmail.com',new Date())); USER_MAP.put(2, new User(2,'test','test@gmail.com',new Date())); } public static void save(User user){ USER_MAP.put(user.getId(), user); } public static User getById(Integer id){ return USER_MAP.get(id); } public static List<User> getAll(){ List<User> users = new ArrayList<User>(USER_MAP.values()); return users; } public static void delete(Integer id){ USER_MAP.remove(id); } } package com.sivalabs.resteasydemo; import java.util.List; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.sivalabs.resteasydemo.MockUserTable; @Path('users') @Produces(MediaType.APPLICATION_XML) public class UserResource { @Path('') @GET public Response getUsersXML() { List<User> users = MockUserTable.getAll(); GenericEntity<List<User>> ge = new GenericEntity<List<User>>(users){}; return Response.ok(ge).build(); } @Path('{id}') @GET public Response getUserXMLById(@PathParam('id') Integer id) { return Response.ok(MockUserTable.getById(id)).build(); } @Path('') @POST public Response saveUser(User user) { MockUserTable.save(user); return Response.ok('<status>success<status>').build(); } @Path('{id}') @DELETE public Response deleteUser(@PathParam('id') Integer id) { MockUserTable.delete(id); return Response.ok('<status>success<status>').build(); } }
Step#6: JUnit TestCase to test the REST Webservice.
package com.sivalabs.resteasydemo; import java.util.List; import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.util.GenericType; import org.junit.Assert; import org.junit.Test; import com.sivalabs.resteasydemo.User; public class UserResourceTest { static final String ROOT_URL = 'http:localhost:8080resteasy-demorest'; @Test public void testGetUsers() throws Exception { ClientRequest request = new ClientRequest(ROOT_URL+'users'); ClientResponse<List<User>> response = request.get(new GenericType<List<User>>(){}); List<User> users = response.getEntity(); Assert.assertNotNull(users); } @Test public void testGetUserById() throws Exception { ClientRequest request = new ClientRequest(ROOT_URL+'users1'); ClientResponse<User> response = request.get(User.class); User user = response.getEntity(); Assert.assertNotNull(user); } @Test public void testSaveUser() throws Exception { User user = new User(); user.setId(3); user.setName('User3'); user.setEmail('user3@gmail.com'); ClientRequest request = new ClientRequest(ROOT_URL+'users'); request.body('applicationxml', user); ClientResponse<String> response = request.post(String.class); String statusXML = response.getEntity(); Assert.assertNotNull(statusXML); } @Test public void testDeleteUser() throws Exception { ClientRequest request = new ClientRequest(ROOT_URL+'users2'); ClientResponse<String> response = request.delete(String.class); String statusXML = response.getEntity(); Assert.assertNotNull(statusXML); } }
Step#7: To test the REST service we can use the REST Client Tool.
You can download REST Client Tool at http://code.google.com/a/eclipselabs.org/p/restclient-tool/
Important Things to Keep in mind:
1. org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap Listener should be registered before any other listener.
2. You should configure resteasy.servlet.mapping.prefix <context-param> if the HttpServletDispatcher servlet url-pattern is anything other than /*
Continue to the second part of this tutorial.
Reference: RESTEasy Tutorial Part-1: Basics from our JCG partner Siva Reddy at the My Experiments on Technology blog.
Guess you need to at this to the pom.xml to make it work:
”
jboss
http://repository.jboss.org/nexus/content/groups/public-jboss/
“
The code has hundreds of errors. when executed. can you please post the code which actually works so that I can utilise the resteasy in my own applications. org.jboss.resteasy.plugins.providers.jaxb.JAXBUnmarshalException: Unable to find JAXBContext for media type: text/html;charset=”iso-8859-1″ at org.jboss.resteasy.plugins.providers.jaxb.CollectionProvider.readFrom(CollectionProvider.java:89) at org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl.proceed(MessageBodyReaderContextImpl.java:105) at org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor.read(GZIPDecodingInterceptor.java:61) at org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl.proceed(MessageBodyReaderContextImpl.java:108) at org.jboss.resteasy.client.core.BaseClientResponse.readFrom(BaseClientResponse.java:398) at org.jboss.resteasy.client.core.BaseClientResponse.getEntity(BaseClientResponse.java:346) at org.jboss.resteasy.client.core.BaseClientResponse.getEntity(BaseClientResponse.java:307) at com.sivalabs.resteasydemo.UserResourceTest.testGetUsers(UserResourceTest.java:28) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at… Read more »
Could you please update your tutorials for resteasy-jaxrs for version 3.0.16 (i.e for 3.0.x) ? I think 3.x version has made lots of changes in their API’s, your updated tutorial will help all your followers to understand better. Please do the needful.