Wednesday, 6 March 2013

How to set properties of a bean from properties file in spring

How to set properties of a bean from properties file.......

This can be accomplished by PropertyPlaceholderConfigurer class

Bean.java
package props;

public class Bean {
private String value1, value2;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
}


ApplicationResource.properties
bean.value1=Sidhartha
bean.value2=Ray

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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<bean name="properties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="ApplicationResource.properties"/>
</bean>
<bean id="bean" class="props.Bean">
<property name="value1" value="${bean.value1}"/>
<property name="value2" value="${bean.value2}"/>
</bean>
</beans>

Client.java

package props;

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

public class Client {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
Bean bean = context.getBean("bean", Bean.class);
System.out.println(bean.getValue1() + " - " + bean.getValue2());
}
}

Web Services Using Tomcat & Axis Framework

Developing SOAP Based Web Services Using Tomcat-6 & Axis-1....

Download Tomcat 6  & Axis 1.2RC2

Installing Axis on Tomcat
Explode the axis zip folder. Now you need to deploy the Axis engine to Tomcat:
Here's how to do it:

Copy "..\axis-1_2\webapps\axis" into "..\apache-tomcat-6.0.36\webapps" folder.
Also add activation.jar & mail.jar into "..\apache-tomcat-6.0.36\webapps\axis\WEB-INF\lib"


Verify that Axis has been deployed correctly:

http://localhost:8085/axis/




Publishing Web Services with Axis

Let's say we have a simple class like the following:
HelloService.java 
 
package com.ws;
public class HelloService {
 public String sayHello(String name){
  return "Hello " + name + " !";
 } 
        public String sayBye(String name){
  return "Bye " + name + " !";
 }
}

How do we go about making this class available via SOAP?
There are a couple of answers to that question, but we'll start with an easy solution.

At first compile the class :

Goto HelloService.java's folder in command promt & compile,

javac -d . HelloService.java

Now copy that .class file & paste it into ..\apache-tomcat-6.0.36\webapps\axis\WEB-INF\classes along with the package structure(here com\ws\HelloService.class).

Ok, now the last step is registering your Web Service so that Axis is aware of it. A Web Service can be registered with a Web Service Deployment Descriptor (WSDD) file. A deployment descriptor contains a bunch of things you want to "deploy" into Axis - i.e. make available to the Axis engine.
Here's a simple wsdd file for our WebService:

HelloService.wsdd

<deployment xmlns="http://xml.apache.org/axis/wsdd/"                     xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
    <service name="HelloService" provider="java:RPC">
        <parameter name="className" value="com.ws.HelloService" />
        <parameter name="allowedMethods" value="*" />
    </service>
</deployment>





Pretty simple, really - the outermost element tells the engine that this is a WSDD deployment,and defines the "java" namespace. Then the service element actually defines the service for us. A service is a targeted chain which means it may have any of: a request flow, a provider, and a response flow.

In this case, our provider is "java:RPC", which is built into Axis, and indicates a Java RPC service. We need to tell the RPCProvider that it should instantiate and call the correct class (e.g. test.HelloService), and another to tell the engine that any public method on that class may be called via SOAP (that's what the "*" means)
Now save your wsdd file as HelloService.wsdd and run the Admin which is an Utility to deploy the WebService :

java -classpath %AXIS_HOME%/lib/axis.jar;%AXIS_HOME%/lib/commons-discovery-0.2.jar;%AXIS_HOME%/lib/commons-logging-1.0.4.jar;%AXIS_HOME%/lib/saaj.jar;%AXIS_HOME%/lib/jaxrpc.jar org.apache.axis.utils.Admin server HelloService.wsdd

If everything was Ok now you should see the WebService deployed on Axis: check the "List" option from the URL http://localhost:8085/axis/

Obtaining WSDL for deployed services
Now you can see your wsdl file something like this.......

http://localhost:8085/axis/services/HelloService?wsdl

<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="http://localhost:8085/axis/services/HelloService"           xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://localhost:8085/axis/services/HelloService" xmlns:intf="http://localhost:8085/axis/services/HelloService" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!--WSDL created by Apache Axis version: 1.4
Built on Apr 22, 2006 (06:55:48 PDT)-->

   <wsdl:message name="sayHelloRequest">
      <wsdl:part name="in0" type="xsd:string"/>
   </wsdl:message>
   <wsdl:message name="sayHelloResponse">
      <wsdl:part name="sayHelloReturn" type="xsd:string"/>
   </wsdl:message>
   <wsdl:portType name="HelloService">
      <wsdl:operation name="sayHello" parameterOrder="in0">
         <wsdl:input message="impl:sayHelloRequest" name="sayHelloRequest"/>
         <wsdl:output message="impl:sayHelloResponse" name="sayHelloResponse"/>
      </wsdl:operation>
   </wsdl:portType>
   <wsdl:binding name="HelloServiceSoapBinding" type="impl:HelloService">
      <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
      <wsdl:operation name="sayHello">
         <wsdlsoap:operation soapAction=""/>
         <wsdl:input name="sayHelloRequest">
            <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://ws.com" use="encoded"/>
         </wsdl:input>
         <wsdl:output name="sayHelloResponse">
            <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://localhost:8085/axis/services/HelloService" use="encoded"/>
         </wsdl:output>
      </wsdl:operation>
   </wsdl:binding>
   <wsdl:service name="HelloServiceService">
      <wsdl:port binding="impl:HelloServiceSoapBinding" name="HelloService">
         <wsdlsoap:address location="http://localhost:8085/axis/services/HelloService"/>
      </wsdl:port>
   </wsdl:service>
</wsdl:definitions>



The client
Let's take a look at an example Web Service Client that will call the sayhello method of the HelloService Web Service
 
Client.java
 
package com.ws;

import java.net.MalformedURLException;
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;

public class Client{
  public static void main(String [] args) throws MalformedURLException, AxisFault  {
   String endpoint = "http://localhost:8085/axis/services/HelloService?wsdl";
   Call client = new Call(endpoint);
   String response = (String)client.invoke("http://localhost:8085/axis/services/HelloService",
          "sayHello",new Object [] {"Sidhartha"});
   System.out.println(response);
     }
}


Generating Java Classes from WSDL

Another approach is to generate Java Classes starting from WSDL contract. You can use the
AdminClient to follow this approach:

java -classpath %AXIS_HOME%/lib/wsdl4j-1.5.1.jar;%AXIS_HOME%/lib/axis.jar;%AXIS_HOME%/lib/commons-discovery-0.2.jar;%AXIS_HOME%/lib/commons-logging-1.0.4.jar;%AXIS_HOME%/lib/saaj.jar;%AXIS_HOME%/lib/jaxrpc.jar org.apache.axis.wsdl.WSDL2Java http://localhost:8085/axis/services/HelloService?wsdl

This will generate the following classes under the service namespace which is localhost\axis\services\HelloService

Spring Web Services Using JAXB

Spring Web Services Example Easy Steps.....

Just a glimpse........
Spring Web Services is a product from Spring community to develop the web services in easier manner. Spring Web Services is following the strategy of contract-first web services. It focuses more on XML and lesser on Java implementation. In this article, we will learn how to write a simple web service application using Spring Web Services. It is expected that the reader has a fair amount of knowledge on Web services concepts before continuing with the article along with the basics of Spring Framework like Dependency Injection and Inversion of Control.

Spring Web Services Example :
In this article, we will design a simple application that'll ask for an employee id(consisting of two characters and five digits, e.g ab12345) and will return the employee details(here name & email id, e.g. Sidhartha Ray & ab@yahoo.co.in) using Spring Web Service in Eclipse IDE. This article will provide the content in a tutorial fashion in a step-by-step manner and parallely giving relevant details to that section. Generally speaking, developing web services involves writing artifacts in the server and the client tier. We will look into the details about those artifacts in the subsequent sections. Given below are the pre-requisite softwares to develop and run the application
 1.Java Development Kit (1.6 or later)
 2.Spring Web Service Framework (1.5.9)
 3.Eclipse3.4 or later (add plugin jaxb 2.0 or later)
 4.Web Server(Apache Tomcat 6)

And the following jar files
1.commons-logging-1.1.1.jar
2.spring.jar
3.spring-beans.jar 
(N.B. Get all the above jars by downloading spring framework 2.5.6 & spring web services 1.5.9)

Server-side artifacts :

The following steps are provided in building up the various server-side artifacts.
 1.Contract Design
 2.Defining the service interface
 3.Implementing the service interface
 4.Defining Spring Web-Service endpoints
 5.Configuring deployment descriptor.
 6.Configuring Spring’s Application Context.

Remember to build the server tier as a web application(Dynamic Web Project in Eclipse IDE), so that it can be made runnable in any web server.

Application folder structure in eclipse'll look like :
      

1.Contract design :

We will design the contract for the service through xml, i.e. a .wsdl(Web Service Description Language) file. The contract defines the input and the output messages that a service expects. Since we wanted to enforce restriction on the input and output, we will provide an XSD, i.e. a.xsd(XML Schema Definition) file. In our case, the request and the response messages will be simple string objects. The following definitions define the .xsd file & .wsdl file:

Employee.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:tns="http://employee.com/schema" elementFormDefault="qualified"
    targetNamespace="http://employee.com/schema">
    <xsd:element name="EmployeeDetailsRequest">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element ref="tns:empId" />
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="EmployeeDetailsResponse">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="name" type="xsd:string" />
                <xsd:element name="email" type="xsd:string" />
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="empId">
        <xsd:simpleType>
            <xsd:restriction base="xsd:string">
                <xsd:pattern value="[a-z]{2}[0-9]{5}" />
            </xsd:restriction>
        </xsd:simpleType>
    </xsd:element>
</xsd:schema>

Now you can generate the service artifacts or jaxb classes by following steps :

i.) Right click on .xsd file >> select JAXB 2.0 >> select Run XJC >>(a pop up will appear) Give Package Name as "com.employee.schema" Output Directory as project's src directory >> Select Finish
ii.) Refresh your project directory and you'll find following four classes :



