Wednesday 28 March 2012

JERSY - Developing RESTful Web Service with Eclipse



1.. Required Software –
Eclipse
Tomcat (7.0.25)
 JDK 1.6
Jersy Artifact


2.    Prepare Working Environment
Extract eclipse-jee-win32.zip as D:\demo\ws-cxf-support sw\eclipse
Extract apache-tomcat-x.x.x.zip as D:\demo\ws-cxf-support sw\tomcat
Extract jersy.zip as D:\demo\ws-cxf-support sw\Jersy

TOMCAT_HOME = D:\demo\ws-cxf-support sw\tomcat
JAVA_HOME = D:\demo\ws-cxf-support sw\JDK1.6

3.   Create a workspace  as D:\demo\workspace

Getting started with RESTful Web Service

1 .    Right Click package explorer
           Select new - >Dynamic web project



















2 .  Select modify button which is part of configuration



















3.   In New Opened window
Select Dynamic web module as – 2.5
Java as 1.6
JAX-RS(REST web service)  - 1.1



















4. Click on Save as – 
In new Opened window
Enter  Name - JAX-RS(REST Web Services)
Description   - JAX-RS(REST Web Services)
Click on Ok























5.   
Click on Ok

6. Now Enter the Project Name as -  RestFulWS
7.  Verify all other combination as follows
Target Runtime – Tomcat 7.025
Dynamic web module version – 2.5
Configuration – JAX-RS(Web Services)
Click on Next
8.  Click on Next



















9.   Click on Next following new window opened, Click on the mark area to add library









 












10. Following New window opened



















11.  Click on New
Enter User Library Name as  - JAX-RS
Add system library added to boot class path



















12.  Click on Ok
Select above Created user Library – JAX –RS and Click on Add Jar
Add the following jar for the above created user library
asm-3.1.jar
jersey-servlet-1.11.jar
jersey-server-1.11.jar
jsr311-api-1.1.1.jar



















13.  Select User Library as JAX-RS and Click On Ok
14.  Check User Library
JAX-RS Servlet Class Name as - com.sun.jersey.spi.container.servlet.ServletContainer





















15.  Click on finish, New Project get Created as “RestFulWS”

16.  Verify for the web.xml as following


<servlet>
<description>JAX-RS Tools Generated - Do not modify</description>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS Servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>


17.  Now create new package under src folder – “com.rest.ws”

18.  Create a new class under created package name as  - ExampleWithOutParam.java
Put the annotation for Created class as
@Path (“/exampleWithOutParam”)
Public class ExampleWithOutParam{
}
Define path is used to call the above class

19.  Add the following method as a part of above class
@Path("/getName")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getName(){
return "Executed getName Successfully";
}




How to call  -  
http://localhost:8080/RestFulWS/rest/exampleWithOutParam/getName 




Create a new class name as

@Path("/loginService")  
public class LoginServiceWithAllParam {  


}
Add all following method as part of above class.



@MatrixParam 
 If  want to pass the multiple values with the web service URL then we can use as follows.



       @GET
       @Path("/validateWithMultipleQueryParam")
public String validateWithMultipleQueryParam(@MatrixParam("userName") String    
                   userName,@MatrixParam("password") String password) {  
    System.out.println( " Enter User Name as "+ userName);
    System.out.println( " Enter password "+ password);
     if("SHRIKANT".equalsIgnoreCase(userName)
                             && "PASSWORD".equalsIgnoreCase(password)) {
       return "Matrix Param request executed successfully";
      } else {
        return "Matrix Param request executed un successfully";
      }
}



How to call  -  
http://localhost:8080/ RestFulWS/rest/loginService/validateWithMultipleQueryParam;userName=shrikant;password=password



@QueryParam
 If  want to pass the values with the web service URL as a query param then we can use as follows.



       @GET
       @Path("/validate")
public String validate(@QueryParam("userName") String userName) {  
System.out.println( " Enter User Name as "+ userName);
return "query param request executed successfully";
}



How to call  -  
http://localhost:8080/RestFulWS/rest/loginService/validate?userName=shrikant


@DefaultValue
 If  no value pass with web service url and user need to use default value. then we can use as follows.



       @GET
       @Path("/validateDefault")
public String validateDefault(@DefaultValue("admin")
                                @QueryParam("userName") String userName) {  
System.out.println( " Enter User Name as "+ userName);
return "default value request executed successfully";
}



How to call  -  
http://localhost:8080/RestFulWS/rest/loginService/validateDefault


@HeaderParam
 If  user required header related values for manipulation then we can use as follows.



       @GET
       @Path("/findBrowser")
public String findBrowser(@HeaderParam("User-Agent") String userAgent) {  
System.out.println( " User used browser as "+ userAgent);
return "header param request executed successfully";
}



How to call  -  
http://localhost:8080/RestFulWS/rest/loginService/findBrowser


@CookieParam

 If  user required values from browser  to manipulate  then we can use as follows.



       @GET
       @Path("/findBrowserCookie")
public String findBrowserCookie(@CookieParam("sessionid") String sessionid) {  
System.out.println( " User session id as "+ sessionid);
return "cookie param request executed successfully";
}



How to call  -  
http://localhost:8080/RestFulWS/rest/loginService/findBrowserCookie





@FormParam
 if user need to pass the value in bean object then we can use as  follow.


login.jsp


 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
                      pageEncoding="ISO-8859-1"%>
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"                      
                      "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="POST" action="rest/loginService/validateLogin">
User Name: <input type="text" name="userName">
Password : <input type="text" name="password">
<input type="submit"></form>
</body>
</html> 


LoginForm.java



package com.rest.ws;

import javax.ws.rs.FormParam;


public class LoginForm {


@FormParam("userName")

private String userName;

@FormParam("password")

private String password;

public String getUserName() {

return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}





