CXF RESTFUL Service - Example jax-rs

CXF frame work  supports restful web services.
It is provided in the following ways:
  1. JAX_RS
  2. JAX_WS ProviderDispatch
  3. HtppBinding
Below is the example of RESTFUL service which gives an xml response.The data is pulled form  the database.I have also integrated  spring-jdbc with cxf.

check the response after running the application at-http://localhost:8086/cxf-jaxrs-poc/myservice/users
Port number can change based on availability.

Lets start with the configurations-cxf.xml:

 <?xml version="1.0" encoding="UTF-8"?>  
 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
   xmlns:jaxrs="http://cxf.apache.org/jaxrs"  
   xsi:schemaLocation="  
 http://www.springframework.org/schema/beans  
 http://www.springframework.org/schema/beans/spring-beans.xsd  
 http://cxf.apache.org/jaxrs  
 http://cxf.apache.org/schemas/jaxrs.xsd"  
   default-lazy-init="false">  
   <jaxrs:server id="myService" address="/">  
     <jaxrs:serviceBeans>  
       <ref bean="serviceImpl" />  
     </jaxrs:serviceBeans>  
     <jaxrs:extensionMappings>  
       <entry key="xml" value="application/xml" />  
     </jaxrs:extensionMappings>  
   </jaxrs:server>  
   <bean id="serviceImpl" class="service.ServiceImpl" />  
   <bean id="MySqlDatasource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">  
     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>  
     <property name="url" value="jdbc:mysql://localhost:3306/emp"/>  
     <property name="username" value="root"/>  
     <property name="password" value="prdc123"/>  
   </bean>  
   <bean id="userDAO" class="dao.UserDAOImpl">  
           <property name="dataSource" ref="MySqlDatasource"/>  
      </bean>  
 </beans>  

