Mar 21, 2016

RESTful Web Services in Java with Spring and CXF

1. Eclipse Web Project Structure

































2 . Create The Java Code

2. 1 . Create CustomerManagerDao interface

package com.test.rest.dao;

import java.util.List;
import com.test.rest.model.Customer;

public interface CustomerManagerDao {

public Customer fetchCustomerById(String id);

public List fetchAllCustomers();

public void insertCustomer(Customer customer);

public void updateCustomer(Customer customer);

public void deleteCustomer(Customer customer);
}

2.2 . Create CustomerManageDaoImpl class

package com.test.rest.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.test.rest.dao.CustomerManagerDao;
import com.test.rest.model.Customer;

@Component("customerDao")
public class CustomerManageDaoImpl implements CustomerManagerDao {

List customers = new ArrayList();

public Customer fetchCustomerById(String id) {

Customer customerobj = new Customer();

customerobj.setId("1");
customerobj.setName("Muni K");
customerobj.setCity("ED");
customerobj.setBirthDate("01-01-1978");
customerobj.setState("NJ");
customerobj.setEmail("abc@xyz.com");

customers.add(customerobj);

for (Customer customer : customers) {
if (customer.getId().equals(id)) {
return customerobj;
}
}
throw new RuntimeException("Customer Not Found: " + id);
}

public List fetchAllCustomers() {
return customers;
}

public void insertCustomer(Customer customer) {
customers.add(customer);
}

public void updateCustomer(Customer customer){

Customer editCustomer = fetchCustomerById(customer.getId());

editCustomer.setBirthDate(customer.getBirthDate());
editCustomer.setCity(customer.getCity());
editCustomer.setEmail(customer.getEmail());
editCustomer.setName(customer.getName());
editCustomer.setState(customer.getState());
}

public void deleteCustomer(Customer customer){

Customer delCustomer = fetchCustomerById(customer.getId());
customers.remove(delCustomer);

}
}

2.3. Create Customer Model class

package com.test.rest.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {
private String id;
private String name;
private String email;
private String birthDate;
private String city;
private String state;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getBirthDate() {
return birthDate;
}

public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}
}

2.4. Create CustomerRequest class

package com.test.rest.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class CustomerRequest {

private Customer customer;

public Customer getCustomer() {
return customer;
}

public void setCustomer(Customer customer) {
this.customer = customer;
}
}

2.5. Create CustomerResponse class

package com.test.rest.model;

import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class CustomerResponse {
private List customers;
private String errorMessage;
private Boolean success = true;

public List getCustomers() {
return customers;
}

public void setCustomers(List customers) {
this.customers = customers;
}

public Boolean isSuccess() {
return success;
}

public void setSuccess(Boolean success) {
this.success = success;
}

public String getErrorMessage() {
return errorMessage;
}

public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

2.6 . Create CustomerManagerService class

package com.test.rest.services;

import javax.ws.rs.Consumes;
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.MediaType;
import org.apache.cxf.jaxrs.model.wadl.Description;
import org.apache.cxf.jaxrs.model.wadl.DocTarget;

import com.test.rest.model.CustomerRequest;
import com.test.rest.model.CustomerResponse;

@Description(value = "Resource", target = DocTarget.RESOURCE)
@Consumes({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN,
MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN,
MediaType.APPLICATION_XML })
public interface CustomerManagerService {
@POST
@Path("/fetchCustomerById/{id}")
public CustomerResponse fetchCustomerById(@PathParam("id") String id);

@POST
@Path("/fetchAllCustomers/")
public CustomerResponse fetchAllCustomers(CustomerRequest request);

@POST
@Path("/insertCustomer/")
public CustomerResponse insertCustomer(CustomerRequest request);

@POST
@Path("/updateCustomer/")
public CustomerResponse updateCustomer(CustomerRequest request);

@POST
@Path("/deleteCustomer/")
public CustomerResponse deleteCustomer(CustomerRequest request);
}

2.7 Create CustomerManagerServiceImpl class 

package com.test.rest.services.impl;

import java.util.Arrays;

import org.springframework.stereotype.Component;

import com.test.rest.dao.CustomerManagerDao;
import com.test.rest.model.CustomerRequest;
import com.test.rest.model.CustomerResponse;
import com.test.rest.services.CustomerManagerService;

@Component("customerManagerService")
public class CustomerManagerServiceImpl implements CustomerManagerService {
private CustomerManagerDao customerDao;

public CustomerManagerDao getCustomerDao() {
return customerDao;
}

public void setCustomerDao(CustomerManagerDao customerDao) {
this.customerDao = customerDao;
}

public CustomerResponse fetchCustomerById(String id) {
CustomerResponse response = new CustomerResponse();

try {
response.setCustomers(Arrays.asList(getCustomerDao().fetchCustomerById(id)));
} catch (Exception e) {
response.setSuccess(false);
response.setErrorMessage(e.getClass() + ": " + e.getMessage());
}

return response;
}

public CustomerResponse fetchAllCustomers(CustomerRequest request) {
CustomerResponse response = new CustomerResponse();

try {
response.setCustomers(getCustomerDao().fetchAllCustomers());
} catch (Exception e) {
response.setSuccess(false);
response.setErrorMessage(e.getClass() + ": " + e.getMessage());
}

return response;
}

public CustomerResponse insertCustomer(CustomerRequest request) {
CustomerResponse response = new CustomerResponse();

try {
getCustomerDao().insertCustomer(request.getCustomer());
} catch (Exception e) {
response.setSuccess(false);
response.setErrorMessage(e.getClass() + ": " + e.getMessage());
}

return response;
}

public CustomerResponse updateCustomer(CustomerRequest request) {
CustomerResponse response = new CustomerResponse();

try {
getCustomerDao().updateCustomer(request.getCustomer());
} catch (Exception e) {
response.setSuccess(false);
response.setErrorMessage(e.getClass() + ": " + e.getMessage());
}

return response;
}

public CustomerResponse deleteCustomer(CustomerRequest request) {
CustomerResponse response = new CustomerResponse();

try {
getCustomerDao().deleteCustomer(request.getCustomer());
} catch (Exception e) {
response.setSuccess(false);
response.setErrorMessage(e.getClass() + ": " + e.getMessage());
}

return response;
}

}

3. /WEB-INF/application-context.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:context="http://www.springframework.org/schema/context"
xmlns:cxf="http://cxf.apache.org/core" 
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/core http://cxf.apache.org/schemas/core.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">

<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

<context:annotation-config />
<context:component-scan base-package="com.test.rest" />

<bean id="customerDao" class="com.test.rest.dao.impl.CustomerManageDaoImpl"> </bean>

<bean id="customerManagerService" class="com.test.rest.services.impl.CustomerManagerServiceImpl">
<property name="customerDao" ref="customerDao" />
</bean>

<bean id="jacksonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"></bean>

<jaxrs:server id="customerManagerREST" address="/rest/CustomerManager">
<jaxrs:serviceBeans>
<ref bean="customerManagerService" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean='jacksonProvider' />
</jaxrs:providers>
</jaxrs:server>

</beans>

4. /WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
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_3_0.xsd">
<display-name>SpringRestDemo</display-name>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</context-param>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
</web-app>

5 . Test fetchCustomerById service (SoapUI Tool)










6. Test insertCustomer service











Thank You !!    :)

No comments: