Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Wednesday, July 1, 2009

Spring and JCaptcha

Recently, I have made a sample application using Spring and JCaptcha, and want to share with you all.

Basically funda of Captcha is to distinguish between human or robot(basically bot written to automate to fill some forms of your website which might be used to crash your application).

In this, program will produce some image containing dictionary words or some random alphanumeric words which you have to fill up in corresponding textfield in the form.

For this I am using JCaptcha and Spring. You can get more information JCaptcha from http://forge.octo.com/jcaptcha/confluence/display/general/Home .

So let start with the integration of JCaptcha and Spring.


  • First thing is to have one conf file, mine is applicationContext.xml file which get loaded using web.xml file.
    <context-param>

    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
  • In applicationContext.xml file,put these lines for basic configuration :


<bean class="com.octo.captcha.service.image.DefaultManageableImageCaptchaService" id="imageCaptchaService"/>

But I think nobody want the basic things with your project so you need to change this configuration to :

<bean id="captchaService"
class="com.octo.captcha.service.multitype.GenericManageableCaptchaService">
<constructor-arg index="0">
<ref bean="imageEngine" />
</constructor-arg>
<constructor-arg index="1">
<value>180</value>
</constructor-arg>
<constructor-arg index="2">
<value>180000</value>
</constructor-arg>
<constructor-arg type="int" index="3" value="75000"/>
</bean>
This is for customizing your JCaptcha look and feel and the words which going to come in image that will be get displayed in your application form.


  • Third important thing is to set up the imageEngine bean which is instance of CaptchaEngine.
There are several Engines pre-configured, but as we want to control configuration, we have to use the GenericCaptchaEngine, which is built with a list of captcha factories

<bean id="imageEngine"

class="com.octo.captcha.engine.GenericCaptchaEngine">

<constructor-arg index="0">

<list>

<ref bean="CaptchaFactory" />

</list>

</constructor-arg>

</bean>

Then, a CaptchaFactory needs:

  • A word generator, to create the text to read.
  • A wordToImage, to generate the captcha from the text.
<bean id="CaptchaFactory"

class="com.octo.captcha.image.gimpy.GimpyFactory">

<constructor-arg>

<ref bean="wordgen" />

</constructor-arg>

<constructor-arg>

<ref bean="wordtoimage" />

</constructor-arg>

</bean>

A WordGenerator creates a text to be read, it can be random, be a common implementation take words from a list, and can make composition to create a text easier to read for a human being. In the example the WordGenerator needs a Dictionnary to get real words from.
<bean id="wordgen"

class="com.octo.captcha.component.word.wordgenerator.DictionaryWordGenerator">

<constructor-arg>

<ref bean="filedict" />

</constructor-arg>

</bean>

A Dictionary provides words, this one reads words from the one provided by default, with almost 6000 english words.

<bean id="filedict"

class="com.octo.captcha.component.word.FileDictionary">

<constructor-arg index="0">

<value>toddlist</value>

</constructor-arg>

</bean>

After to other important part to create a factory, is the WordToImage component, which is mainly created with three others components:

  • A font generator
  • A background generator
  • A Text paster
This example is a bit more complex one; it takes the usual main three components, but also three deformations, to increase the power of captchas. All three are set to none, a component which creates no deformation, see below, and Examples to have more examples of deformations.

<bean id="wordtoimage"

class="com.octo.captcha.component.image.wordtoimage.ComposedWordToImage">

<constructor-arg index="0">

<ref bean="fontGenRandom" />

</constructor-arg>

<constructor-arg index="1">

<ref bean="backGenUni" />

</constructor-arg>

<constructor-arg index="2">

<ref bean="simpleWhitePaster" />

</constructor-arg>

</bean>



A FontGenerator provide Fonts to a WordToImage, differents fonts increase the difficulties for cracking software using a learning process. This one generates random fonts from a list, and the first two arguments are the minimum size and the maximum size of the font.
<bean id="fontGenRandom"

class="com.octo.captcha.component.image.fontgenerator.RandomFontGenerator">

<constructor-arg index="0">

<value>40</value>

</constructor-arg>

<constructor-arg index="1">

<value>50</value>

</constructor-arg>

<constructor-arg index="2">

<list>

<ref bean="fontArial" />

</list>

</constructor-arg>

</bean>



A font is declared like this :

<bean id="fontArial" class="java.awt.Font">

<constructor-arg index="0">

<value>Arial</value>

</constructor-arg>

<constructor-arg index="1">

<value>0</value>

</constructor-arg>

<constructor-arg index="2">

<value>10</value>

</constructor-arg>

</bean>



The BackgrountGenerator component can be very simple like in the example, single color, or more complex with real picture, or fancy computed shapes. The first two arguments are always, the size (length and height) of the resulting image.
<bean id="backGenUni"

class="com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator">

<constructor-arg index="0">

<value>300</value>

</constructor-arg>

<constructor-arg index="1">

