Wednesday, March 21, 2012

Spring WebService Tutorial

I tested this tutorial on following configuration
 JDK1.7
Tomcat 7.0
Maven-3.0.3


Folder structure
  • Integration-springWS
    • Properties
      • dev.properties
    • src
      • main
        • java
          • com
            • test
              • BasicEndpointCommand.java
              • EndpointPointCommand.java
              • NotificationEndpoint.java
              • ObjectFactory.java
              • UserRequestType.java
              • UserResponseType.java
        • resources
          • log4j.properties
        • webapp
          • WEB-INF
            • notification.xsd
            • psring-ws-servlet.xml
            • web.xml
          • index.htm
      • test
    • pom.xml
    • tomcat-deploy.sh
dev.properties

LOG_LEVEL=debug
LOG_FILE_DIR=springWS_log

BasicEndpointCommand.java



package com.test;
import java.util.Date;
import java.util.Map;
import org.apache.log4j.Logger;


/**
 * Description:
 * @author Sandeep
 */


public class BasicEndpointCommand implements EndpointPointCommand {


private static final Logger log = Logger.getLogger(BasicEndpointCommand.class);

@SuppressWarnings("unchecked")
@Override
public Object execute(Map info) throws Exception {
if (log.isDebugEnabled()) {
log.debug("TIME::" + new Date());
log.debug("INFO::" + info);
}
return null;
}
}



EndpointPointCommand.java



package com.test;
import java.util.Map;

/**
 * @author Sandeep
 */
public interface EndpointPointCommand {
@SuppressWarnings("unchecked")
public Object execute(Map info) throws Exception;
}

NotificationEndpoint.java




package com.test;




import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.xml.bind.JAXBElement;


import org.apache.log4j.Logger;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;


/**
 * @author Sandeep 
 */
@Endpoint
public class NotificationEndpoint {

public static final String KEY_USERID = "KEY_USERID";
public static final String KEY_USERNAME = "KEY_USERNAME";

private List commands;
private static final Logger log = Logger.getLogger(NotificationEndpoint.class);
@PayloadRoot(localPart = "userRequest", namespace = "http://www.stack-over-flow.blogspot.com/schema")
    public JAXBElement user(JAXBElement requestElement) throws Exception {

UserResponseType responseType = new UserResponseType();
UserRequestType request = requestElement.getValue();
try{
Map info = new HashMap();

info.put(KEY_USERID, request.getUserId());
info.put(KEY_USERNAME, request.getUserName());


log.debug("INFO ::"+info );

for(EndpointPointCommand command: commands){
command.execute(info);
}

}catch(Exception e){
responseType.setSuccessful(false);
responseType.setError(e.getMessage());
}

responseType.setSuccessful(true);
return new ObjectFactory().createUserResponse(responseType);
}


public List getCommands() {
return commands;
}


public void setCommands(List commands) {
this.commands = commands;
}
}


ObjectFactory.java




package com.test;


import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;




@XmlRegistry
public class ObjectFactory {


    private final static QName _UserResponse_QNAME = new QName("http://www.stack-over-flow.blogspot.com/schema", "userResponse");
    private final static QName _UserRequest_QNAME = new QName("http://www.stack-over-flow.blogspot.com/schema", "userRequest");


    public ObjectFactory() {
    }


    /**
     * Create an instance of {@link DaEventNotificationRequestType }
     * 
     */
    public UserRequestType createUserRequestType() {
        return new UserRequestType();
    }


    /**
     * Create an instance of {@link DaEventNotificationResponseType }
     * 
     */
    public UserResponseType createUserResponseType() {
        return new UserResponseType();
    }


    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link DaEventNotificationResponseType }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://www.stack-over-flow.blogspot.com/schema", name = "userResponse")
    public JAXBElement createUserResponse(UserResponseType value) {
        return new JAXBElement(_UserResponse_QNAME, UserResponseType.class, null, value);
    }


    /**
     * Create an instance of {@link JAXBElement }{@code <}{@link DaEventNotificationRequestType }{@code >}}
     * 
     */
    @XmlElementDecl(namespace = "http://www.stack-over-flow.blogspot.com/schema", name = "userRequest")
    public JAXBElement createUserRequest(UserRequestType value) {
        return new JAXBElement(_UserRequest_QNAME, UserRequestType.class, null, value);
    }


}



UserRequestType.java

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-833 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.03.06 at 09:16:46 AM GST 
//


package com.test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UserRequestType", propOrder = {

})
public class UserRequestType {

    protected int userId;
    @XmlElement(required = true)
    protected String userName;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int value) {
        this.userId = value;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String value) {
        this.userName = value;
    }
}