       @POST
       @Path("/validateLogin")
public String validateLogin(@FormParam("userName") String userName,   
                             @FormParam("password") String password) {  
System.out.println( " Enter User Name as "+ userName);
System.out.println( " Enter password "+ password);
if("SHRIKANT".equalsIgnoreCase(userName) &&  
                               "PASSWORD".equalsIgnoreCase(password)) {
return "form param request executed successfully";
} else {
return "form param request executed un successfully";
}
}



How to call  -  
http://localhost:8080/RestFulWS/login.jsp






If Exception Found -



INFO: Marking servlet JAX-RS Servlet as unavailable
Mar 28, 2012 3:25:10 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet /RestFulWS threw load() exception
java.lang.NoClassDefFoundError:


check WEB-INF/lib
and place all the jar file which is used for use library(see 12.)



















Friday 23 March 2012

Apache Ant - Build a Project in Eclipse with build.xml


Required Software -
Ant 1.8.2
Java 1.6
Tomcate 6.0.26


Extract Ant 1.8.2.zip as C:/Ant/Ant Build Demo/apache-ant-1.8.2

Extract apache-tomcat-6.0.26.zip as C:/apache-tomcat-6.0.26

CATALINA_HOME = C:/apache-tomcat-6.0.26
ANT_HOME =  C:/Ant/Ant Build Demo/apache-ant-1.8.2;
PATH =C:/jdk1.6./bin;C:/Ant/Ant Build Demo/apache-ant-1.8.2/bin;

SET  JVM_ARGS="-Xms1024m -Xmx1024m"
CLASSPATH=C:/Ant/Ant Build Demo/apache-ant-1.8.2/jar/catalina-ant-5.5.23.jar;C:/Ant/Ant Build Demo/apache-ant-1.8.2/jar/commons-net-1.4.1.jar;


1. Following structure for the creating a build.xml
<?xml version="1.0" ?>
<project name="TESTWebApp" default="war" basedir=".">
     --------------------
     --------------------
</project>

2. Assigned variable from property file
<?xml version="1.0" ?>
<project name="TESTWebApp" default="war" basedir=".">
        <property file="build.properties" />
<property name="project-name" value="${project.name}" />
<property name="builder" value="${project.builder}" />
<tstamp prefix="build-info">
<format property="current-date" pattern="dd-MM-yyyy" locale="en" />
<format property="current-time" pattern="hh:mm:ss a z" locale="en" />
</tstamp>
<property name='app.version' value='${app.version}'/>
<property name='app.name' value='${app.name}'/>
<property name='ant.config.xml.home' value='${ant.config.xml.home}'/>
</project>

3. Auto Increment Version for the War/Jar/Ear file.
<?xml version="1.0" ?>
<project name="TESTWebApp" default="war" basedir=".">
 <property file="version.properties" />
<property name='app.build.version' value='${app.build.version}'/>
<property name='app.major' value='${app.major}'/>
<property name='app.minor' value='${app.minor}'/>
<target name="version"  >
<propertyfile  file="version.properties">
  <entry key="app.build.version" type="int" default="0" operation="+" />
</propertyfile>
</target>
</project>

4. Replace a phrase from file with values from property file.
    In  following Exmple :
            "@build-timestamp@" replace with generated current time stamp using ant.
            "@build- version@" replace with auto incremented build version number.
<?xml version="1.0" ?>
<project name="TESTWebApp" default="replace" basedir=".">
         <target name="replace" depends="version">
                <replace file="${web.dir}/index.jsp" token="@build-timestamp@" value="${build-                                             info.current-date}:${build-info.current-time}" />
                <replace file="${web.dir}/index.jsp" token="@build-version@" value="${project.name}-                                                ${app.build.version}.${app.major}.${app.minor}" />
          </target>
</project>

5. Configure the class-path for compiling all the Java file with all the required .jar
    In  following Example :
                  "web.lib.dir" - adding all the available jar in class-path
                  "tomcat.web.lib.dir" - adding all the available jar in class-path
                  "ant.config.xml.home}/jar" - adding all the available jar  in class-path
<?xml version="1.0" ?>
<project name="TESTWebApp" default="war" basedir=".">
       <path id="compile.classpath">
<fileset dir="${web.lib.dir}">
<include name="*.jar" />
</fileset>
<fileset dir="${tomcat.web.lib.dir}">
<include name="*.jar" />
</fileset>
<fileset dir="${ant.config.xml.home}/jar">
<include name="*.jar" />
</fileset>
</path>
</project>

6. Compile all the Java source code from the respective SRC folder.
    In  following Example :
                  "build.classes.dir" - destdir, use as destination folder to store all compile files.
                  "build.src.dir" - srcdir , use as source folder to compile all the java files.
                  "compile.classpath" - classpath , use for all the compilation.
                  "debug=true" - use to set the log level
                  "depends=clean" - clean is a target which is execute before compile (Optional).
                  echo tag basically use for the information message.
<?xml version="1.0" ?>
<project name="TESTWebApp" default="compile" basedir=".">
         <target name="compile" depends="clean">
<mkdir dir="${build.classes.dir}" />
<javac destdir="${build.classes.dir}"
  debug="true"
  srcdir="${build.src.dir}">
<classpath refid="compile.classpath" />
</javac>
<echo>complile all java file and place into respective folder</echo>
</target>
</project>

7. Copy all the file from SRC of specified pattern to DEST.
    In  following Example :
                  "build.classes.dir" - destdir, use as destination folder to store all compile files.
                  "build.src.dir" - srcdir , use as source folder to compile all the java files.
                  "meta.files" -  use for all the for defined pattern.
                 "depends=compile" - compile is a target which is execute before copy.meta.files   
                  (Optional).
<?xml version="1.0" ?>
<project name="TESTWebApp" default=" copy.meta.files" basedir=".">
        <patternset id="meta.files">
<include name="**/*.xml" />
<include name="**/*.properties" />
        </patternset>

<target name="copy.meta.files" depends="compile">
<copy todir="${build.classes.dir}">
<fileset dir="${build.src.dir}">
<patternset refid="meta.files" />
</fileset>
</copy>
</target>
</project>

8. Execute target jar for creating jar file from compiled classes
    In  following Example :
                  "build.classes.dir" -basedir, use as base folder to create a jar file.
                  "dist.dir" - destfile is folder.
                  "dist.dir.jar" - folder under the "dist.dir" , for generating jar files.
                  "project.name" -  use for the generating jar file with major and minor version.
                 "depends=copy.meta.files" - compile is a target which is execute before jar
                   (Optional).
<?xml version="1.0" ?>
<project name="TESTWebApp" default="jar" basedir=".">
        <target name="jar" depends="copy.meta.files">
<jar destfile="${dist.dir}/${dist.dir.jar}/${project.name}-${app.build.version}.${app.major}.${app.minor}.jar"
basedir="${build.classes.dir}" />
<echo>jar generated :: ${project.name}-${app.build.version}.${app.major}.${app.minor}.jar </echo>
</target>
</project>


9. Execute target war , for creating war file from jar file
    In  following Example :
                  "dist.dir" - destfile is folder.
                  "dist.dir.jar" - folder under the "dist.dir.jar" , for generating jar files.
                  "dist.dir.war" - folder under the "dist.dir" , for generating war files.
                  "project.name" -  use for the generating jar file with major and minor version.
                 "depends=jar" - compile is a target which is execute before war
                   (Optional).

<?xml version="1.0" ?>
<project name="TESTWebApp" default="war" basedir=".">

<target name="war" depends="jar">
<war destfile="${dist.dir}/${dist.dir.war}/${project.name}-
                                                         ${app.build.version}.${app.major}.${app.minor}.war"
                              webxml="${web.dir}/WEB-INF/web.xml">
<fileset dir="${web.dir}" >
<exclude name="WEB-INF/web.xml" />
</fileset>
<lib dir="${dist.dir}/${dist.dir.jar}" />
</war>
<echo>war generated :: ${project.name}-${app.build.version}.${app.major}.${app.minor}.war
                </echo>
</target>
</project>



9. Execute target war , for creating war file from compiled classes file
    In  following Example :
                  "build.classes.dir" - folder under all compile clasess placed.
                  "dist.dir" - destfile is folder.
                  "dist.dir.war" - folder under the "dist.dir" , for generating war files.
                  "project.name" -  use for the generating jar file with major and minor version.
                 "depends=compile" - compile is a target which is execute before war
                   (Optional).

<?xml version="1.0" ?>
<project name="TESTWebApp" default="war" basedir=".">
 <target name="war" depends="compile">
<war destfile="${dist.dir}/${dist.dir.war}/${project.name}-
                                                         ${app.build.version}.${app.major}.${app.minor}.war"
                              webxml="${web.dir}/WEB-INF/web.xml">
<fileset dir="${web.dir}" >
<exclude name="WEB-INF/web.xml" />
</fileset>
<classes dir="${build.classes.dir}" />
</war>
<echo>war generated :: ${project.name}-${app.build.version}.${app.major}.${app.minor}.war
                </echo>
</target>
</project>

10. build.proprties

#################################################################################
#######                      Output Folder Tree Stucture                                           ##############
#################################################################################
dist.dir=c:/Ant/Ant Build Demo/dist
dist.dir.war=war
dist.dir.jar=jar


#################################################################################
#######                       Project Specific Details                                                   ##############
#################################################################################
web.dir=C:/apache-tomcat-6.0.26/webapps/TESTWebApp
web.lib.dir=${web.dir}/WEB-INF/lib
build.classes.dir=${web.dir}/WEB-INF/classes
build.src.dir = ${web.dir}/WEB-INF/src
project.name=TESTWebApp
tomcat.dir=C:/apache-tomcat-6.0.26/
tomcat.web.lib.dir=${tomcat.dir}/lib
project.builder = Shrikant
app.version =1.0
app.name = TESTWebApp
ant.config.xml.home=C:/Ant/Ant Build Demo/apache-ant-1.8.2



10. version.proprties

#################################################################################
#######                          Version History                                                                     ##############
#################################################################################
app.build.version=13

Thursday 22 March 2012

Apache CXF - Developing Web Service with Eclipse



Required Software –

Apache CXF
Eclipse
Tomcat (6 and above)
JDK 1.6

Extract eclipse-jee-win32.zip as D:\demo\ws-cxf-support sw\eclipse
Extract apache-tomcat-x.x.x.zip as D:\demo\ws-cxf-support sw\tomcat
Extract apache-cxf-2.x.x.zip as D:\demo\ws-cxf-support sw\Apache CXF

TOMCAT_HOME = D:\demo\ws-cxf-support sw\tomcat
APACHE_CXF_HOME = D:\demo\ws-cxf-support sw\Apache CXF
JAVA_HOME = D:\demo\ws-cxf-support sw\JDK1.6
Create a workspace  as D:\demo\workspace

Configure Apache Tomcat as Follows : -
1. Select Window
2. Select Window->Preferences
3. Select Window->Preferences->Server
4. Select Server->Runtime Environment
5. Click On Add
6. Select the Apache Tomcat (For Respected Version ) and Click On Next
7. Select JDK1.6 as a part of Installed JRE
8. Select Tomcat Home directory See above TOMCAT_HOME


Configure Apache CXF as Follows : -
1. Select Window
2. Select Window->Preferences
3. Select WebService->CXF2.X Preferances
4. Select Add
 Select Apache CXF home See above APACHE_CXF_HOME
 Select Configure Apache CXF and Click on 2nd Tab (Java2WS)
 Select Configure Apache CXF and Click on 3rd Tab (WSDL2Java)
 Select Configure Apache CXF and Click on 4th Tab (JAX-WS)
 Select Configure Apache CXF and Click on 5th Tab (Endpoint Config)
 Select Use CXF Servlet

Getting Started with WebService Project (Publisher): -
1. Create a Web Service
     Right Click in Package Explorer
     Select New  Dynamic Web Project
     Enter Project Name as - WebServiceServer
     Target runtime – Apache Tomcat v
     Dynamic Web module Version – 2.5
     Configuration – CXF Web Services Project v2.5
     Click On Finish
     
2.   Enter Project Name – WebServiceServer