<value>100</value>

</constructor-arg>

</bean>


The TextPaster, according to his name, pastes the text on the background. This can be done in a simple way, (see example below), or another implementation can paste each character randomly (but still readably), or can double the text to make computers more confused. TextPaster can be even decorated to put perturbations around the text, a component, TextDecorator, is designed for this purpose, see Annexes for some examples. Commons arguments for TextPaster are:
  • Minimal length of the text
  • Maximal length of the text
  • A color generator component to create the text color, see Annexes.
    <bean id="simpleWhitePaster" class="com.octo.captcha.component.image.textpaster.SimpleTextPaster">

    <constructor-arg type="java.lang.Integer" index="0">

    <value>3</value>

    </constructor-arg>

    <constructor-arg type="java.lang.Integer" index="1">

    <value>5</value>

    </constructor-arg>

    <constructor-arg type="java.awt.Color" index="2">

    <ref bean="colorGreen" />

    </constructor-arg>

    </bean>
And a color definition:

<bean id="colorGreen" class="java.awt.Color">

<constructor-arg index="0">

<value>0</value>

</constructor-arg>

<constructor-arg index="1">

<value>255</value>

</constructor-arg>

<constructor-arg index="2">

<value>0</value>

</constructor-arg>

</bean>


This is all about the how jCaptcha generates the captcha image,now time is to use this captcha service with some application.
I am going to use this in simple registration form.
You can go through code for more details.


This is screenshot form of my registration page. The "grow" image is generated by the JCaptcha Controller.
Things to do for this are :

  • In your registration form ,you should have text with name "j_captcha_response" and the second thing is to have image source which will get generated using CaptchaImageGenerator class.
<tr>

<td><label>Control text</label></td><td><input type="text" name="j_captcha_response" /></td>

</tr>

<tr>

<td colspan="2"><img src="captcha.htm" /></td>

</tr>
  • There is CaptchaImageGenerator which generate a jpeg image file for capchta image using captcha service.
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

byte[] captchaChallengeAsJpeg = null;

ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
String captchaId = request.getSession().getId();

BufferedImage challenge = captchaService.getImageChallengeForID(captchaId,request.getLocale());

JPEGImageEncoder jpegEncoder =

JPEGCodec.createJPEGEncoder(jpegOutputStream);

jpegEncoder.encode(challenge);
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream responseOutputStream =
response.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();

return
null;
}
  • There will be validator method to validate this image :
protected
void validateCaptcha(HttpServletRequest request, BindException errors){

boolean isResponseCorrect = false;
String captchaId = request.getSession().getId();
String response = request.getParameter(captchaResponseParameterName);

try {
if(response != null){
isResponseCorrect = captchaService.validateResponseForID(captchaId, response);
}
} catch (CaptchaServiceException e) {

}
if(!isResponseCorrect){
String objectName = "Captcha";
String[] codes = {"invalid"};
Object[] arguments = {};
String defaultMessage = "Invalid image test entered!";
ObjectError oe = new ObjectError(objectName, codes, arguments, defaultMessage);
errors.addError(oe);
}
}

That's it you are done with JCpatcha. You can download the code from http://www.esnips.com/doc/271c96b3-2209-4dcd-9456-2acb302d431e/JCaptchaSpring

Tuesday, June 2, 2009

Spring WebService with Castor


This tutorial is all about Spring based contract-first based web-services.
I am also demostrating how to use Castor as marshaller and unmashaller.
The client for web-service I am using as SOAP UI which will generate the
SOAP request for the web-service and offcourse it will also show the response
sent by the web-service.

For developing web services I will start with the XML Schema/WSDL because it is contract first web-service followed by the Java code second. Spring-WS focuses on this development style, and this tutorial will help you get started. Note that the first part of this tutorial contains almost no Spring-WS specific information: it is mostly about XML, XSD, and WSDL. The second part focusses on implementing this contract using Spring-WS .

The most important thing when doing contract-first Web service development is
to try and think in terms of XML. This means that Java-language concepts are
of lesser importance. It is the XML that is sent across the wire, and you
should focus on that. The fact that Java is used to implement the Web service
is an implementation detail. An important detail, but a detail nonetheless.

In this tutorial, we will define a Web service that is created by a Store
department. Clients can send order request to this service to add a order.

1.2. Messages
In this section, we will focus on the actual XML messages that are sent to
and from the Web service. We will start out by determining what these messages
look like.

1.2.1. Order
In the scenario, we have to deal with Order requests, so it makes sense
to determine what a Order looks like in XML:

<OrderRequest>
<item>
<id>13245</id>
<itemName>Keyboard</itemName>
<quantity>10</quantity>
<discount>0</discount>
<sellingprice>3000</sellingprice>
</item>
<item>
<id>13247</id>
<itemName>Monitor</itemName>
<quantity>10</quantity>
<discount>0</discount>
<sellingprice>90000</sellingprice>
</item>
<customerID>898798</customerID>
<orderID>8797</orderID>
</OrderRequest>