web.xml configuration- add cxf servlet-and spring context listners
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
   <display-name>cxf-jaxrs-poc</display-name>  
   <description>cxf-jaxrs-poc</description>  
 <!--   <context-param> -->  
 <!--     <param-name>webAppRootKey</param-name> -->  
 <!--     <param-value>cxf.rest.example.root</param-value> -->  
 <!--   </context-param> -->  
   <context-param>  
     <param-name>contextConfigLocation</param-name>  
     <param-value>/WEB-INF/cxf.xml</param-value>  
   </context-param>  
   <listener>  
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
   </listener>  
   <servlet>  
     <servlet-name>CXFServlet</servlet-name>  
     <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  
     <load-on-startup>1</load-on-startup>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>CXFServlet</servlet-name>  
     <url-pattern>/*</url-pattern>  
   </servlet-mapping>  
 </web-app> 

Service Defn Interface
 package service;  
 import javax.ws.rs.core.Response;  
 import pojo.User;  
 import pojo.UserCollection;  
 public interface ServiceDefn {  
   public abstract UserCollection getUsers();  
   public abstract User getUser(Integer id);  
   public abstract Response getBadRequest();  
 }  

service impl class-- define restful service path,prepares the data for response
 package service;  
 import java.util.ArrayList;  
 import java.util.HashMap;  
 import java.util.Iterator;  
 import java.util.List;  
 import java.util.Map;  
 import javax.ws.rs.DELETE;  
 import javax.ws.rs.GET;  
 import javax.ws.rs.POST;  
 import javax.ws.rs.PUT;  
 import javax.ws.rs.Path;  
 import javax.ws.rs.PathParam;  
 import javax.ws.rs.Produces;  
 import javax.ws.rs.core.Response;  
 import javax.ws.rs.core.Response.Status;  
 import dao.Manager;  
 import pojo.User;  
 import pojo.UserCollection;  
 @Path("/myservice/")  
 @Produces("application/xml")  
 public class ServiceImpl implements ServiceDefn {  
   private static Map<Integer, User> users = new HashMap<Integer, User>();  
   private static Manager m;  
   Integer currentId = 3;  
   static {  
 //    users.put(1, new User(1, "foo","Manager"));  
 //    users.put(2, new User(2, "bar","SE"));  
 //    users.put(3, new User(3, "baz","CTO"));  
        List l=new ArrayList();       
         m=new Manager();  
         l=m.view();  
        Iterator itr=l.iterator();  
        int i=0;  
        while(itr.hasNext()){  
             users.put(i++, (User) itr.next());  
        }  
   }  
   public ServiceImpl() {  
   }  
   @GET  
   @Path("/users")  
   public UserCollection getUsers() {  
        System.out.println(users.values());  
     return new UserCollection(users.values());  
   }  
   @GET  
   @Path("/user/{id}")  
   public User getUser(@PathParam("id") Integer id) {  
     return users.get(id);  
   }  
   @GET  
   @Path("/users/bad")  
   public Response getBadRequest() {  
     return Response.status(Status.BAD_REQUEST).build();  
   }  
   @PUT  
   @Path("/users/")  
   public Response updateUsers(User user) {  
     System.out.println("----invoking updateCustomer, Customer name is: " + user.getName());  
     User c = users.get(user.getId());  
     Response r;  
     if (c != null) {  
          users.put(user.getId(), user);  
       r = Response.ok().build();  
     } else {  
       r = Response.notModified().build();  
     }  
     return r;  
   }  
   @POST  
   @Path("/users/")  
   public Response addUsers(User user) {  
     System.out.println("----invoking addCustomer, Customer name is: " + user.getName());  
     user.setId(++currentId);  
     users.put(user.getId(), user);  
     return Response.ok(user).build();  
   }  
   @DELETE  
   @Path("/user/{id}/")  
   public Response deleteUser(@PathParam("id") String id) {  
     System.out.println("----invoking deleteCustomer, Customer id is: " + id);  
     Integer idNumber = Integer.parseInt(id);  
     User c = users.get(idNumber);  
     Response r;  
     if (c != null) {  
       r = Response.ok().build();  
       users.remove(idNumber);  
     } else {  
       r = Response.notModified().build();  
     }  
     return r;  
   }  
 }  

Users COllection
 package pojo;  
 import java.util.Collection;  
 import javax.xml.bind.annotation.XmlElement;  
 import javax.xml.bind.annotation.XmlElementWrapper;  
 import javax.xml.bind.annotation.XmlRootElement;  
 @XmlRootElement  
 public class UserCollection {  
   private Collection<User> users;  
   public UserCollection() {  
   }  
   public UserCollection(Collection<User> users) {  
     this.users = users;  
   }  
   @XmlElement(name="user")  
   @XmlElementWrapper(name="users")  
   public Collection<User> getUsers() {  
     return users;  
   }  
 }  

User
 package pojo;  
 import javax.xml.bind.annotation.XmlRootElement;  
 @XmlRootElement(name = "user")  
 public class User {  
   private Integer id;  
   private String name;  
   private String designation;  
      public String getDesignation() {  
           return designation;  
      }  
      public void setDesignation(String designation) {  
           this.designation = designation;  
      }  
      public User() {  
   }  
   public User(Integer id, String name,String designation) {  
     this.id = id;  
     this.name = name;  
     this.designation=designation;  
   }  
   public User(String name,String designation) {  
     this.id = id;  
     this.name = name;  
     this.designation=designation;  
   }  
   public Integer getId() {  
     return id;  
   }  
   public void setId(Integer id) {  
     this.id = id;  
   }  
   public void setName(String name) {  
     this.name = name;  
   }  
   public String getName() {  
     return name;  
   }  
   @Override  
      public String toString() {  
           return "User [id=" + id + ", name=" + name + ", designation="  
                     + designation + "]";  
      }  
 }  

Comments

Popular posts from this blog

defining functions clojure

Integrating Struts2 with Spring Security using Custom Login Form