      Select Target RunTime as – Configured Tomcat Server




3.   Add package name com.ws


     Add a new class as a implementation for the service (ShowNameImpl.java)
     Click on finish
     Open a above class
       Add a method as a part of above class.
     
      public String getName(String name){
         return "Test "+name;
    }
4.   Select  Project , Right click on project name
5.  Select webservice
6.   Select Bottom up java bean web service
      Enter Service implementation class com.ws.ShowNameImpl
      Checked Monitor web service
7.   Click on Next     
8.  Checked Use a Service Endpoint Interface
     Select Create an SEI – enter Interface as IShowName
     Checked a method
      Click on Next
9.  Click on Next
10. Click on Next 
11. Click on Start Server
12.  Click on Next
13. Click On Next
14.  Click on Finish
15.  Open WebService Explorer , Click on method Name getName()
16.  Click on add – Enter Name – Shrikant
      Click on “Go” button

Request.xml generated on server log
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://ws.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
    <q0:getName>
      <q0:name>shrikant</q0:name>
    </q0:getName>
  </soapenv:Body>
</soapenv:Envelope>



Response.xml generated on server log
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
     <ns2:getNameResponse xmlns:ns2="http://ws.com/">
         <return>Test shrikant</return>
     </ns2:getNameResponse>
  </soap:Body>
</soap:Envelope>
Getting Started with WebService Project (Consumer): -
  1. Click on New->Dynamic Web Project
    ProjectName – WebServiceClient
    Target runtime – Apache Tomcat v
    Dynamic Web module Version – 2.5
    Configuration – CXF Web Services Project v2.5
    Click On Finish
 2.  Select wsdl folder from WebServiceServer/WEB-INF/wsdl
         Copy to WebServiceClient/WEB-INF/wsdl
     3.   Right Click on wsdl/shownameimpl.wsdl
         Select Web Services
         Select Generate Client and Click
     4.   Checked Monitor Web Service
            Click on Next
      5.   Click on Next
     6. Click On Next
        7.  Click On Next
     8.    Click on Start Server
                 Click On Finish
       9.   Click on Finish
10.   Check For the entire java file as a part of com.ws.*
11.    Select   IShowName_ShowNameImplPort_Client.java

                          ("Invoking getName...");

java.lang.String _getName_arg0 =

"Shrikant";




java.lang.String _getName__return = port.getName(_getName_arg0);
System.
out.println("getName.result=" + _getName__return);


And Run As Java Application.


<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://ws.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
    <q0:getName>
      <q0:name>shrikant</q0:name>
    </q0:getName>
  </soapenv:Body>
</soapenv:Envelope>