A OrderRequest consists of customer id ,order id and the list of items that are in order. We have also decided to use the "string" elements, because that will save a lot of parsing hassle.

1.3. Data Contract
Now that we have seen some examples of the XML data that we will use,
it makes sense to formalize this into a schema. This data contract
defines the message format we accept. There are four different ways
of defining such a contract for XML:
DTDsXML
Schema (XSD)
RELAX
NGSchematron

DTDs have limited namespace support, so they are not suitable for Web
services. Relax NG and Schematron certainly are easier than XML Schema.
Unfortunately, they are not so widely supported across platforms. We
will use XML Schema.

By far the easiest way to create an XSD is to infer it from sample
documents. Any good XML editor or Java IDE offers this functionality.
Basically, these tools use some sample XML documents, and generate a
schema from it that validates them all. The end result certainly needs
to be polished up, but it's a great starting point.

This is our final xsd:
orderService.xsd
---------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:ideeksha-spring-ws="http://ideeksha.gotdns.com/order" targetNamespace="http://ideeksha.gotdns.com/order" elementFormDefault="qualified">
<complexType name="item">
<sequence>
<element name="id" type="string" minOccurs="1"/>
<element name="itemName" type="string" minOccurs="1"/>
<element name="quantity" type="string" minOccurs="1"/>
<element name="discount" type="string" minOccurs="1"/>
<element name="sellingprice" type="string" minOccurs="1"/>
</sequence>
</complexType>

<complexType name="order-response">
<sequence>
<element name="code" type="string" minOccurs="1"/>
</sequence>
</complexType>

<complexType name="order-request">
<sequence>
<element name="item" type="ideeksha-spring-ws:item" minOccurs="1" maxOccurs="unbounded"/>
<element name="customerID" type="string" minOccurs="1"/>
<element name="orderID" type="string" minOccurs="1"/>
</sequence>
</complexType>

<element name="OrderRequest" type="ideeksha-spring-ws:order-request"/>
<element name="OrderResponse" type="ideeksha-spring-ws:order-response"/>
</schema>

1.4. Service contract
A service contract is generally expressed as a WSDL file.
Note that in Spring-WS, writing the WSDL by hand is not required. Based on the XSD and some conventions, Spring-WS can create the WSDL for you, as explained in the section entitled Section 3.6, “Implementing the Endpoint”.
This is our final wsdl file generated by Spring :

http://localhost:8080/SpringWebService/order-ws/orderWebService.wsdl
---------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?><wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:sch="http://ideeksha.gotdns.com/order" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://ideeksha.gotdns.com/order" targetNamespace="http://ideeksha.gotdns.com/order">
<wsdl:types>
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:ideeksha-spring-ws="http://ideeksha.gotdns.com/order" elementFormDefault="qualified" targetNamespace="http://ideeksha.gotdns.com/order">
<complexType name="item">
<sequence>
<element minOccurs="1" name="id" type="string"/>
<element minOccurs="1" name="itemName" type="string"/>
<element minOccurs="1" name="quantity" type="string"/>
<element minOccurs="1" name="discount" type="string"/>

<element minOccurs="1" name="sellingprice" type="string"/>
</sequence>
</complexType>

<complexType name="order-response">
<sequence>
<element minOccurs="1" name="code" type="string"/>
</sequence>
</complexType>

<complexType name="order-request">

<sequence>
<element maxOccurs="unbounded" minOccurs="1" name="item" type="ideeksha-spring-ws:item"/>
<element minOccurs="1" name="customerID" type="string"/>
<element minOccurs="1" name="orderID" type="string"/>
</sequence>
</complexType>

<element name="OrderRequest" type="ideeksha-spring-ws:order-request"/>
<element name="OrderResponse" type="ideeksha-spring-ws:order-response"/>
</schema>

</wsdl:types>
<wsdl:message name="OrderResponse">
<wsdl:part element="tns:OrderResponse" name="OrderResponse">
</wsdl:part>
</wsdl:message>
<wsdl:message name="OrderRequest">
<wsdl:part element="tns:OrderRequest" name="OrderRequest">
</wsdl:part>
</wsdl:message>

<wsdl:portType name="OrderResource">
<wsdl:operation name="Order">
<wsdl:input message="tns:OrderRequest" name="OrderRequest">
</wsdl:input>
<wsdl:output message="tns:OrderResponse" name="OrderResponse">
</wsdl:output>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="OrderResourceSoap11" type="tns:OrderResource">

<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="Order">
<soap:operation soapAction=""/>
<wsdl:input name="OrderRequest">
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output name="OrderResponse">
<soap:body use="literal"/>
</wsdl:output>

</wsdl:operation>
</wsdl:binding>
<wsdl:service name="OrderResourceService">
<wsdl:port binding="tns:OrderResourceSoap11" name="OrderResourceSoap11">
<soap:address location="http://localhost:8080/SpringWebService/order-ws/orderWebService"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