UserResponseType.java

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-833 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.03.06 at 09:16:46 AM GST 
//

package com.test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UserResponseType", propOrder = {

})
public class UserResponseType {
    protected boolean successful;
    protected String error;
    public boolean isSuccessful() {
        return successful;
    }
    public void setSuccessful(boolean value) {
        this.successful = value;
    }
    public String getError() {
        return error;
    }
    public void setError(String value) {
        this.error = value;
    }
}

log4j.properties

# Log4J logging properties

log4j.rootLogger=error, File

###### File appender definition #######
log4j.appender.File=org.apache.log4j.DailyRollingFileAppender
log4j.appender.File.File=integration-springws.log
log4j.appender.File.Append=true
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{3}] %m%n

# logger level
log4j.logger.org.apache.commons=warn
log4j.logger.org.apache.cxf=warn
log4j.logger.org.springframework=warn
log4j.logger.javax.xml.bind=warn

notification.xsd


<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified" attributeFormDefault="unqualified"
xmlns="http://www.stack-over-flow.blogspot.com/schema" targetNamespace="http://www.stack-over-flow.blogspot.com/schema">
<xs:element name="userRequest" type="UserRequestType" />
<xs:element name="userResponse" type="UserResponseType" />
<xs:complexType name="UserRequestType">
<xs:annotation>
<xs:documentation></xs:documentation>
</xs:annotation>
<xs:all>
<xs:element name="userId" type="xs:int" />
<xs:element name="userName" type="xs:string" />
</xs:all>
</xs:complexType>
<xs:complexType name="UserResponseType">
<xs:all>
<xs:element name="successful" type="xs:boolean" minOccurs="1" />
<xs:element name="error" type="xs:string" minOccurs="0" />
</xs:all>
</xs:complexType>
</xs:schema>


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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="notificationEndpoint" class="com.test.NotificationEndpoint">
        <property name="commands">
        <list>
        <ref local="basicCommand"/>
        </list>
        </property>
    </bean>
    <bean id="basicCommand" class="com.test.BasicEndpointCommand"/>
<bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping"/>
<bean class="org.springframework.ws.server.endpoint.adapter.GenericMarshallingMethodEndpointAdapter">
<constructor-arg ref="marshaller" />
</bean>
<bean id="notification" class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
    <property name="schema" ref="schema"/>
    <property name="portTypeName" value="UserNotification"/>
    <property name="locationUri" value="Integration-springws/spring-ws/notificationService"/>
    <property name="targetNamespace" value="http://www.stack-over-flow.blogspot.com/schema"/>
</bean>
<bean id="schema" class="org.springframework.xml.xsd.SimpleXsdSchema">
    <property name="xsd" value="/WEB-INF/notification.xsd"/>
</bean>
<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="contextPath" value="com.test" />
</bean>
</beans>


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>spring-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-ws</servlet-name>
        <url-pattern>/spring-ws/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
    <welcome-file>index.htm</welcome-file>
    </welcome-file-list>
</web-app>
Index.htm

<html>
<title>Spring WS Endpoint</title>
<head></head>
<body>
To see WSDL see following link<p>
<a href="spring-ws/notificationService/notification.wsdl">wsdl<a/>
<body>
</html>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Integration-springws-test</groupId>
<artifactId>Integration-springws</artifactId>
<version>1.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>notification-endpoint Spring-WS Application</name>
<url>http://www.springframework.org/spring-ws</url>
<build>
<finalName>Integration-springws</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<configuration>
<server>myserver</server>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Implementation-Build>${buildNumber}</Implementation-Build>
</manifestEntries>
</archive>
</configuration>
</plugin>
   </plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
<!-- <scope>test</scope> -->
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>2.5.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
    <groupId>commons-configuration</groupId>
    <artifactId>commons-configuration</artifactId>
    <version>1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>oracle</id>
<name>SpringSource Enterprise Bundle Repository - External Bundle Releases</name>
<url>http://www.mvnsearch.org/maven2/</url>
</repository> 
</repositories>
</project>
tomcat-deploy.sh

pid=`ps -aef | grep tomcat | grep -v grep | awk '{print $2}'`

if [ -n "$pid" ]; then 

  echo 'About to kill:' $pid

  kill -9 `ps -aef | grep tomcat | grep -v grep | awk '{print $2}'`
else
  echo 'No tomcat running.'
fi
rm -rf $TOMCAT_HOME/webapps/*Integration-springws*
cp ./target/Integration-springws.war $TOMCAT_HOME/webapps
$TOMCAT_HOME/bin/startup.sh

after this just open the browser and type following URL in the browser

http://localhost:8080/Integration-springws/

No comments:

Post a Comment