Employee.wsdl
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<wsdl:definitions xmlns:emp="http://employee.com/schema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://employee.com/employee" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="Employee" targetNamespace="http://employee.com/employee">
    <wsdl:types>
        <xsd:schema targetNamespace="http://employee.com/employee">
            <xsd:import namespace="http://employee.com/schema" schemaLocation="Employee.xsd"/>
        </xsd:schema>
    </wsdl:types>
    <wsdl:message name="EmployeeDetailsRequest">
        <wsdl:part element="emp:EmployeeDetailsRequest" name="EmployeeDetailsRequest"/>
    </wsdl:message>
    <wsdl:message name="EmployeeDetailsResponse">
        <wsdl:part element="emp:EmployeeDetailsResponse" name="EmployeeDetailsResponse"/>
    </wsdl:message>
    <wsdl:portType name="EmployeePortType">
        <wsdl:operation name="EmployeeDetails">
            <wsdl:input message="tns:EmployeeDetailsRequest"/>
            <wsdl:output message="tns:EmployeeDetailsResponse"/>
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="EmployeeSOAPBinding" type="tns:EmployeePortType">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="EmployeeDetails">
            <soap:operation soapAction="http://employee.com/employee/EmployeeDetails"/>
            <wsdl:input>
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="EmployeeService">
        <wsdl:port binding="tns:EmployeeSOAPBinding" name="Employee">
            <soap:address location="http://localhost:8888/EmployeeWS/services/Employee"/>
        </wsdl:port>
    </wsdl:service>
</wsdl:definitions>

2.Defining the service interface :

Defining the service interface - The service interface represents the client-facing interface for invoking the service by passing in the required inputs. Note that the interface will be a simple POJO, the interface doesn’t need to extend or implement any of the spring web-service related APIs. In this example, the input will be a simple java string object.

EmployeeService.java
package com.employee.service;

import com.employee.schema.EmployeeDetailsRequest;
import com.employee.schema.EmployeeDetailsResponse;

public interface EmployeeService {
    EmployeeDetailsResponse getEmployeeDetails(EmployeeDetailsRequest request);
}


3.Implementing the service interface :
 
Implementing the service interface - Writing the implementation for the above service interface will be fairly straight-forward. It returns an EmployeeDetailsResponse object with name : Sidhartha Ray & Email : ab@yahoo.co.in if employee id is ab12345, else returns with name : Nitesh Yetta & Email : xy@yahoo.co.in.

EmployeeServiceImpl.java
package com.employee.service;

import com.employee.schema.EmployeeDetailsRequest;
import com.employee.schema.EmployeeDetailsResponse;

public class EmployeeServiceImpl implements EmployeeService{

    @Override
    public EmployeeDetailsResponse getEmployeeDetails(
            EmployeeDetailsRequest request) {
        EmployeeDetailsResponse response = new EmployeeDetailsResponse();
        if(request.getEmpId().equalsIgnoreCase("ab12345")){    //two char & five digits
            response.setEmail("ab@yahoo.co.in");
            response.setName("Sidhartha Ray");
        }else{
            response.setEmail("xy@yahoo.co.in");
            response.setName("Nitesh Yetta");
        }
        return response;
    }
}