I define the OrderRequest message, which gets used in the
portType.

The OrderRequest type is defined in the schema.

I define the OrderResource port type, which gets used in the
binding.


I use a document/literal style.

The literal http://schemas.xmlsoap.org/soap/http signifies a
HTTP transport.

The soapAction attribute signifies the SOAPAction HTTP
header that will be sent with every request.

The http://localhost:8080/SpringWebService/order-ws/SpringWebService address is the URL where the web-service can be invoked.

This is the final WSDL. We will describe how to implement the resulting schema and WSDL in the next section.

1.5. Creating the project
In this section, we will be using Maven2 to create the
initial project structure for us. Doing so is not required, but greatly reduces the amount of code we have to write to setup our HolidayService.

The following command creates a Maven2 web application project for us, using the Spring-WS archetype (that is, project template)
mvn archetype:create -DarchetypeGroupId=org.springframework.ws \
-DarchetypeArtifactId=spring-ws-archetype \
-DarchetypeVersion=1.5.7 \
-DgroupId=com.ideeksha.spring.ws \
-DartifactId=SpringWebService

This command will create a new directory called SpringWebService. In this directory,
there is a 'src/main/webapp' directory, which will contain the root of the WAR file.
You will find the standard web application deployment descriptor 'WEB-INF/web.xml' here, which defines a Spring-WS MessageDispatcherServlet and maps all incoming requests to this servlet:

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Store Department Order Service</display-name>
<servlet>
<servlet-name>order-ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>order-ws</servlet-name>
<url-pattern>/order-ws/*</url-pattern>
</servlet-mapping>
</web-app>

In addition to the above 'WEB-INF/web.xml' file, you will also need another,
Spring-WS-specific configuration file, named 'WEB-INF/order-ws-servlet.xml'.
This file contains all of the Spring-WS-specific beans such as EndPoints,
WebServiceMessageReceivers, and such like, and is used to create a new Spring container.
The name of this file is derived from the name of the attendant servlet (in this case
'order-ws') with '-servlet.xml' appended to it.

1.6. Implementing the Endpoint
In Spring-WS, you will implement Endpoints to handle incoming XML messages.
There are two flavors of endpoints: message endpoints and
payload endpoints. Message endpoints give access to the entire XML message, including SOAP headers. Typically, the endpoint will only be interested in the payload of the message, that is the contents of the SOAP body.
In that case, creating a payload endpoint makes more sense.

1.6.1. Handling the XML Message
In this sample application, we are going to use Castor to handle
the XML message.

OrderWSEndpoint.java
------------------------------
package com.ideeksha.order.ws;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;

@Endpoint
public class OrderWSEndpoint {

private static final Log LOG = LogFactory.getLog(OrderWSEndpoint.class);

@PayloadRoot(localPart = "OrderRequest", namespace = "http://ideeksha.gotdns.com/order")
public OrderResponse receiveOrder(
OrderRequest orderRequest) {

try {
List<Item> itemList = orderRequest.getItemList();

Iterator<Item> iterator = itemList.iterator();
while (iterator.hasNext()) {
Item item = iterator.next();
System.out.println(item);
}
} catch (Exception e) {
LOG.error("", e);
}
OrderResponse orderResponse = new OrderResponse();
orderResponse.setCode("SUCCESS");

return orderResponse;
}

}

We are using annoation to mark a class as Endpoint and the method which is to be executed for the particular type of request is denoted by
"@PayloadRoot(localPart = "OrderRequest", namespace = "http://ideeksha.gotdns.com/order")" anotaion.
So "receiveOrder" ,method will get executed if any OrderRequest is come for this EndPoint.

Because we use Castor, we must add some dependencies to the Maven pom.xml, which is in the root of our project directory. Here is the part of POM file:

<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core-tiger</artifactId>
<version>1.5.6</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.0</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.xml.soap</groupId>
<artifactId>saaj-api</artifactId>
<version>1.3</version>
<scope>runtime</scope>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.xml.messaging.saaj</groupId>
<artifactId>saaj-impl</artifactId>
<version>1.3</version>
<scope>runtime</scope>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.codehaus.castor</groupId>
<artifactId>castor</artifactId>
<version>1.2</version>
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
</dependencies>

Here is how we would configure these classes in our order-ws-servlet.xml

Spring XML configuration file:

<beans xmlns="http://www.springframework.org/schema/beans">
<bean id="orderWSEndpoint" class="com.ideeksha.order.ws.OrderWSEndpoint" autowire="byName"/>
</beans>

1.6.2. Routing the Message to the Endpoint

Now that we have written an endpoint that handles the message, we must define how incoming messages are routed to that endpoint. In Spring-WS, this is the responsibility of an EndpointMapping. In this tutorial, we will route messages based on their content, by using a PayloadRootAnnotationMethodEndpointMapping. Here is how we configure a PayloadRootAnnotationMethodEndpointMapping in order-ws-servlet.xml:

<bean id="loggingInterceptor"
class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor"/>
<bean
class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping">
<property name="interceptors">
<list>
<ref local="loggingInterceptor"/>
</list>
</property>
</bean>

This means that whenever an XML message is received it will check all the annonated EndPoint Class and check for the method which will serve the request with that particular namespace and local name.(It also adds a PayloadLoggingInterceptor,that dumps incoming and outgoing messages to the log.)

1.7. Publishing the WSDL
Finally, we need to publish the WSDL. As stated in Section 3.4, “Service contract”, we don't need to write a WSDL ourselves; Spring-WS can generate one for us based on some conventions.
Here is how we define the generation:

<bean id="orderWebService" class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
<property name="schema" ref="orderSchema"/>
<property name="portTypeName" value="OrderResource"/>
<property name="locationUri" value="/order-ws/orderWebService"/>
<property name="targetNamespace" value="http://ideeksha.gotdns.com/order"/>
</bean>
<bean id="orderSchema" class="org.springframework.xml.xsd.SimpleXsdSchema">
<property name="xsd" value="/WEB-INF/orderService.xsd"/>
</bean>

The bean id determines the URL where the WSDL can be retrieved. In this case, the bean id is holiday, which means that the WSDL can be retrieved as holiday.wsdl in the servlet context. The full URL will typically be

http://localhost:8080/SpringWebService/order-ws/orderWebService.wsdl.

The schema property refers to the human resource schema we defined in Section 3.3, “Data Contract”, wrapped in a SimpleXsdSchema. We simply placed the schema in the WEB-INF directory of the application.

Next, we define the WSDL port type to be OrderResource.

We set the location where the service can be reached:
/order-ws/orderWebService/. We use a a relative URI and we instruct the framework to transform it dynamically to an absolute URI. Hence, if the service is deployed to different contexts we don't have to change the URI manually.
Finally, we define the target namespace for the WSDL definition itself. Setting these
is not required. If not set, we give the WSDL the same namespace as the schema.

1.8. Doing the Castor Mapping
We have to define the marshaller and unmashller for the XML messages.We define them in order-ws-servlet.xml file.

<bean id="marshaller" class="org.springframework.oxm.castor.CastorMarshaller">
<property name="mappingLocation" value="classpath:WEB-INF/castor-mapping.xml"/>
</bean>
<bean
class="org.springframework.ws.server.endpoint.adapter.GenericMarshallingMethodEndpointAdapter">
<constructor-arg ref="marshaller"/>
<constructor-arg ref="marshaller"/>
</bean>

O/X mapping is done using castor so you can assess the xml as object.Below is the OrderRequest and OrderResponse with its corresponding castor mapping:

OrderRequest.java:
-------------------
package com.ideeksha.order.ws;

import java.util.List;

public class OrderRequest {
private List<Item> itemList = null;
private String customerID;
private String orderID;

public List<Item> getItemList() {
return itemList;
}

public void setItemList(
List<Item> itemList) {
this.itemList = itemList;
}

public String getCustomerID() {
return customerID;
}

public void setCustomerID(String customerID) {
this.customerID = customerID;
}

public String getOrderID() {
return orderID;
}

public void setOrderID(String orderID) {
this.orderID = orderID;
}

}


OrderResponse.java
-----------------------

package com.ideeksha.order.ws;

public class OrderResponse {

private String code;

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

}

Item.java
--------------------
package com.ideeksha.order.ws;

public class Item {
private String id = null;
private String itemName = null;
private String sellingprice = null;
private String quantity = null;
private String discount = null;

public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getSellingprice() {
return sellingprice;
}
public void setSellingprice(String sellingprice) {
this.sellingprice = sellingprice;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
@Override
public String toString() {
return id+ " " + itemName + " " + sellingprice + " " +quantity + " " + discount;
}


}

castor-mapping.xml
--------------------------------

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN"
"http://castor.org/mapping.dtd">
<mapping>
<description>Description of the mapping</description>
<class name="com.ideeksha.order.ws.OrderResponse">
<map-to xml="OrderResponse" ns-uri="http://ideeksha.gotdns.com/order" />
<field name="code">
<bind-xml name="code" node="element" type="string"/>
</field>

</class>

<class name="com.ideeksha.order.ws.Item">
<map-to xml="item" ns-uri="http://ideeksha.gotdns.com/order" />

<field name="id">
<bind-xml name="id" node="element" type="string"/>
</field>

<field name="itemName">
<bind-xml name="itemName" node="element" type="itemName"/>
</field>

<field name="quantity">
<bind-xml name="quantity" node="element" type="string"/>
</field>

<field name="discount">
<bind-xml name="discount" node="element" type="itemName"/>
</field>

<field name="sellingprice">
<bind-xml name="sellingprice" node="element" type="itemName"/>
</field>


</class>

<class name="com.ideeksha.order.ws.OrderRequest">
<map-to xml="OrderRequest" ns-uri="http://ideeksha.gotdns.com/order" />
<field name="customerID">
<bind-xml name="customerID" node="element" type="itemName"/>
</field>
<field name="orderID">
<bind-xml name="orderID" node="element" type="itemName"/>
</field>
<field name="itemList" type="com.ideeksha.order.ws.Item" collection="arraylist">
<bind-xml name="item" node="element" type="ideeksha-spring-ws:item"/>
</field>

</class>
</mapping>


You can create a WAR file using mvn install.
If you deploy the application (to Tomcat, Jetty, etc.), and point your browser at
this location, you will see the generated WSDL. This WSDL is ready to be used by clients, such as soapUI, or other SOAP frameworks.

I will explain how to create project in SOAPUI and send a order request to our webservice.
Create new Project in SOAP UI and give the project name and the wsdl file path.In my case the Project name is SpringWebSerice and the wsdl path will be
"http://localhost:8080/SpringWebService/order-ws/orderWebService.wsdl"


The click on "Order" and then to "request1" under the SpringWebService Project menu.
Edit the default values of this request.Now send this request be clicking on run button(green arrowhead) on the top of the request message window. And the you will get "SUCCESSFUL" as response as we are sending as Order response.




This conclude spring webservice turorial. You can download the source code for this article from http://www.mediafire.com/download.php?zxlmjmnuiei

Thursday, May 28, 2009

Spring + Hibernate


Spring + Hibernate


This article is for those who know spring and hibernate but never integrated or run them together. I hope you know both of these technologies as I am not going in detail of these :)

Steps to integrate hibernate and spring are as follows:
1. Jars for hibernate, spring and the dependencies (Use maven for this, I will be adding pom.xml file for your reference).
2. Mapping and Configuration files of hibernate.
3. And off-course you have to have the spring bean xml file.

I will split this tutorial into three parts:
1. Develop Hibernate Application
2. Using hibernate with Spring Framework.
3. Running the Example Application.


Developing Hibernate Application:
We will have employee as entity with which we are going play with.

First will look into how we do this in traditional way means with standalone client:
1. Will have Employee POJO class
Employee.java
---------------------------------------------
package com.ideeksha;

public class Employee {

private Long employeeCode;
private String employeeName;
private int employeesalary;

public Long getEmployeeCode() {
return employeeCode;
}
public void setEmployeeCode(Long employeeCode) {
this.employeeCode = employeeCode;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public int getEmployeesalary() {
return employeesalary;
}
public void setEmployeesalary(int employeesalary) {
this.employeesalary = employeesalary;
}
}

2. Then will have the mapping file

Employee.hbm.xml
---------------------------------------------

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ideeksha">
<class name="Employee" table="EMP">
<id name="employeeCode" column="EMP_CODE" type="long">
<generator class="increment"></generator>
</id>
<property name="employeeName" column="NAME" type="string"></property>
<property name="employeesalary"></property>
</class>
</hibernate-mapping>

3. And the configuration file :

Hibernate.cfg.xml
---------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">tiger</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:machinename</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</property>

<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>

<mapping resource="Employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>
4. Offcourse the main class to run this :

PersistEmployee.java
--------------------------------------------------------


package com.ideeksha;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class PersistEmp {

/**
* @param args
*/
public static void main(String[] args) {
SessionFactory factory=null;
Session session = null;
Transaction tx = null;

try
{
factory = new Configuration().configure().buildSessionFactory();
session = factory.openSession();
tx = session.beginTransaction();

Employee emp = new Employee();
emp.setEmployeeName("Anil Verma");

session.save(emp);


tx.commit();

}catch (Exception e) {
tx.rollback();
e.printStackTrace();
}finally
{
session.close();
factory.close();
}


}

}


