Monday, June 29, 2015

Access Webserice - REST

once web service up and running we need to test that app. Alos when we are given end point of REST web app we need to verify.
We can just type the URI and get the details or response given from REST web service.
IF we get the URI for GET request for the example app We built,

http://localhost:8080/Rest/rest/employeeservices/getemployeedetail?employeeId=1

accessing through browser will give us the output

<employee>
<dateOfJoining>01-02-2001</dateOfJoining>
<department>Sales</department>
<email>test@example.com</email>
<employeeId>675436</employeeId>
<firstName>John</firstName>
<lastName>Smith</lastName>
</employee>


but here we don't have much options.
here we get the output in xml format. But if you can remember our service implementation it produces both "xml" and "json"

=======================================================================
@Path("/")
@WebService(name="employeeService" , targetNamespace="http://localhost/cxf-rest/example")
public interface CxfRestService {

@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/getemployeedetail")
public Response getEmployeeDetails(
@QueryParam("employeeId") String employeeId);
}
=======================================================================

So if we need to get the output in the json format then we need to set the few setting "Accept=application/xml"

to help to achieve all these thing we need to use http client.There are various res client applications in the web and here i will be using "Advance Rest Client " plugin in the chrome.
In Rest Client you set the values for Header , type of request and etc.





You can see all the details here.
Request header, Response Header, REST URI, type of the call, and the output - here in XML

So our service produces, both xml and json
let's change output for json.

how to do that ?
Then set the "Accept" in the header "application/json"  for "json".



you can see the out in json format

====================================================================
{
firstName"John"
lastName"Smith"
employeeId"675436"
email"test@example.com"
dateOfJoining"01-02-2001"
department"Sales"
}
====================================================================


Access Webserice - REST1

once web service up and running we need to test that app. Alos when we are given end point of REST web app we need to verify.
We can just type the URI and get the details or response given from REST web service.
IF we get the URI for GET request for the example app We built,

http://localhost:8080/Rest/rest/employeeservices/getemployeedetail?employeeId=1

accessing through browser will give us the output

<employee>
<dateOfJoining>01-02-2001</dateOfJoining>
<department>Sales</department>
<email>test@example.com</email>
<employeeId>675436</employeeId>
<firstName>John</firstName>
<lastName>Smith</lastName>
</employee>


but here we don't have much options.
here we get the output in xml format. But if you can remember our service implementation it produces both "xml" and "json"

Access Webserice - REST

once web service up and running we need to test that app. Alos when we are given end point of REST web app we need to verify.
We can just type the URI and get the details or response given from REST web service.
IF we get the URI for GET request for the example app We built,

http://localhost:8080/Rest/rest/employeeservices/getemployeedetail?employeeId=1

accessing through browser will give us the output

<employee>
<dateOfJoining>01-02-2001</dateOfJoining>
<department>Sales</department>
<email>test@example.com</email>
<employeeId>675436</employeeId>
<firstName>John</firstName>
<lastName>Smith</lastName>
</employee>


but here we don't have much options.
here we get the output in xml format. But if you can remember our service implementation it produces both "xml" and "json"

Thursday, June 25, 2015

Creating WebService

Let's create a web service.
We will use maven as build tool and it will makes our life easy.
I will be using STS , Spring Tool Suite.

First we create a maven  web project using STS.
It will have below structure.
Web Project structure



you can build war file using maven tool.
Go to folder where "pom.xml" file exists. and open a command window
execute the maven command

===============
mvn clean package
==============

above command will build the war file.
eg: Here my folder path is "C:\eclipseWorkSpace\2015-01-19_SpringSecurity\Rest>"  where "pom.xml" file reside and remember this the basic web project create with maven using STS. you can create a web project using maven commands directly also. So when i execute the command "mvn clean package " in the command line I have to change the directory to the above mention folder where "pom.xml" resides.
you will see the war file will be created inside target directory. "C:\eclipseWorkSpace\2015-01-19_SpringSecurity\Rest\target"

Web project structure after building war file - Rest.war created

Now get the war file and deploy in the tomcat.
to deploy copy "Rest.war" and paste it inside "webapps" folder inside tomcat.

To refresh your knowledge in tomcat, we can get the tomcat from site and unzip and go to "bin" folder
Here in my case it is "C:\Softwares\Apache\Apache Tomcat\Apache Tomcat 8.0.3\apache-tomcat-8.0.3\bin" and open commad window. set the path to bin directory. execute the command "catalina.bat run"

===================================
C:\Softwares\Apache\Apache Tomcat\Apache Tomcat 8.0.3\apache-tomcat-8.0.3\bin>catalina.bat run
===================================

you will see the starting of the tomcat and trace will shown in the same command window.
If you need you can also run "startup " also, but it will have a seperate window open and run tomcat.

Now you application is deployed in tomcat and to test open browser and type "http://localhost:8080/Rest/" and you will see the default message or default page created with the app showing "Hello World!" in the browser.

Steps we did so far
========
1. create a maven web project using STS
2. build the project using maven - command line "mvn clean package"
3. deploy the web project "war file" in the  tomcat and view in the browser.

Above are the simple steps to create a default web project , pakage war file , deploy and test whether create project really works.

Below are the inside of the files created in the web project. Initially we do not have lots of files only basic files and folder structure will be as shown above and i won't try to explain it again.

Web.xml
======================================================================
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>
======================================================================

index.jsp
======================================================================
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
======================================================================