4.Defining Spring Web-Service endpoint :

Defining endpoints - Endpoints are components for processing the input request messages and are usually responsible for invoking the desired service by passing in the required details. Spring Web Services implementation comes with two flavors of endpoints – message endpoints and payload endpoints. Message endpoints provide access to the raw input XML message including the XML header along with the XML body. On the other hand, Payload endpoints are useful in dealing with the XML body alone. In our simple application, we will define a Payload endpoint for parsing the input XML message for invoking the service.

EmployeeDetailsEndpoint.java
package com.employee.endpoint;

import org.springframework.oxm.Marshaller;
import org.springframework.ws.server.endpoint.AbstractMarshallingPayloadEndpoint;
import com.employee.schema.EmployeeDetailsRequest;
import com.employee.service.EmployeeService;

public class EmployeeDetailsEndpoint extends AbstractMarshallingPayloadEndpoint{
    private EmployeeService service;
    public EmployeeDetailsEndpoint(EmployeeService service,
            Marshaller marshaller) {
        super(marshaller);
        this.service = service;
    }
    @Override
    protected Object invokeInternal(Object arg0) throws Exception {
        return service.getEmployeeDetails((EmployeeDetailsRequest)arg0);
    }
}
Here as we want to use JAXB for marshalling/unmarshalling, we have gone through AbstractMarshallingPayloadEndpoint.
The method invokeInternal will be called when an XML request is received by the framework and the whole xml content will be available in the requestElement. The rest of the code does the job of finding the request string from the input XML, invoke the employee service and then constructs the appropriate XML response.

5.Configuring deployment descriptor :

The web application’s deployment descriptor must be configured with a servlet that is capable of dispatching web service message to the appropriate handler. This happens to be the MessageDispatcherServlet servlet.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>EmployeeWS</display-name>
  <servlet>
      <servlet-name>EmployeeWS</servlet-name>
      <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/spring/context/ApplicationContext.xml</param-value>
      </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>EmployeeWS</servlet-name>
    <url-pattern>/*</url-pattern>  
  </servlet-mapping>
</web-app>

In the above XML, we have routed all requests to the servlet spring-ws-service which in-turns maps to MessageDispatcherServlet. The above dispatcher servlet will search for a configuration file representing the spring application context for looking up the definition for various spring beans. By default, the name of the configuration file will be derived from the servlet name. If the name of the servlet is xyz, then the name of the configuration file will be xyz-servlet.xml. In our case, the configuration file will be spring-ws-servlet.xml. We can also give any name to the Spring Configuration File by just adding the following init-param to the MessageDispatcherServlet :

       <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/spring/context/ApplicationContext.xml</param-value>
      </init-param>

6.Configuring Spring’s Application Context :

The minimal requirement of the spring application configuration file that resides in a web server is to contain the following entries:
 i Endpoints definition
 ii Endpoint mappings definition
 iii WSDL Definition

spring-ws-servlet.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:oxm="http://www.springframework.org/schema/oxm"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-1.5.xsd">
    <!-- For Hand-Written contract(.wsdl) -->
    <bean id="EmployeeService"
        class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition">
        <constructor-arg value="/wsdl/Employee.wsdl" />
    </bean>
    <oxm:jaxb2-marshaller id="marshaller"
        contextPath="com.employee.schema" />
    <oxm:jaxb2-marshaller id="unmarshaller"
        contextPath="com.employee.schema" />
    <!-- Endpoint Mapping... -->
    <bean name="service" class="com.employee.service.EmployeeServiceImpl" />
    <bean id="employeeDetailsEndpoint" class="com.employee.endpoint.EmployeeDetailsEndpoint">
        <constructor-arg ref="service" />
        <constructor-arg ref="marshaller" />
    </bean>
    <bean name="endPointMapping"
        class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
        <property name="mappings">
            <props>
                <prop key="{http://employee.com/schema}EmployeeDetailsRequest">employeeDetailsEndpoint</prop>
            </props>
        </property>
    </bean>
</beans>

Now Deploy the application into tomcat server & hit the url to see the .wsdl:

http://<server-address>:<port>/EmployeeWS/services/EmployeeService.wsdl
OR
http://<server-address>:<port>/EmployeeWS/<MessageDispatcherServlet_name_from_deployment_descriptor>/<wsdl_bean_name_from_spring_app_context>.wsdl


B. Test service Using soapUI




Reference :