Yes!! you have developed your simple hibernate application.

2. Using hibernate with Spring Framework.

And now time is come to integrate this to Spring.Configuring the Hibernate SessionFactory in Spring.Here is an example Hibernate SessionFactory configured in Spring. You will be using this instead of the typical hibernate-config.xml. All we are doing here is telling Hibernate/Spring what our Hibernate mapping files are:

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>

<value>Employee.hbm.xml</value>
</list>
</property>
</bean>

If you have a hibernate.properties in your classpath, the Spring LocalSessionFactoryBean will use that file to configure the database connections, dialect and pooling. Alternatively, you can define a DataSource in Spring (any class that implements javax.sql.DataSource) and explicity set all of your Hibernate properties in the LocalSessionFactoryBean:

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>

</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle9iDialect
</prop>
</props>

</property>
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName">
<value> oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value> jdbc:oracle:thin:@localhost:1521:machinename</value>

</property>
<property name="username"><value>scott</value></property>
<property name="password"><value>tiger</value></property>
</bean>


Extending HibernateDaoSupport for the Actual DAO Implementation
The Spring HibernateDaoSupport class provides all kinds of convenience methods for working with Hibernate. Most of these are accessible via the HibernateTemplate object that this class exposes.
Anyway, here is our EmployeeDAO implemented by extending HibernateDaoSupport:

EmployeeDAOImpl.java
-----------------------------------------
package com.ideeksha;
public class EmployeeDAOImpl
extends HibernateDaoSupport
implements EmployeeDAO
{
/**
* Returns a java.util.List of all Employees in the system.
* @return
*/
public Collection getEmployees()
{
return getHibernateTemplate().loadAll(Employee.class);
}

/**
* Get a Employee Object given the id
* @param id
* @return
*/
public Employee getEmployeeById(Long id)
{
return (Employee)
getHibernateTemplate().load(Employee.class, id);
}

/**
* Save a Employee Object, if the given Employee
* is not in the data store,it should insert it,
* if it is in the data store, it should update it.
* @param employee
*/
public Employee saveEmployee(Employee employee)
{
getHibernateTemplate().saveOrUpdate(employee);
return employee;
}
}

3. Running the Example Application.

Now we are done with the spring configuration. We will write a client for Spring DAO now.
PersistEmp.java
--------------------------------

package com.ideeksha;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersistEmp {

public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring2beans.xml");
EmployeeDAO dao=( EmployeeDAO)context.getBean("employeeDAO");
Employee emp = new Employee();
emp.setEmployeeName("Anil Verma");
dao.save(group);

}
}

Now we can run this client application directly. This will be the final spring conf file :
spring2beans.xml
-------------------------------
<!-- from the file 'context.xml' -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">