pom.properties
======================================================================
#Generated by Maven
#Fri Jun 26 10:41:37 IST 2015
version=0.0.1-SNAPSHOT
groupId=com.webservice.rest
artifactId=Rest

======================================================================

pom.xml
======================================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.webservice.rest</groupId>
  <artifactId>Rest</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Rest Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>Rest</finalName>
  </build>
</project>
======================================================================

Now let's go to create the web service application.
Here we use Apache CXF , spring , Jaxon, JAXB

First I will add all coding 

REST Web Service
---------------------
All dependencies

Pom.xml
======================================================================
<modelVersion>4.0.0</modelVersion>
<groupId>com.webservice.rest</groupId>
<artifactId>Rest</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT&lt;/version>
<name>Rest Maven Webapp</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope&gt;
</dependency>

<!-- Spring Dependencies -->
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-core&lt;/artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-context</artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-web&lt;/artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-beans</artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>

<!-- XML dependency -->
<dependency>
<groupId>javax.xml.bind&lt;/groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>

<!-- Apache CXF Dependencies -->
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId&gt;
<version>2.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>2.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>2.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId&gt;
<version>2.7.13</version>
</dependency>
<!-- Jackson The JSON Producer dependency -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
</dependencies>
<build>
<finalName>Rest</finalName>
</build>
</project>

======================================================================

web.xml
======================================================================
<?xml version="1.0" encoding="UTF-8"?>
id="WebApp_ID" version="3.0">


<display-name>Archetype Created Web Application</display-name&gt;

<welcome-file-list>
<welcome-file>index.jsp&lt;/welcome-file>
</welcome-file-list>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans.xml</param-value>
</context-param>

<servlet>
<servlet-name>CXFServlet</servlet-name&gt;
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class&gt;
</servlet>

<servlet-mapping>
<servlet-name>CXFServlet</servlet-name&gt;
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

</web-app>

======================================================================

Employee.java    -->model class
======================================================================
package com.rest.cxfrestservice.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
public class Employee {
private String firstName;
private String lastName;
private String employeeId;
private String email;
private String dateOfJoining;
private String department;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmployeeId() {
return employeeId;
}

public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}

public String getEmail() {
return email;
}

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

public String getDateOfJoining() {
return dateOfJoining;
}

public void setDateOfJoining(String dateOfJoining) {
this.dateOfJoining = dateOfJoining;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

}

======================================================================

EmployeeDao .java --> dao class
======================================================================
package com.rest.cxfrestservice.dao;

import com.rest.cxfrestservice.model.Employee;

public class EmployeeDao {
public Employee getEmployeeDetails(String employeeId) {
Employee emp = new Employee();
emp.setDateOfJoining("01-02-2001");
emp.setDepartment("Sales");
emp.setEmail("test@example.com");
emp.setEmployeeId("675436");
emp.setFirstName("John");
emp.setLastName("Smith");
return emp;
}
}

======================================================================

CxfRestService .java  -->  Interface for Employee Service.
======================================================================
package com.rest.cxfrestservice.service;

import javax.jws.WebService;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * Interface for Employee Service.
 * 
 * @author APRASAD
 * 
 */

@Path("/")
@WebService(name="employeeService" , targetNamespace="http://localhost/cxf-rest/example")
public interface CxfRestService {

@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/getemployeedetail")
public Response getEmployeeDetails(
@QueryParam("employeeId") String employeeId);
}

======================================================================

CxfRestServiceImpl .java --> implementation of for Employee Service.
======================================================================
package com.rest.cxfrestservice.service;

import javax.ws.rs.core.Response;

import org.springframework.beans.factory.annotation.Autowired;

import com.rest.cxfrestservice.dao.EmployeeDao;

public class CxfRestServiceImpl implements CxfRestService {

@Autowired
private EmployeeDao employeeDao;

public Response getEmployeeDetails(String employeeId) {
if (employeeId == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
return Response.ok(employeeDao.getEmployeeDetails(employeeId)).build();
}
}

======================================================================

bean.xml
======================================================================

<import resource="classpath:META-INF/cxf/cxf.xml" />
<context:component-scan base-package="com.rest.*" />

<jaxrs:server id="employeeService" address="/employeeservices"&gt;
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
<jaxrs:serviceBeans>
<ref bean="cxfServiceImpl" />
</jaxrs:serviceBeans>
<jaxrs:extensionMappings&gt;
<entry key="xml" value="application/xml" />
<entry key="json" value="application/json" />
</jaxrs:extensionMappings&gt;
</jaxrs:server>

<bean id="cxfServiceImpl" class="com.rest.cxfrestservice.service.CxfRestServiceImpl" />
<bean id="employeeDao" class="com.rest.cxfrestservice.dao.EmployeeDao" />
</beans>
======================================================================


access above depolyed jar with


you will get out as

======================================================================
<employee>
<dateOfJoining>01-02-2001</dateOfJoining>
<department>Sales</department>
<employeeId>675436</employeeId>
<firstName>John</firstName>
<lastName>Smith</lastName>
</employee>
======================================================================



======================================================================

<grammars/>
<resource path="/">
<resource path="getemployeedetail">
<method name="GET">
<request>
<param name="employeeId" style="query" type="xs:string"/>
</request>
<response>
<representation mediaType="application/xml"/&gt;
<representation mediaType="application/json"/&gt;
</response>
</method>
</resource>
</resource>
</resources>
</application>
======================================================================