<bean id="employeeDAO" class="com.ideeksha.EmployeeDAOImpl">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/hibernate"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>com/ideeksha/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
</value>
</property>
</bean>
</beans>


And yes the last part remaining is the pom.xml file :

<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.ideeksha</groupId>
<artifactId>SpringHibernate</artifactId>
<name>SpringHibernate</name>
<version>0.0.1-SNAPSHOT</version>
<description/>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.5.ga</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>

</project>



Check the database table, is your employee is been persisted or not ...If Yes ..I can say now you have successfully integrated hibernate and spring. If "No" ...Its time to go to bed ...try next morning :)


And off-course if you feel lazy to do the coding ...this is the link were you will get the code ..

http://www.mediafire.com/download.php?jydgwgmhynw

Cheers!!!

Wednesday, May 27, 2009


The Spring Framework: Understanding IoC

In Spring, the Inversion of Control (IoC) principle is implemented using the Dependency Injection (DI) design pattern. IoC or Inversion of Control is one of the core features of Spring. It helps in simplifying the implementation of business logic. To use the Spring Framework to its full potential, understanding the IoC container of the framework is essential.

Let's understand dependency injection with the help of an example. First we will see a java version of the example and later we will add spring functionalities to it. As far as the example go, its pretty simple. The Quiz interface exposes the getQuestion() method. To keep things simple, our Quiz will generate only one question.

Quiz.java
----------------
package com.ideeksha;

public interface Quiz {

public String getQuestion();
}

The StrutsQuiz and the SpringQuiz class implements Quiz interface and they generate questions related to struts and spring respectively.

StrutsQuiz.java
----------------------
package com.ideeksha;

public class StrutsQuiz implements Quiz {

@Override
public String getQuestion() {
return "Are you new to Struts?";
}

}

SpringQuiz.java
----------------------
package com.ideeksha;

public class SpringQuiz implements Quiz {

@Override
public String getQuestion() {
return "Are you new to Spring?";
}

}

We have a QuizService class that displays the question to the user. The QuizService class holds reference to the Quiz.

QuizService.java
-----------------------
package com.ideeksha;

public class QuizService {

private Quiz quiz = new SpringQuiz ();

public void askQuestion()
{
System.out.println(quiz.getQuestion());
}
}

Finally we create the QuizProgram class to conduct quiz.
QuizProgram.java
----------------
package com.ideeksha;

public class QuizProgram {

public static void main(String[] args) {
QuizService quizService = new QuizService();
quizService.askQuestion();
}

}

As you can see it is pretty simple, here we create an instance of the QuizService class and call the askQuestion() method. When you run the program as expected "Are you new to Spring?" gets printed in the console.




Spring Dependency Injection

Let's have a look at the class diagram of this example. The green arrows indicate generalization and the blue arrows indicates association.




As you can see this architecture is tightly coupled. We create an instance of the Quiz in the QuizService class in the following way.
private Quiz quiz = new SpringQuiz();

To make our quiz master Struts genius we need to make modifications to the QuizService class like this.
private Quiz quiz = new StrutsQuiz();

So it is tightly coupled. Now lets see how we can avoid this by using the Dependency Injection design pattern. The Spring framework provides prowerful container to manage the components. The container is based on the Inversion of Control (IoC) principle and can be implemented by using the Dependency Injection (DI) design pattern. Here the component only needs to choose a way to accept the resources and the container will deliver the resource to the components.
In this example instead of we, directly creating an object of the Quiz bean in the QuizService class, we make use of the container to do this job for us. Instead of hard coding any values we will allow the container to inject the required dependancies.
We can inject the dependancies using the setter or constructor injection. Here we will see how we can do this using the setter injection.
QuizService.java
-----------------------
package com.ideeksha;

public class QuizService {

Quiz quiz;

public void setQuiz(Quiz quiz) {
this.quiz = quiz;
}

public void askQuestion()
{
System.out.println(quiz.getQuestion());
}
}

The value for the Quiz will be set using the setQuiz () method. The Quiz object is never instantiated in the QuizService class, but still we access it. Usually this will throw a NullPointerException, but here the container will instantiate the object for us, so it works fine.

After making all the changes, the class diagram of the example look like this.



The container comes into picture and it helps in injecting the dependancies.
The bean configuration is done in the beans.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="springQuiz" class="com.ideeksha.SpringQuiz"></bean>
<bean id="strutsQuiz" class="com.ideeksha.StrutsQuiz"></bean>
<bean id="quizService" class="com.ideeksha.QuizService">
<property name="quiz">
<ref local="springQuiz"/>
</property>
</bean>
</beans>

We define each bean using the bean tag. The id attribute of the bean tag gives a logical name to the bean and the class attribute represents the actual bean class. The property tag is used to refer the property of the bean. To inject a bean using the setter injection you need to use the ref tag.

Here a reference of SpringQuiz is injected to the Quiz bean. When we execute this example, "Are you new to Spring?" gets printed in the console.
To make our Quiz ask questions related to Struts, the only change we need to do is, to change the bean reference in the ref tag.

<bean id="quizService" class="com.ideeksha.QuizService">
<property name="quiz">
<ref local="strutsQuiz"/>
</property>
</bean>

In this way the Dependency Injection helps in reducing the coupling between the components. And yes it says “NO” to ‘new’ operator!!!

To Run This example



QuizExample.java

---------------------------
package com.ideeksha;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class QuizProgram {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
QuizService quizService = (QuizService) context.getBean("quizService");
quizService.askQuestion();
}
}


More things on Spring IOC --Ways to do Spring dependency Injection !!!
Inversion of Control or IoC is one of the techniques used to wire services or components to an application program. By definition, IoC is “A software design pattern and set of associated programming techniques in which the flow of control of a system is inverted in comparison to the traditional interaction mode.” Simply stated, in IoC, instead of an application calling the framework, it is the framework that calls the components specified by the application.
This approach is similar to the one that Hollywood agents adopt with their clients. It is sometimes known as “Don’t call me, I will call you.” This is why IoC is also known as the Hollywood approach.
However, IoC is a broad and generic term. The aspect of IoC that the Spring Framework uses is "Injection of required resources or dependency at Run-time into the dependent resource," which is also known as Dependency Injection. Hence, the service provided by the IoC container of Spring is Dependency Injection. Therefore, I will be using the terms IoC and Dependency Injection in a lax way.
There are three forms or styles of Dependency Injection. They are:
1. Constructor Injection
2. Setter Injection
3. Interface Injection

Of these, the Spring Framework directly supports the first and second forms whereas the third form is supported indirectly. Between the first and the second, the Spring Framework prefers the use of second rather than the first. Here are the details.
1. Constructor Injection: In Constructor Injection, an IoC container uses the constructor to inject the dependency. All the dependencies, whether they are simple values or references to other objects, are declared in the constructor. One of the advantages of Constructor Injection is that all the dependencies are declared in one go. This also helps in understanding whether the class depends on too many services.
2. Setter Injection: This form of Dependency Injection uses Setters, also known as mutators (because they change the value of the corresponding instance variables), to inject the required resources or dependencies. In other words, each of the objects that the class depends upon will have a setter and the IoC container will use the setters to provide the resource at run-time.

The main difference between Constructor Injection and Setter Injection is that in Constructor Injection, the handing over of the dependencies takes place during instantiation of the dependent object, whereas with Setter Injection, it takes place after the dependent object is instantiated. The Spring Framework favors Setter Injection over Constructor Injection.
3. Interface Injection: Interface Injection provides the concrete implementations of an interface to the dependent object according to the configuration. The main difference between Interface Injection and the previous two is that in Interface Injection, any of the implementations of the interface can be injected, whereas with the other two, the object of the class specified is injected. Spring does not provide direct support for Interface Injection.

That completes the overview of IoC.

To execute this example add the following jar files to the classpath.

antlr-runtime-3.0
commons-logging-1.0.4
org.springframework.asm-3.0.0.M3
org.springframework.beans-3.0.0.M3
org.springframework.context-3.0.0.M3
org.springframework.context.support-3.0.0.M3
org.springframework.core-3.0.0.M3
org.springframework.expression-3.0.0.M3