SWS-998 - Backport Maven/Asciidoctor migration to 2.x

This commit is contained in:
Greg Turnquist
2017-10-16 11:26:42 -05:00
parent 547a077625
commit 19a1209999
46 changed files with 5435 additions and 6818 deletions

BIN
.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

1
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

@@ -0,0 +1 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip

View File

@@ -1,14 +1,28 @@
version: 2
jobs:
build:
docker:
- image: circleci/openjdk:8u141
steps:
- checkout
- run: ./gradlew clean build
- run: ./gradlew -Pprofile=spring4-next clean build
build:
docker:
- image: circleci/openjdk:8u141
steps:
- checkout
- run:
name: Test current version
command: ./mvnw -Pdistribute,snapshot,docs clean test
- run:
name: Test Spring.NEXT
command: ./mvnw -Pspringnext clean test
- run:
name: Test Spring.NEXT snapshots
command: ./mvnw -Pspringnext-snapshot clean test
- run:
name: Deploy to Artifactory
command: ./deploy.bash
general:
branches:
ignore:
- gh-pages # list of branches to ignore
dependencies:
cache_directories:
- "~/.m2"

7
deploy.bash Executable file
View File

@@ -0,0 +1,7 @@
#!/bin/bash -x
if [ "${CIRCLE_BRANCH}" == "master" ] || [ "${CIRCLE_BRANCH}" == "2.x" ]; then
./mvnw -Pdistribute,snapshot,docs clean -Dmaven.test.skip=true deploy
else
echo "We only deploy 'master' and '2.x' branches"
fi

Binary file not shown.

View File

@@ -1,6 +0,0 @@
#Thu Oct 05 08:58:22 CDT 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.0.2-bin.zip

225
mvnw vendored Executable file
View File

@@ -0,0 +1,225 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
echo $MAVEN_PROJECTBASEDIR
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

143
mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,143 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

634
pom.xml Normal file
View File

@@ -0,0 +1,634 @@
<?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>org.springframework.ws</groupId>
<artifactId>spring-ws</artifactId>
<version>2.4.1.BUILD-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Spring Web Services</name>
<url>http://project.spring.io/spring-ws</url>
<developers>
<developer>
<id>apoutsma</id>
<name>Arjen Poutsma</name>
<email>apoutsma@pivotal.io</email>
<organization>Pivotal Software, Inc.</organization>
<roles>
<role>Project Creator</role>
</roles>
</developer>
<developer>
<id>tareqa</id>
<name>Tareq Abed Rabbo</name>
<email>tareq.abedrabbo@gmail.com</email>
<organization>Pivotal Software, Inc.</organization>
<roles>
<role>Developer</role>
</roles>
</developer>
<developer>
<id>gturnquist</id>
<name>Greg Turnquist</name>
<email>gturnquist@pivotal.io</email>
<organization>Pivotal Software, Inc.</organization>
<roles>
<role>Project Lead</role>
</roles>
</developer>
</developers>
<organization>
<name>Pivotal Software</name>
<url>http://spring.io</url>
</organization>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0</url>
<comments>
Copyright 2011 the original author or authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.
See the License for the specific language governing permissions and
limitations under the License.
</comments>
</license>
</licenses>
<modules>
<module>spring-ws-core</module>
<module>spring-ws-security</module>
<module>spring-ws-support</module>
<module>spring-ws-test</module>
<module>spring-xml</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<maven.javadoc.failOnError>false</maven.javadoc.failOnError>
<activemq.version>4.1.2</activemq.version>
<aspectj.version>1.6.12</aspectj.version>
<axiom.version>1.2.20</axiom.version>
<commons-httpclient.version>3.1</commons-httpclient.version>
<commons-logging.version>1.1.3</commons-logging.version>
<dom4j.version>1.6.1</dom4j.version>
<easymock.version>3.1</easymock.version>
<ehcache.version>2.8.9</ehcache.version>
<httpclient.version>4.3.6</httpclient.version>
<javax-mail.version>1.4.7</javax-mail.version>
<javax-servlet.version>3.0.1</javax-servlet.version>
<jaxen.version>1.1.6</jaxen.version>
<jdom2.version>2.0.6</jdom2.version>
<jetty.version>6.1.26</jetty.version>
<jms.version>1.1-rev-1</jms.version>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<mock-javamail.version>1.6</mock-javamail.version>
<saaj-impl.version>1.3.28</saaj-impl.version>
<smack.version>4.1.9</smack.version>
<spring.version>4.2.9.RELEASE</spring.version>
<spring-security.version>4.0.4.RELEASE</spring-security.version>
<sun-mail.version>1.5.4</sun-mail.version>
<woodstox.version>4.2.0</woodstox.version>
<wsdl4j.version>1.6.3</wsdl4j.version>
<wss4j.version>1.6.19</wss4j.version>
<wss4j2.version>2.2.0</wss4j2.version>
<xml-schema-core.version>2.1.0</xml-schema-core.version>
<xmlunit.version>1.5</xmlunit.version>
<xws-security.version>3.0</xws-security.version>
<xom.version>1.2.5</xom.version>
</properties>
<dependencies>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commons-logging.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>${easymock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>${xmlunit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>${sun-mail.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
<version>${woodstox.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>springnext</id>
<properties>
<spring.version>4.3.12.RELEASE</spring.version>
<spring-security.version>4.2.3.RELEASE</spring-security.version>
</properties>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-release</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</profile>
<profile>
<id>springnext-snapshot</id>
<properties>
<spring.version>4.3.13.BUILD-SNAPSHOT</spring.version>
<spring-security.version>4.2.4.BUILD-SNAPSHOT</spring-security.version>
</properties>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-release</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</profile>
<profile>
<id>distribute</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
<additionalparam>-quiet</additionalparam>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>gpg</id>
<properties>
<gpg.useagent>true</gpg.useagent>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifact</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>snapshot</id>
<build>
<plugins>
<plugin>
<groupId>org.jfrog.buildinfo</groupId>
<artifactId>artifactory-maven-plugin</artifactId>
<version>2.6.1</version>
<inherited>false</inherited>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>publish</goal>
</goals>
<configuration>
<deployProperties>
<archives>*:*:*:*@zip zip.name:spring-ws, zip.displayname:Spring Web Services, zip.deployed:false</archives>
</deployProperties>
<publisher>
<contextUrl>http://repo.spring.io</contextUrl>
<username>{{USERNAME}}</username>
<password>{{PASSWORD}}</password>
<repoKey>libs-snapshot-local</repoKey>
<snapshotRepoKey>libs-snapshot-local</snapshotRepoKey>
</publisher>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>milestone</id>
<build>
<plugins>
<plugin>
<groupId>org.jfrog.buildinfo</groupId>
<artifactId>artifactory-maven-plugin</artifactId>
<version>2.6.1</version>
<inherited>false</inherited>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>publish</goal>
</goals>
<configuration>
<deployProperties>
<archives>*:*:*:*@zip zip.name:spring-ws, zip.displayname:Spring Web Services, zip.deployed:false</archives>
</deployProperties>
<publisher>
<contextUrl>http://repo.spring.io</contextUrl>
<username>{{USERNAME}}</username>
<password>{{PASSWORD}}</password>
<repoKey>libs-milestone-local</repoKey>
<snapshotRepoKey>libs-snapshot-local</snapshotRepoKey>
</publisher>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>release</id>
<build>
<plugins>
<plugin>
<groupId>org.jfrog.buildinfo</groupId>
<artifactId>artifactory-maven-plugin</artifactId>
<version>2.6.1</version>
<inherited>false</inherited>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>publish</goal>
</goals>
<configuration>
<deployProperties>
<archives>*:*:*:*@zip zip.name:spring-ws, zip.displayname:Spring Web Services, zip.deployed:false</archives>
</deployProperties>
<publisher>
<contextUrl>http://repo.spring.io</contextUrl>
<username>{{USERNAME}}</username>
<password>{{PASSWORD}}</password>
<repoKey>libs-release-local</repoKey>
<snapshotRepoKey>libs-snapshot-local</snapshotRepoKey>
</publisher>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>docs</id>
<build>
<plugins>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.6</version>
<dependencies>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>1.5.0-alpha.15</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>html</id>
<phase>generate-resources</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html5</backend>
<outputDirectory>${project.build.directory}/site/reference/html</outputDirectory>
<sourceHighlighter>prettify</sourceHighlighter>
<attributes>
<icons>font</icons>
<sectanchors>true</sectanchors>
</attributes>
</configuration>
</execution>
<execution>
<id>pdf</id>
<phase>generate-resources</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>pdf</backend>
<sourceHighlighter>coderay</sourceHighlighter>
</configuration>
</execution>
</executions>
<configuration>
<sourceDirectory>src/main/asciidoctor</sourceDirectory>
<sourceDocumentName>index.adoc</sourceDocumentName>
<doctype>book</doctype>
<attributes>
<version>${project.version}</version>
<projectName>${project.name}</projectName>
<projectVersion>${project.version}</projectVersion>
<allow-uri-read>true</allow-uri-read>
<toclevels>3</toclevels>
<numbered>true</numbered>
<baseDir>${project.basedir}</baseDir>
</attributes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
<!--<additionalparam>-quiet</additionalparam>-->
</configuration>
<executions>
<execution>
<id>aggregate</id>
<goals>
<goal>aggregate-jar</goal>
</goals>
<phase>prepare-package</phase>
<inherited>false</inherited>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<dependencies>
<dependency>
<groupId>ant-contrib</groupId>
<artifactId>ant-contrib</artifactId>
<version>1.0b3</version>
<exclusions>
<exclusion>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-nodeps</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>org.tigris.antelope</groupId>
<artifactId>antelopetasks</artifactId>
<version>3.2.10</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>package-and-attach-docs-zip</id>
<goals>
<goal>run</goal>
</goals>
<phase>package</phase>
<inherited>false</inherited>
<configuration>
<tasks>
<zip destfile="${project.build.directory}/${project.artifactId}-${project.version}.zip">
<zipfileset src="${project.build.directory}/${project.artifactId}-${project.version}-javadoc.jar" prefix="api" />
<zipfileset dir="${project.build.directory}/site/reference/html" prefix="reference" />
<zipfileset dir="${project.build.directory}/generated-docs" includes="index.pdf" />
</zip>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.10</version>
<inherited>false</inherited>
<executions>
<execution>
<id>attach-zip</id>
<goals>
<goal>attach-artifact</goal>
</goals>
<configuration>
<artifacts>
<artifact>
<file>${project.build.directory}/${project.artifactId}-${project.version}.zip</file>
<type>zip;zip.type=docs;zip.deployed=false</type>
</artifact>
</artifacts>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>central</id>
<distributionManagement>
<snapshotRepository>
<id>sonatype-nexus-snapshots</id>
<name>Sonatype Nexus Snapshots</name>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</snapshotRepository>
<repository>
<id>sonatype-nexus-staging</id>
<name>Nexus Release Repository</name>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
</profile>
</profiles>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
</pluginRepository>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
<scm>
<url>https://github.com/spring-projects/spring-ws</url>
<connection>scm:git:git://github.com/spring-projects/spring-ws.git</connection>
<developerConnection>scm:git:ssh://git@github.com:spring-projects/spring-ws.git</developerConnection>
</scm>
</project>

19
settings.xml Normal file
View File

@@ -0,0 +1,19 @@
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<servers>
<server>
<id>sonatype-nexus-snapshots</id>
<username>${env.USERNAME}</username>
<password>${env.PASSWORD}</password>
</server>
<server>
<id>sonatype-nexus-staging</id>
<username>${env.USERNAME}</username>
<password>${env.PASSWORD}</password>
</server>
</servers>
</settings>

180
spring-ws-core/pom.xml Normal file
View File

@@ -0,0 +1,180 @@
<?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>
<parent>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws</artifactId>
<version>2.4.1.BUILD-SNAPSHOT</version>
</parent>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<packaging>jar</packaging>
<description>Spring WS Core</description>
<dependencies>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-xml</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!--// XML-->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>${jdom2.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>${dom4j.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>xom</groupId>
<artifactId>xom</artifactId>
<version>${xom.version}</version>
<optional>true</optional>
<exclusions>
<exclusion>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
</exclusion>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
<exclusion>
<groupId>xalan</groupId>
<artifactId>xalan</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.ws.xmlschema</groupId>
<artifactId>xmlschema-core</artifactId>
<version>${xml-schema-core.version}</version>
<optional>true</optional>
</dependency>
<!--// SOAP-->
<dependency>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId>
<version>${axiom.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-impl</artifactId>
<version>${axiom.version}</version>
<optional>true</optional>
<exclusions>
<exclusion>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>wstx-asl</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--// WSDL-->
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
<version>${wsdl4j.version}</version>
<optional>true</optional>
</dependency>
<!--// Transport-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax-servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>${commons-httpclient.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>${jetty.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.mortbay.jetty</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -42,7 +42,7 @@ public class ClientInterceptorAdapterTest {
@Test
public void handleTestAdapter() {
TestClientInterceptorAdapter interceptor = new TestClientInterceptorAdapter(new ArrayList<>());
TestClientInterceptorAdapter interceptor = new TestClientInterceptorAdapter(new ArrayList<String>());
Assert.assertFalse(interceptor.handleRequest(null));
Assert.assertFalse(interceptor.handleResponse(null));

View File

@@ -18,16 +18,15 @@ package org.springframework.ws.server.endpoint.mapping;
import java.lang.reflect.Method;
import java.util.Collections;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.Source;
import org.apache.commons.logging.LogFactory;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
@@ -47,6 +46,8 @@ import org.springframework.ws.soap.saaj.SaajSoapMessage;
import org.springframework.ws.soap.saaj.SaajSoapMessageFactory;
import org.springframework.ws.soap.server.SoapMessageDispatcher;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("payloadRootAnnotationMethodEndpointMapping.xml")
public class PayloadRootAnnotationMethodEndpointMappingTest {
@@ -80,20 +81,6 @@ public class PayloadRootAnnotationMethodEndpointMappingTest {
assertEquals("Invalid endpoint registered", expected, endpoint);
}
@Test
public void registrationRepeatable() throws NoSuchMethodException {
Method doItMultiple = MyEndpoint.class.getMethod("doItRepeatable");
MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doItMultiple);
MethodEndpoint endpoint = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request3"));
assertNotNull("MethodEndpoint not registered", endpoint);
assertEquals("Invalid endpoint registered", expected, endpoint);
endpoint = mapping.lookupEndpoint(new QName("http://springframework.org/spring-ws", "Request4"));
assertNotNull("MethodEndpoint not registered", endpoint);
assertEquals("Invalid endpoint registered", expected, endpoint);
}
@Test
public void registrationInvalid() {
assertNull("Invalid endpoint registered",
@@ -150,14 +137,6 @@ public class PayloadRootAnnotationMethodEndpointMappingTest {
public void doItMultiple() {
}
@PayloadRoot(localPart = "Request3",
namespace = "http://springframework.org/spring-ws")
@PayloadRoot(localPart = "Request4",
namespace = "http://springframework.org/spring-ws")
public void doItRepeatable() {
}
}
static class OtherBean {

View File

@@ -18,11 +18,9 @@ package org.springframework.ws.soap.server.endpoint.mapping;
import java.lang.reflect.Method;
import static org.easymock.EasyMock.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.context.DefaultMessageContext;
@@ -34,6 +32,8 @@ import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.soap.server.endpoint.annotation.SoapAction;
import org.springframework.ws.soap.server.endpoint.annotation.SoapActions;
import static org.easymock.EasyMock.*;
public class SoapActionAnnotationMethodEndpointMappingTest {
private SoapActionAnnotationMethodEndpointMapping mapping;
@@ -89,29 +89,6 @@ public class SoapActionAnnotationMethodEndpointMappingTest {
verify(requestMock, factoryMock);
}
@Test
public void registrationRepeatable() throws Exception {
SoapMessage requestMock = createMock(SoapMessage.class);
expect(requestMock.getSoapAction()).andReturn("http://springframework.org/spring-ws/SoapAction3");
expect(requestMock.getSoapAction()).andReturn("http://springframework.org/spring-ws/SoapAction4");
WebServiceMessageFactory factoryMock = createMock(WebServiceMessageFactory.class);
replay(requestMock, factoryMock);
Method doItRepeatable = MyEndpoint.class.getMethod("doItRepeatable");
MethodEndpoint expected = new MethodEndpoint("endpoint", applicationContext, doItRepeatable);
MessageContext context = new DefaultMessageContext(requestMock, factoryMock);
EndpointInvocationChain chain = mapping.getEndpoint(context);
Assert.assertNotNull("MethodEndpoint not registered", chain);
Assert.assertEquals("Invalid endpoint registered", expected, chain.getEndpoint());
chain = mapping.getEndpoint(context);
Assert.assertNotNull("MethodEndpoint not registered", chain);
Assert.assertEquals("Invalid endpoint registered", expected, chain.getEndpoint());
verify(requestMock, factoryMock);
}
@Endpoint
private static class MyEndpoint {
@@ -124,13 +101,6 @@ public class SoapActionAnnotationMethodEndpointMappingTest {
@SoapAction("http://springframework.org/spring-ws/SoapAction2")})
public void doItMultiple() {
}
@SoapAction("http://springframework.org/spring-ws/SoapAction3")
@SoapAction("http://springframework.org/spring-ws/SoapAction4")
public void doItRepeatable() {
}
}
}

123
spring-ws-security/pom.xml Normal file
View File

@@ -0,0 +1,123 @@
<?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>
<parent>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws</artifactId>
<version>2.4.1.BUILD-SNAPSHOT</version>
</parent>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
<packaging>jar</packaging>
<description>Spring WS Security</description>
<dependencies>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-xml</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>${project.parent.version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!--// Spring Security-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
</dependency>
<!--// WS-Security-->
<dependency>
<groupId>com.sun.xml.wss</groupId>
<artifactId>xws-security</artifactId>
<version>${xws-security.version}</version>
<optional>true</optional>
<exclusions>
<exclusion>
<groupId>javax.xml.crypto</groupId>
<artifactId>xmldsig</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.ws.security</groupId>
<artifactId>wss4j</artifactId>
<version>${wss4j.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.santuario</groupId>
<artifactId>xmlsec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.wss4j</groupId>
<artifactId>wss4j-ws-security-dom</artifactId>
<version>${wss4j2.version}</version>
</dependency>
<!--// SOAP-->
<dependency>
<groupId>com.sun.xml.messaging.saaj</groupId>
<artifactId>saaj-impl</artifactId>
<version>${saaj-impl.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId>
<version>${axiom.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-impl</artifactId>
<version>${axiom.version}</version>
<optional>true</optional>
<exclusions>
<exclusion>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>wstx-asl</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>

120
spring-ws-support/pom.xml Normal file
View File

@@ -0,0 +1,120 @@
<?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>
<parent>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws</artifactId>
<version>2.4.1.BUILD-SNAPSHOT</version>
</parent>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-support</artifactId>
<packaging>jar</packaging>
<description>Spring WS Support</description>
<dependencies>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-xml</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.jms</groupId>
<artifactId>jms-api</artifactId>
<version>${jms.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>${javax-mail.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>${sun-mail.version}</version>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack</groupId>
<artifactId>smack-tcp</artifactId>
<version>${smack.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack</groupId>
<artifactId>smack-java7</artifactId>
<version>${smack.version}</version>
<optional>true</optional>
</dependency>
<!--optional("org.igniterealtime.smack:smack-extensions:$smackVersion")-->
<dependency>
<groupId>org.igniterealtime.smack</groupId>
<artifactId>smack-extensions</artifactId>
<version>${smack.version}</version>
<optional>true</optional>
</dependency>
<!--testCompile("commons-httpclient:commons-httpclient:$commonsHttpclientVersion")-->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>${commons-httpclient.version}</version>
<scope>test</scope>
</dependency>
<!--testRuntime("org.apache.activemq:activemq-core:4.1.2") {-->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-core</artifactId>
<version>${activemq.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jms_1.1_spec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jvnet.mock-javamail</groupId>
<artifactId>mock-javamail</artifactId>
<version>${mock-javamail.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>

54
spring-ws-test/pom.xml Normal file
View File

@@ -0,0 +1,54 @@
<?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>
<parent>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws</artifactId>
<version>2.4.1.BUILD-SNAPSHOT</version>
</parent>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-test</artifactId>
<packaging>jar</packaging>
<description>Spring WS Test</description>
<dependencies>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-xml</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>${xmlunit.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

47
spring-xml/pom.xml Normal file
View File

@@ -0,0 +1,47 @@
<?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>
<parent>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws</artifactId>
<version>2.4.1.BUILD-SNAPSHOT</version>
</parent>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-xml</artifactId>
<packaging>jar</packaging>
<description>Spring XML</description>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.apache.ws.xmlschema</groupId>
<artifactId>xmlschema-core</artifactId>
<version>${xml-schema-core.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>${jaxen.version}</version>
<optional>true</optional>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,7 @@
[bibliography]
= Bibliography
- [[[waldo-94]]] Jim Waldo, Ann Wollrath, and Sam Kendall. _A Note on Distributed Computing_. Springer Verlag. 1994
- [[[alpine]]] Steve Loughran & Edmund Smith. _Rethinking the Java SOAP Stack_. May 17, 2005. (C) 2005 IEEE Telephone Laboratories, Inc.
- [[[effective-enterprise-java]]] Ted Neward. Scott Meyers. _Effective Enterprise Java_. Addison-Wesley. 2004
- [[[effective-xml]]] Elliotte Rusty Harold. Scott Meyers. _Effective XML_. Addison-Wesley. 2004

View File

@@ -0,0 +1,499 @@
[[client]]
= Using Spring Web Services on the Client
== Introduction
Spring-WS provides a client-side Web service API that allows for consistent, XML-driven access to Web services. It also caters for the use of marshallers and unmarshallers so that your service tier code can deal exclusively with Java objects.
The `org.springframework.ws.client.core` package provides the core functionality for using the client-side access API. It contains template classes that simplify the use of Web services, much like the core Spring `JdbcTemplate` does for JDBC. The design principle common to Spring template classes is to provide helper methods to perform common operations, and for more sophisticated usage, delegate to user implemented callback interfaces. The Web service template follows the same design. The classes offer various convenience methods for the sending and receiving of XML messages, marshalling objects to XML before sending, and allows for multiple transport options.
== Using the client-side API
[[client-web-service-template]]
=== `WebServiceTemplate`
The `WebServiceTemplate` is the core class for client-side Web service access in Spring-WS. It contains methods for sending `Source` objects, and receiving response messages as either `Source` or `Result`. Additionally, it can marshal objects to XML before sending them across a transport, and unmarshal any response XML into an object again.
[[client-transports]]
==== URIs and Transports
The `WebServiceTemplate` class uses an URI as the message destination. You can either set a `defaultUri` property on the template itself, or supply an URI explicitly when calling a method on the template. The URI will be resolved into a `WebServiceMessageSender`, which is responsible for sending the XML message across a transport layer. You can set one or more message senders using the `messageSender` or `messageSenders` properties of the `WebServiceTemplate` class.
===== HTTP transports
There are two implementations of the `WebServiceMessageSender` interface for sending messages via HTTP. The default implementation is the `HttpUrlConnectionMessageSender`, which uses the facilities provided by Java itself. The alternative is the `HttpComponentsMessageSender`, which uses the https://hc.apache.org/httpcomponents-client-ga[Apache HttpComponents HttpClient]. Use the latter if you need more advanced and easy-to-use functionality (such as authentication, HTTP connection pooling, and so forth).
To use the HTTP transport, either set the `defaultUri` to something like `http://example.com/services`, or supply the *uri* parameter for one of the methods.
The following example shows how the default configuration can be used for HTTP transports:
[source,xml]
----
<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="defaultUri" value="http://example.com/WebService"/>
</bean>
</beans>
----
The following example shows how override the default configuration, and to use Apache HttpClient to authenticate using HTTP authentication:
[source,xml]
----
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
<property name="credentials">
<bean class="org.apache.http.auth.UsernamePasswordCredentials">
<constructor-arg value="john:secret"/>
</bean>
</property>
</bean>
</property>
<property name="defaultUri" value="http://example.com/WebService"/>
</bean>
----
===== JMS transport
For sending messages over JMS, Spring Web Services provides the `JmsMessageSender`. This class uses the facilities of the Spring framework to transform the `WebServiceMessage` into a JMS `Message`, send it on its way on a `Queue` or `Topic`, and receive a response (if any).
To use the `JmsMessageSender`, you need to set the `defaultUri` or *uri* parameter to a JMS URI, which - at a minimum - consists of the `jms:` prefix and a destination name. Some examples of JMS URIs are: `jms:SomeQueue`, `jms:SomeTopic?priority=3&deliveryMode=NON_PERSISTENT`, and `jms:RequestQueue?replyToName=ResponseName`. For more information on this URI syntax, refer to the class level Javadoc of the `JmsMessageSender`.
By default, the `JmsMessageSender` send JMS `BytesMessage`, but this can be overriden to use `TextMessages` by using the `messageType` parameter on the JMS URI. For example: `jms:Queue?messageType=TEXT_MESSAGE`. Note that `BytesMessages` are the preferred type, because `TextMessages` do not support attachments and character encodings reliably.
The following example shows how to use the JMS transport in combination with an ActiveMQ connection factory:
[source,xml]
----
<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost?broker.persistent=false"/>
</bean>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.jms.JmsMessageSender">
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
</property>
<property name="defaultUri" value="jms:RequestQueue?deliveryMode=NON_PERSISTENT"/>
</bean>
</beans>
----
===== Email transport
Spring Web Services also provides an email transport, which can be used to send web service messages via SMTP, and retrieve them via either POP3 or IMAP. The client-side email functionality is contained in the `MailMessageSender` class. This class creates an email message from the request `WebServiceMessage`, and sends it via SMTP. It then waits for a response message to arrive in the incoming POP3 or IMAP server.
To use the `MailMessageSender`, set the `defaultUri` or *uri* parameter to a `mailto` URI. Here are some URI examples: `mailto:john@example.com`, and `mailto:server@localhost?subject=SOAP%20Test`. Make sure that the message sender is properly configured with a `transportUri`, which indicates the server to use for sending requests (typically a SMTP server), and a `storeUri`, which indicates the server to poll for responses (typically a POP3 or IMAP server).
The following example shows how to use the email transport:
[source,xml]
----
<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.mail.MailMessageSender">
<property name="from" value="Spring-WS SOAP Client &lt;client@example.com&gt;"/>
<property name="transportUri" value="smtp://client:s04p@smtp.example.com"/>
<property name="storeUri" value="imap://client:s04p@imap.example.com/INBOX"/>
</bean>
</property>
<property name="defaultUri" value="mailto:server@example.com?subject=SOAP%20Test"/>
</bean>
</beans>
----
===== XMPP transport
Spring Web Services 2.0 introduced an XMPP (Jabber) transport, which can be used to send and receive web service messages via XMPP. The client-side XMPP functionality is contained in the `XmppMessageSender` class. This class creates an XMPP message from the request `WebServiceMessage`, and sends it via XMPP. It then listens for a response message to arrive.
To use the `XmppMessageSender`, set the `defaultUri` or *uri* parameter to a `xmpp` URI, for example `xmpp:johndoe@jabber.org`. The sender also requires an `XMPPConnection` to work, which can be conveniently created using the `org.springframework.ws.transport.xmpp.support.XmppConnectionFactoryBean`.
The following example shows how to use the xmpp transport:
[source,xml]
----
<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="connection" class="org.springframework.ws.transport.xmpp.support.XmppConnectionFactoryBean">
<property name="host" value="jabber.org"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
</bean>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.xmpp.XmppMessageSender">
<property name="connection" ref="connection"/>
</bean>
</property>
<property name="defaultUri" value="xmpp:user@jabber.org"/>
</bean>
</beans>
----
==== Message factories
In addition to a message sender, the `WebServiceTemplate` requires a Web service message factory. There are two message factories for SOAP: `SaajSoapMessageFactory` and `AxiomSoapMessageFactory`. If no message factory is specified (via the `messageFactory` property), Spring-WS will use the `SaajSoapMessageFactory` by default.
=== Sending and receiving a `WebServiceMessage`
The `WebServiceTemplate` contains many convenience methods to send and receive web service messages. There are methods that accept and return a `Source` and those that return a `Result`. Additionally, there are methods which marshal and unmarshal objects to XML. Here is an example that sends a simple XML message to a Web service.
[source,xml,subs="verbatim,quotes"]
----
import java.io.StringReader;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.transport.WebServiceMessageSender;
public class WebServiceClient {
private static final String MESSAGE =
"<message xmlns=\"http://tempuri.org\">Hello Web Service World</message>";
private final WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
public void setDefaultUri(String defaultUri) {
webServiceTemplate.setDefaultUri(defaultUri);
}
_// send to the configured default URI_
public void simpleSendAndReceive() {
StreamSource source = new StreamSource(new StringReader(MESSAGE));
StreamResult result = new StreamResult(System.out);
webServiceTemplate.sendSourceAndReceiveToResult(source, result);
}
_// send to an explicit URI_
public void customSendAndReceive() {
StreamSource source = new StreamSource(new StringReader(MESSAGE));
StreamResult result = new StreamResult(System.out);
webServiceTemplate.sendSourceAndReceiveToResult("http://localhost:8080/AnotherWebService",
source, result);
}
}
----
[source,xml]
----
<beans xmlns="http://www.springframework.org/schema/beans">
<bean id="webServiceClient" class="WebServiceClient">
<property name="defaultUri" value="http://localhost:8080/WebService"/>
</bean>
</beans>
----
The above example uses the `WebServiceTemplate` to send a hello world message to the web service located at `http://localhost:8080/WebService` (in the case of the `simpleSendAndReceive()` method), and writes the result to the console. The `WebServiceTemplate` is injected with the default URI, which is used because no URI was supplied explicitly in the Java code.
Please note that the `WebServiceTemplate` class is thread-safe once configured (assuming that all of it's dependencies are thread-safe too, which is the case for all of the dependencies that ship with Spring-WS), and so multiple objects can use the same shared `WebServiceTemplate` instance if so desired. The `WebServiceTemplate` exposes a zero argument constructor and `messageFactory`/`messageSender` bean properties which can be used for constructing the instance (using a Spring container or plain Java code). Alternatively, consider deriving from Spring-WS's `WebServiceGatewaySupport` convenience base class, which exposes convenient bean properties to enable easy configuration. (You do *not* have to extend this base class... it is provided as a convenience class only.)
=== Sending and receiving POJOs - marshalling and unmarshalling
In order to facilitate the sending of plain Java objects, the `WebServiceTemplate` has a number of `send(..)` methods that take an `Object` as an argument for a message's data content. The method `marshalSendAndReceive(..)` in the `WebServiceTemplate` class delegates the conversion of the request object to XML to a `Marshaller`, and the conversion of the response XML to an object to an `Unmarshaller`. (For more information about marshalling and unmarshaller, refer to http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/oxm.html[the Spring documentation].) By using the marshallers, your application code can focus on the business object that is being sent or received and not be concerned with the details of how it is represented as XML. In order to use the marshalling functionality, you have to set a marshaller and unmarshaller with the `marshaller`/`unmarshaller` properties of the `WebServiceTemplate` class.
=== `WebServiceMessageCallback`
To accommodate the setting of SOAP headers and other settings on the message, the `WebServiceMessageCallback` interface gives you access to the message *after* it has been created, but *before* it is sent. The example below demonstrates how to set the SOAP Action header on a message that is created by marshalling an object.
[source,java]
----
public void marshalWithSoapActionHeader(MyObject o) {
webServiceTemplate.marshalSendAndReceive(o, new WebServiceMessageCallback() {
public void doWithMessage(WebServiceMessage message) {
((SoapMessage)message).setSoapAction("http://tempuri.org/Action");
}
});
}
----
NOTE: Note that you can also use the `org.springframework.ws.soap.client.core.SoapActionCallback` to set the SOAP Action header.
==== WS-Addressing
In addition to the <<server-ws-addressing,server-side WS-Addressing>> support, Spring Web Services also has support for this specification on the client-side.
For setting WS-Addressing headers on the client, you can use the `org.springframework.ws.soap.addressing.client.ActionCallback`. This callback takes the desired Action header as a parameter. It also has constructors for specifying the WS-Addressing version, and a `To` header. If not specified, the `To` header will default to the URL of the connection being made.
Here is an example of setting the `Action` header to `http://samples/RequestOrder`:
[source,java]
----
webServiceTemplate.marshalSendAndReceive(o, new ActionCallback("http://samples/RequestOrder"));
----
=== `WebServiceMessageExtractor`
The `WebServiceMessageExtractor` interface is a low-level callback interface that allows you to have full control over the process to extract an `Object` from a received `WebServiceMessage`. The `WebServiceTemplate` will invoke the `extractData(..)` method on a supplied `WebServiceMessageExtractor` *while the underlying connection to the serving resource is still open*. The following example illustrates the `WebServiceMessageExtractor` in action:
[source,java,subs="verbatim,quotes"]
----
public void marshalWithSoapActionHeader(final Source s) {
final Transformer transformer = transformerFactory.newTransformer();
webServiceTemplate.sendAndReceive(new WebServiceMessageCallback() {
public void doWithMessage(WebServiceMessage message) {
transformer.transform(s, message.getPayloadResult());
},
new WebServiceMessageExtractor() {
public Object extractData(WebServiceMessage message) throws IOException
_// do your own transforms with message.getPayloadResult()
// or message.getPayloadSource()_
}
});
}
----
== Client-side testing
When it comes to testing your Web service clients (i.e. classes that uses the `WebServiceTemplate` to access a Web service), there are two possible approaches:
* Write *Unit Tests*, which simply mock away the `WebServiceTemplate` class, `WebServiceOperations` interface, or the complete client class.
+
The advantage of this approach is that it's quite easy to accomplish; the disadvantage is that you are not really testing the exact content of the XML messages that are sent over the wire, especially when mocking out the entire client class.
+
* Write *Integrations Tests*, which do test the contents of the message.
The first approach can easily be accomplished with mocking frameworks such as EasyMock, JMock, etc. The next section will focus on writing integration tests, using the test features introduced in Spring Web Services 2.0.
=== Writing client-side integration tests
Spring Web Services 2.0 introduced support for creating Web service client integration tests. In this context, a client is a class that uses the `WebServiceTemplate` to access a Web service.
The integration test support lives in the `org.springframework.ws.test.client` package. The core class in that package is the `MockWebServiceServer`. The underlying idea is that the web service template connects to this mock server, sends it request message, which the mock server then verifies against the registered expectations. If the expectations are met, the mock server then prepares a response message, which is send back to the template.
The typical usage of the `MockWebServiceServer` is: .
. Create a `MockWebServiceServer` instance by calling `MockWebServiceServer.createServer(WebServiceTemplate)`, `MockWebServiceServer.createServer(WebServiceGatewaySupport)`, or `MockWebServiceServer.createServer(ApplicationContext)`.
. Set up request expectations by calling `expect(RequestMatcher)`, possibly by using the default `RequestMatcher` implementations provided in `RequestMatchers` (which can be statically imported). Multiple expectations can be set up by chaining `andExpect(RequestMatcher)` calls.
. Create an appropriate response message by calling `andRespond(ResponseCreator)`, possibly by using the default `ResponseCreator` implementations provided in `ResponseCreators` (which can be statically imported).
. Use the `WebServiceTemplate` as normal, either directly of through client code.
. Call `MockWebServiceServer.verify()` to make sure that all expectations have been met.
NOTE: Note that the `MockWebServiceServer` (and related classes) offers a 'fluent' API, so you can typically use the Code Completion features (i.e. ctrl-space) in your IDE to guide you through the process of setting up the mock server.
NOTE: Also note that you rely on the standard logging features available in Spring Web Services in your unit tests. Sometimes it might be useful to inspect the request or response message to find out why a particular tests failed. See <<logging>> for more information.
Consider, for example, this Web service client class:
[source,java]
----
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
public class CustomerClient extends WebServiceGatewaySupport { //<1>
public int getCustomerCount() {
CustomerCountRequest request = new CustomerCountRequest(); //<2>
request.setCustomerName("John Doe");
CustomerCountResponse response =
(CustomerCountResponse) getWebServiceTemplate().marshalSendAndReceive(request); //<3>
return response.getCustomerCount();
}
}
----
<1> The `CustomerClient` extends `WebServiceGatewaySupport`, which provides it with a webServiceTemplate property.
<2> `CustomerCountRequest` is an object supported by a marshaller. For instance, it can have a `@XmlRootElement` annotation to be supported by JAXB2.
<3> The `CustomerClient` uses the `WebServiceTemplate` offered by `WebServiceGatewaySupport` to marshal the request object into a SOAP message, and sends that to the web service. The response object is unmarshalled into a `CustomerCountResponse`.
A typical test for `CustomerClient` would look like this:
[source,java]
----
import javax.xml.transform.Source;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.xml.transform.StringSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import org.springframework.ws.test.client.MockWebServiceServer; //<1>
import static org.springframework.ws.test.client.RequestMatchers.*; //<1>
import static org.springframework.ws.test.client.ResponseCreators.*; //<1>
@RunWith(SpringJUnit4ClassRunner.class) //<2>
@ContextConfiguration("integration-test.xml") //<2>
public class CustomerClientIntegrationTest {
@Autowired
private CustomerClient client; //<3>
private MockWebServiceServer mockServer; //<4>
@Before
public void createServer() throws Exception {
mockServer = MockWebServiceServer.createServer(client);
}
@Test
public void customerClient() throws Exception {
Source requestPayload = new StringSource(
"<customerCountRequest xmlns='http://springframework.org/spring-ws'>" +
"<customerName>John Doe</customerName>" +
"</customerCountRequest>");
Source responsePayload = new StringSource(
"<customerCountResponse xmlns='http://springframework.org/spring-ws'>" +
"<customerCount>10</customerCount>" +
"</customerCountResponse>");
mockServer.expect(payload(requestPayload)).andRespond(withPayload(responsePayload));//<5>
int result = client.getCustomerCount(); //<6>
assertEquals(10, result); //<6>
mockServer.verify(); //<7>
}
}
----
<1> The `CustomerClientIntegrationTest` imports the `MockWebServiceServer`, and statically imports `RequestMatchers` and `ResponseCreators`.
<2> This test uses the standard testing facilities provided in the Spring Framework. This is not required, but is generally the easiest way to set up the test.
<3> The `CustomerClient` is configured in `integration-test.xml`, and wired into this test using `@Autowired`.
<4> In a `@Before` method, we create a `MockWebServiceServer` by using the `createServer` factory method.
<5> We define expectations by calling `expect()` with a `payload()` `RequestMatcher` provided by the statically imported `RequestMatchers` (see <<client-test-request-matcher>>).
+
We also set up a response by calling `andRespond()` with a `withPayload()` `ResponseCreator` provided by the statically imported `ResponseCreators` (see <<client-test-response-creator>>).
+
This part of the test might look a bit confusing, but the Code Completion features of your IDE are of great help. After typing `expect(`, simply type ctrl-space, and your IDE will provide you with a list of possible request matching strategies, provided you statically imported `RequestMatchers`. The same applies to `andRespond(`, provided you statically imported `ResponseCreators`.
<6> We call `getCustomerCount()` on the `CustomerClient`, thus using the `WebServiceTemplate`. The template has been set up for 'testing mode' by now, so no real (HTTP) connection is made by this method call. We also make some JUnit assertions based on the result of the method call.
<7> We call `verify()` on the `MockWebServiceServer`, thus verifying that the expected message was actually received.
[[client-test-request-matcher]]
=== `RequestMatcher` and `RequestMatchers`
To verify whether the request message meets certain expectations, the `MockWebServiceServer` uses the `RequestMatcher` strategy interface. The contract defined by this interface is quite simple:
[source,java]
----
public interface RequestMatcher {
void match(URI uri,
WebServiceMessage request)
throws IOException,
AssertionError;
}
----
You can write your own implementations of this interface, throwing `AssertionError`s when the message does not meet your expectations, but you certainly do not have to. The `RequestMatchers` class provides standard `RequestMatcher` implementations for you to use in your tests. You will typically statically import this class.
The `RequestMatchers` class provides the following request matchers:
[cols="2", options="header"]
|===
| `RequestMatchers` method
| Description
| `anything()`
| Expects any sort of request.
| `payload()`
| Expects a given request payload.
| `validPayload()`
| Expects the request payload to validate against given XSD schema(s).
| `xpath()`
| Expects a given XPath expression to exist, not exist, or evaluate to a given value.
| `soapHeader()`
| Expects a given SOAP header to exist in the request message.
| `connectionTo()`
| Expects a connection to the given URL.
|===
You can set up multiple request expectations by chaining `andExpect()` calls, like so:
[source,java]
----
mockServer.expect(connectionTo("http://example.com")).
andExpect(payload(expectedRequestPayload)).
andExpect(validPayload(schemaResource)).
andRespond(...);
----
For more information on the request matchers provided by `RequestMatchers`, refer to the class level Javadoc.
[[client-test-response-creator]]
=== `ResponseCreator` and `ResponseCreators`
When the request message has been verified and meets the defined expectations, the `MockWebServiceServer` will create a response message for the `WebServiceTemplate` to consume. The server uses the `ResponseCreator` strategy interface for this purpose:
[source,java]
----
public interface ResponseCreator {
WebServiceMessage createResponse(URI uri,
WebServiceMessage request,
WebServiceMessageFactory messageFactory)
throws IOException;
}
----
Once again you can write your own implementations of this interface, creating a response message by using the message factory, but you certainly do not have to, as the `ResponseCreators` class provides standard `ResponseCreator` implementations for you to use in your tests. You will typically statically import this class.
The `ResponseCreators` class provides the following responses:
[cols="2", options="header"]
|===
| `ResponseCreators` method
| Description
| `withPayload()`
| Creates a response message with a given payload.
| `withError()`
| Creates an error in the response connection. This method gives you the opportunity to test your error handling.
| `withException()`
| Throws an exception when reading from the response connection. This method gives you the opportunity to test your exception handling.
| `withMustUnderstandFault()`, `withClientOrSenderFault()`, `withServerOrReceiverFault()`, and `withVersionMismatchFault()`
| Creates a response message with a given SOAP fault. This method gives you the opportunity to test your Fault handling.
|===
For more information on the request matchers provided by `RequestMatchers`, refer to the class level Javadoc.

View File

@@ -0,0 +1,301 @@
:toclevels: 10
[[common]]
= Shared components
In this chapter, we will explore the components which are shared between client- and server-side Spring-WS development. These interfaces and classes represent the building blocks of Spring-WS, so it is important to understand what they do, even if you do not use them directly.
[[web-service-messages]]
== Web service messages
[[web-service-message]]
=== `WebServiceMessage`
One of the core interfaces of Spring Web Services is the `WebServiceMessage`. This interface represents a protocol-agnostic XML message. The interface contains methods that provide access to the payload of the message, in the form of a `javax.xml.transform.Source` or a `javax.xml.transform.Result`. `Source` and `Result` are tagging interfaces that represent an abstraction over XML input and output. Concrete implementations wrap various XML representations, as indicated in the following table.
[cols="2", options="header"]
|===
| Source/Result implementation
| Wraps XML representation
| `javax.xml.transform.dom.DOMSource`
| `org.w3c.dom.Node`
| `javax.xml.transform.dom.DOMResult`
| `org.w3c.dom.Node`
| `javax.xml.transform.sax.SAXSource`
| `org.xml.sax.InputSource` and `org.xml.sax.XMLReader`
| `javax.xml.transform.sax.SAXResult`
| `org.xml.sax.ContentHandler`
| `javax.xml.transform.stream.StreamSource`
| `java.io.File`, `java.io.InputStream`, or `java.io.Reader`
| `javax.xml.transform.stream.StreamResult`
| `java.io.File`, `java.io.OutputStream`, or `java.io.Writer`
|===
In addition to reading from and writing to the payload, a Web service message can write itself to an output stream.
[[soap-message]]
=== `SoapMessage`
The `SoapMessage` is a subclass of `WebServiceMessage`. It contains SOAP-specific methods, such as getting SOAP Headers, SOAP Faults, etc. Generally, your code should not be dependent on `SoapMessage`, because the content of the SOAP Body (the payload of the message) can be obtained via `getPayloadSource()` and `getPayloadResult()` in the `WebServiceMessage`. Only when it is necessary to perform SOAP-specific actions, such as adding a header, getting an attachment, etc., should you need to cast `WebServiceMessage` to `SoapMessage`.
[[message-factories]]
=== Message Factories
Concrete message implementations are created by a `WebServiceMessageFactory`. This factory can create an empty message, or read a message based on an input stream. There are two concrete implementations of `WebServiceMessageFactory`; one is based on SAAJ, the SOAP with Attachments API for Java, the other based on Axis 2's AXIOM, the AXis Object Model.
==== `SaajSoapMessageFactory`
The `SaajSoapMessageFactory` uses the SOAP with Attachments API for Java to create `SoapMessage` implementations. *SAAJ* is part of *J2EE* 1.4, so it should be supported under most modern application servers. Here is an overview of the *SAAJ* versions supplied by common application servers:
[cols="2", options="header"]
|===
| Application Server
| *SAAJ* Version
| BEA WebLogic 8
| 1.1
| BEA WebLogic 9
| 1.1/1.2^1^
| IBM WebSphere 6
| 1.2
| SUN Glassfish 1
| 1.3
2+|^1^Weblogic 9 has a known bug in the *SAAJ* 1.2 implementation: it implement all the 1.2 interfaces, but throws a `UnsupportedOperationException` when called. Spring Web Services has a workaround: it uses *SAAJ* 1.1 when operating on WebLogic 9.
|===
Additionally, Java SE 6 includes *SAAJ* 1.3. You wire up a `SaajSoapMessageFactory` like so:
[source,xml]
----
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory" />
----
NOTE: *SAAJ* is based on DOM, the Document Object Model. This means that all SOAP messages are stored *in memory*. For larger SOAP messages, this may not be very performant. In that case, the `AxiomSoapMessageFactory` might be more applicable.
==== `AxiomSoapMessageFactory`
The `AxiomSoapMessageFactory` uses the AXis 2 Object Model to create `SoapMessage` implementations. *AXIOM* is based on *StAX*, the Streaming API for XML. StAX provides a pull-based mechanism for reading XML messages, which can be more efficient for larger messages.
To increase reading performance on the `AxiomSoapMessageFactory`, you can set the `payloadCaching` property to false (default is true). This will read the contents of the SOAP body directly from the socket stream. When this setting is enabled, the payload can only be read once. This means that you have to make sure that any pre-processing (logging etc.) of the message does not consume it.
You use the `AxiomSoapMessageFactory` as follows:
[source,xml]
----
<bean id="messageFactory" class="org.springframework.ws.soap.axiom.AxiomSoapMessageFactory">
<property name="payloadCaching" value="true"/>
</bean>
----
In addition to payload caching, *AXIOM* also supports full streaming messages, as defined in the `StreamingWebServiceMessage`. This means that the payload can be directly set on the response message, rather than being written to a DOM tree or buffer.
Full streaming for *AXIOM* is used when a handler method returns a *JAXB2*-supported object. It will automatically set this marshalled object into the response message, and write it out to the outgoing socket stream when the response is going out.
For more information about full streaming, refer to the class-level Javadoc for `StreamingWebServiceMessage` and `StreamingPayload`.
[[soap_11_or_12]]
==== *SOAP* 1.1 or 1.2
Both the `SaajSoapMessageFactory` and the `AxiomSoapMessageFactory` have a `soapVersion` property, where you can inject a `SoapVersion` constant. By default, the version is 1.1, but you can set it to 1.2 like so:
[source,xml]
----
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<property name="soapVersion">
<util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_12"/>
</property>
</bean>
</beans>
----
In the example above, we define a `SaajSoapMessageFactory` that only accepts *SOAP* 1.2 messages.
[WARNING]
====
Even though both versions of *SOAP* are quite similar in format, the 1.2 version is not backwards compatible with 1.1 because it uses a different XML namespace. Other major differences between *SOAP* 1.1 and 1.2 include the different structure of a Fault, and the fact that `SOAPAction` HTTP headers are effectively deprecated, thought they still work.
One important thing to note with *SOAP* version numbers, or WS-* specification version numbers in general, is that the latest version of a specification is generally not the most popular version. For *SOAP*, this means that currently, the best version to use is 1.1. Version 1.2 might become more popular in the future, but currently 1.1 is the safest bet.
====
[[message-context]]
=== `MessageContext`
Typically, messages come in pairs: a request and a response. A request is created on the client-side, which is sent over some transport to the server-side, where a response is generated. This response gets sent back to the client, where it is read.
In Spring Web Services, such a conversation is contained in a `MessageContext`, which has properties to get request and response messages. On the client-side, the message context is created by the <<client-web-service-template,`WebServiceTemplate`>>. On the server-side, the message context is read from the transport-specific input stream. For example, in HTTP, it is read from the `HttpServletRequest` and the response is written back to the `HttpServletResponse`.
[[transport-context]]
== `TransportContext`
One of the key properties of the SOAP protocol is that it tries to be transport-agnostic. This is why, for instance, Spring-WS does not support mapping messages to endpoints by HTTP request URL, but rather by mesage content.
However, sometimes it is necessary to get access to the underlying transport, either on the client or server side. For this, Spring Web Services has the `TransportContext`. The transport context allows access to the underlying `WebServiceConnection`, which typically is a `HttpServletConnection` on the server side; or a `HttpUrlConnection` or `CommonsHttpConnection` on the client side. For example, you can obtain the IP address of the current request in a server-side endpoint or interceptor like so:
[source,java]
----
TransportContext context = TransportContextHolder.getTransportContext();
HttpServletConnection connection = (HttpServletConnection )context.getConnection();
HttpServletRequest request = connection.getHttpServletRequest();
String ipAddress = request.getRemoteAddr();
----
[[xpath]]
== Handling XML With XPath
One of the best ways to handle XML is to use XPath. Quoting <<effective-xml>>, item 35:
[quote, Elliotte Rusty Harold]
XPath is a fourth generation declarative language that allows you to specify which nodes you want to process without specifying exactly how the processor is supposed to navigate to those nodes. XPath's data model is very well designed to support exactly what almost all developers want from XML. For instance, it merges all adjacent text including that in CDATA sections, allows values to be calculated that skip over comments and processing instructions` and include text from child and descendant elements, and requires all external entity references to be resolved. In practice, XPath expressions tend to be much more robust against unexpected but perhaps insignificant changes in the input document.
Spring Web Services has two ways to use XPath within your application: the faster `XPathExpression` or the more flexible `XPathTemplate`.
[[xpath-expression]]
=== `XPathExpression`
The `XPathExpression` is an abstraction over a compiled XPath expression, such as the Java 5 `javax.xml.xpath.XPathExpression`, or the Jaxen `XPath` class. To construct an expression in an application context, there is the `XPathExpressionFactoryBean`. Here is an example which uses this factory bean:
[source,xml]
----
<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="nameExpression" class="org.springframework.xml.xpath.XPathExpressionFactoryBean">
<property name="expression" value="/Contacts/Contact/Name"/>
</bean>
<bean id="myEndpoint" class="sample.MyXPathClass">
<constructor-arg ref="nameExpression"/>
</bean>
</beans>
----
The expression above does not use namespaces, but we could set those using the `namespaces` property of the factory bean. The expression can be used in the code as follows:
[source,java]
----
package sample;
public class MyXPathClass {
private final XPathExpression nameExpression;
public MyXPathClass(XPathExpression nameExpression) {
this.nameExpression = nameExpression;
}
public void doXPath(Document document) {
String name = nameExpression.evaluateAsString(document.getDocumentElement());
System.out.println("Name: " + name);
}
}
----
For a more flexible approach, you can use a `NodeMapper`, which is similar to the `RowMapper` in Spring's JDBC support. The following example shows how we can use it:
[source,java]
----
package sample;
public class MyXPathClass {
private final XPathExpression contactExpression;
public MyXPathClass(XPathExpression contactExpression) {
this.contactExpression = contactExpression;
}
public void doXPath(Document document) {
List contacts = contactExpression.evaluate(document,
new NodeMapper() {
public Object mapNode(Node node, int nodeNum) throws DOMException {
Element contactElement = (Element) node;
Element nameElement = (Element) contactElement.getElementsByTagName("Name").item(0);
Element phoneElement = (Element) contactElement.getElementsByTagName("Phone").item(0);
return new Contact(nameElement.getTextContent(), phoneElement.getTextContent());
}
});
PlainText Section qName:lineannotation level:5, chunks:[// do something with list of Contact objects] attrs:[:]
}
}
----
Similar to mapping rows in Spring JDBC's `RowMapper`, each result node is mapped using an anonymous inner class. In this case, we create a `Contact` object, which we use later on.
[[xpath-template]]
=== `XPathTemplate`
The `XPathExpression` only allows you to evaluate a single, pre-compiled expression. A more flexible, though slower, alternative is the `XpathTemplate`. This class follows the common template pattern used throughout Spring (JdbcTemplate, JmsTemplate, etc.). Here is an example:
[source,java,subs="verbatim,quotes"]
----
package sample;
public class MyXPathClass {
private XPathOperations template = new Jaxp13XPathTemplate();
public void doXPath(Source source) {
String name = template.evaluateAsString("/Contacts/Contact/Name", request);
_// do something with name_
}
}
----
[[logging]]
== Message Logging and Tracing
When developing or debugging a Web service, it can be quite useful to look at the content of a (SOAP) message when it arrives, or just before it is sent. Spring Web Services offer this functionality, via the standard Commons Logging interface.
WARNING: Make sure to use Commons Logging version 1.1 or higher. Earlier versions have class loading issues, and do not integrate with the Log4J TRACE level.
To log all server-side messages, simply set the `org.springframework.ws.server.MessageTracing` logger to level DEBUG or TRACE. On the debug level, only the payload root element is logged; on the TRACE level, the entire message content. If you only want to log sent messages, use the `org.springframework.ws.server.MessageTracing.sent` logger; or `org.springframework.ws.server.MessageTracing.received` to log received messages.
On the client-side, similar loggers exist: `org.springframework.ws.client.MessageTracing.sent` and `org.springframework.ws.client.MessageTracing.received`.
Here is an example `log4j.properties` configuration, logging the full content of sent messages on the client side, and only the payload root element for client-side received messages. On the server-side, the payload root is logged for both sent and received messages:
[source]
----
log4j.rootCategory=INFO, stdout
log4j.logger.org.springframework.ws.client.MessageTracing.sent=TRACE
log4j.logger.org.springframework.ws.client.MessageTracing.received=DEBUG
log4j.logger.org.springframework.ws.server.MessageTracing=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%p [%c{3}] %m%n
----
With this configuration, a typical output will be:
----
TRACE [client.MessageTracing.sent] Sent request [<SOAP-ENV:Envelope xmlns:SOAP-ENV="...
DEBUG [server.MessageTracing.received] Received request [SaajSoapMessage {http://example.com}request] ...
DEBUG [server.MessageTracing.sent] Sent response [SaajSoapMessage {http://example.com}response] ...
DEBUG [client.MessageTracing.received] Received response [SaajSoapMessage {http://example.com}response] ...
----

View File

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

View File

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 20 KiB

View File

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

Before

Width:  |  Height:  |  Size: 6.7 KiB

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

View File

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View File

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 22 KiB

View File

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 36 KiB

View File

@@ -0,0 +1,51 @@
= Spring Web Services Reference Documentation
Arjen Poutsma, Rick Evans, Tareq Abed Rabbo, Greg Turnquist
:revnumber: {version}
:revdate: {localdate}
:toc:
:toclevels: 4
:toc-placement!:
:sectnumlevels: 3
(C) 2005-2017 The original authors.
NOTE: Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
toc::[]
:sectnums!:
[[spring-framework-reference]]
include::preface.adoc[leveloffset=+1]
:sectnums!:
= I. Introduction
:sectnums:
This first part of the reference documentation <<what-is-spring-ws,is an overview>> of Spring Web Services and the underlying concepts. Spring-WS is then introduced, and <<why-contract-first,the concepts>> behind contract-first Web service development are explained.
include::what-is-spring-ws.adoc[leveloffset=+1]
include::why-contract-first.adoc[leveloffset=+1]
include::tutorial.adoc[leveloffset=+1]
:sectnums!:
= II. Reference
:sectnums:
This part of the reference documentation details the various components that comprise Spring Web Services. This includes <<common,a chapter>> that discusses the parts common to both client- and server-side WS, a chapter devoted to the specifics of <<server,writing server-side Web services>>, a chapter about using Web services on <<client,the client-side>>, and a chapters on using <<security,WS-Security>>.
include::common.adoc[leveloffset=+1]
include::server.adoc[leveloffset=+1]
include::client.adoc[leveloffset=+1]
include::security.adoc[leveloffset=+1]
:sectnums!:
[[resources]]
= III. Other Resources
:sectnums:
In addition to this reference documentation, there exist a number of other resources that may help you learn how to use Spring Web Services. These additional, third-party resources are enumerated in this section.
:sectnums!:
include::bibliography.adoc[leveloffset=+1]

View File

@@ -0,0 +1,8 @@
[preface]
[[overview]]
= Preface
In the current age of Service Oriented Architectures, more and more people are using Web Services to connect previously unconnected systems. Initially, Web services were considered to be just another way to do a Remote Procedure Call (RPC). Over time however, people found out that there is a big difference between RPCs and Web services. Especially when interoperability with other platforms is important, it is often better to send encapsulated XML documents, containing all the data necessary to process the request. Conceptually, XML-based Web services are better off being compared to message queues rather than remoting solutions. Overall, XML should be considered the platform-neutral representation of data, the *interlingua* of SOA. When developing or using Web services, the focus should be on this XML, and not on Java.
Spring Web Services focuses on creating these document-driven Web services. Spring Web Services facilitates contract-first SOAP service development, allowing for the creation of flexible web services using one of the many ways to manipulate XML payloads. Spring-WS provides a powerful <<server,message dispatching framework>>, a <<security,WS-Security>> solution that integrates with your existing application security solution, and a <<client,Client-side API>> that follows the familiar Spring template pattern.

View File

@@ -0,0 +1,980 @@
[[security]]
= Securing your Web services with Spring-WS
[[security-introduction]]
== Introduction
This chapter explains how to add WS-Security aspects to your Web services. We will focus on the three different areas of WS-Security, namely:
*Authentication.* This is the process of determining whether a *principal* is who they claim to be. In this context, a "principal" generally means a user, device or some other system which can perform an action in your application.
*Digital signatures.* The digital signature of a message is a piece of information based on both the document and the signer's private key. It is created through the use of a hash function and a private signing function (encrypting with the signer's private key).
*Encryption and Decryption.* _Encryption_ is the process of transforming data into a form that is impossible to read without the appropriate key. It is mainly used to keep information hidden from anyone for whom it is not intended. *Decryption* is the reverse of encryption; it is the process of transforming of encrypted data back into an readable form.
All of these three areas are implemented using the `XwsSecurityInterceptor` or `Wss4jSecurityInterceptor`, which we will describe in <<security-xws-security-interceptor>> and <<security-wss4j-security-interceptor>>, respectively
NOTE: Note that WS-Security (especially encryption and signing) requires substantial amounts of memory, and will also decrease performance. If performance is important to you, you might want to consider not using WS-Security, or simply use HTTP-based security.
[[security-xws-security-interceptor]]
== `XwsSecurityInterceptor`
The `XwsSecurityInterceptor` is an `EndpointInterceptor` (see <<server-endpoint-interceptor>>) that is based on SUN's XML and Web Services Security package (XWSS). This WS-Security implementation is part of the Java Web Services Developer Pack (http://java.sun.com/webservices/[_Java WSDP_]).
Like any other endpoint interceptor, it is defined in the endpoint mapping (see <<server-endpoint-mapping>>). This means that you can be selective about adding WS-Security support: some endpoint mappings require it, while others do not.
NOTE: Note that XWSS requires both a SUN 1.5 JDK and the SUN SAAJ reference implementation. The WSS4J interceptor does not have these requirements (see <<security-wss4j-security-interceptor>>).
The `XwsSecurityInterceptor` requires a *security policy file* to operate. This XML file tells the interceptor what security aspects to require from incoming SOAP messages, and what aspects to add to outgoing messages. The basic format of the policy file will be explained in the following sections, but you can find a more in-depth tutorial http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp564887[_here_]. You can set the policy with the `policyConfiguration` property, which requires a Spring resource. The policy file can contain multiple elements, e.g. require a username token on incoming messages, and sign all outgoing messages. It contains a `SecurityConfiguration` element as root (not a `JAXRPCSecurity` element).
Additionally, the security interceptor requires one or more`CallbackHandler`s to operate. These handlers are used to retrieve certificates, private keys, validate user credentials, etc. Spring-WS offers handlers for most common security concerns, e.g. authenticating against a Spring Security authentication manager, signing outgoing messages based on a X509 certificate. The following sections will indicate what callback handler to use for which security concern. You can set the callback handlers using the `callbackHandler` or `callbackHandlers` property.
Here is an example that shows how to wire the `XwsSecurityInterceptor` up:
[source,xml]
----
<beans>
<bean id="wsSecurityInterceptor"
class="org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor">
<property name="policyConfiguration" value="classpath:securityPolicy.xml"/>
<property name="callbackHandlers">
<list>
<ref bean="certificateHandler"/>
<ref bean="authenticationHandler"/>
</list>
</property>
</bean>
...
</beans>
----
This interceptor is configured using the `securityPolicy.xml` file on the classpath. It uses two callback handlers which are defined further on in the file.
[[keystore]]
=== Keystores
For most cryptographic operations, you will use the standard `java.security.KeyStore` objects. These operations include certificate verification, message signing, signature verification, and encryption, but excludes username and time-stamp verification. This section aims to give you some background knowledge on keystores, and the Java tools that you can use to store keys and certificates in a keystore file. This information is mostly not related to Spring-WS, but to the general cryptographic features of Java.
The `java.security.KeyStore` class represents a storage facility for cryptographic keys and certificates. It can contain three different sort of elements:
*Private Keys.* These keys are used for self-authentication. The private key is accompanied by certificate chain for the corresponding public key. Within the field of WS-Security, this accounts to message signing and message decryption.
*Symmetric Keys.* Symmetric (or secret) keys are used for message encryption and decryption as well. The difference being that both sides (sender and recipient) share the same, secret key.
*Trusted certificates.* These X509 certificates are called a *trusted certificate* because the keystore owner trusts that the public key in the certificates indeed belong to the owner of the certificate. Within WS-Security, these certificates are used for certificate validation, signature verification, and encryption.
==== KeyTool
Supplied with your Java Virtual Machine is the *keytool* program, a key and certificate management utility. You can use this tool to create new keystores, add new private keys and certificates to them, etc. It is beyond the scope of this document to provide a full reference of the *keytool* command, but you can find a reference http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/keytool.html[_here_] , or by giving the command `keytool -help` on the command line.
==== KeyStoreFactoryBean
To easily load a keystore using Spring configuration, you can use the `KeyStoreFactoryBean`. It has a resource location property, which you can set to point to the path of the keystore to load. A password may be given to check the integrity of the keystore data. If a password is not given, integrity checking is not performed.
[source,xml]
----
<bean id="keyStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="password" value="password"/>
<property name="location" value="classpath:org/springframework/ws/soap/security/xwss/test-keystore.jks"/>
</bean>
----
WARNING: If you don't specify the location property, a new, empty keystore will be created, which is most likely not what you want.
[[security-key-store-callback-handler]]
==== KeyStoreCallbackHandler
To use the keystores within a `XwsSecurityInterceptor`, you will need to define a `KeyStoreCallbackHandler`. This callback has three properties with type keystore: (`keyStore`,`trustStore`, and `symmetricStore`). The exact stores used by the handler depend on the cryptographic operations that are to be performed by this handler. For private key operation, the `keyStore` is used, for symmetric key operations the `symmetricStore`, and for determining trust relationships, the `trustStore`. The following table indicates this:
[cols="2", options="header"]
|===
| Cryptographic operation
| Keystore used
| Certificate validation
| first the `keyStore`, then the `trustStore`
| Decryption based on private key
| `keyStore`
| Decryption based on symmetric key
| `symmetricStore`
| Encryption based on public key certificate
| `trustStore`
| Encryption based on symmetric key
| `symmetricStore`
| Signing
| `keyStore`
| Signature verification
| `trustStore`
|===
Additionally, the `KeyStoreCallbackHandler` has a `privateKeyPassword` property, which should be set to unlock the private key(s) contained in the`keyStore`.
If the `symmetricStore` is not set, it will default to the `keyStore`. If the key or trust store is not set, the callback handler will use the standard Java mechanism to load or create it. Refer to the JavaDoc of the `KeyStoreCallbackHandler` to know how this mechanism works.
For instance, if you want to use the `KeyStoreCallbackHandler` to validate incoming certificates or signatures, you would use a trust store, like so:
[source,xml]
----
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="trustStore" ref="trustStore"/>
</bean>
<bean id="trustStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:truststore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
----
If you want to use it to decrypt incoming certificates or sign outgoing messages, you would use a key store, like so:
[source,xml]
----
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="keyStore" ref="keyStore"/>
<property name="privateKeyPassword" value="changeit"/>
</bean>
<bean id="keyStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:keystore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
----
The following sections will indicate where the `KeyStoreCallbackHandler` can be used, and which properties to set for particular cryptographic operations.
=== Authentication
As stated in the introduction, *authentication* is the task of determining whether a principal is who they claim to be. Within WS-Security, authentication can take two forms: using a username and password token (using either a plain text password or a password digest), or using a X509 certificate.
==== Plain Text Username Authentication
The simplest form of username authentication uses*plain text passwords*. In this scenario, the SOAP message will contain a `UsernameToken` element, which itself contains a `Username` element and a `Password` element which contains the plain text password. Plain text authentication can be compared to the Basic Authentication provided by HTTP servers.
WARNING: Note that plain text passwords are not very secure. Therefore, you should always add additional security measures to your transport layer if you are using them (using HTTPS instead of plain HTTP, for instance).
To require that every incoming message contains a `UsernameToken` with a plain text password, the security policy file should contain a `RequireUsernameToken` element, with the `passwordDigestRequired` attribute set to`false`. You can find a reference of possible child elements http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp567459[_here_].
[source,xml]
----
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
...
<xwss:RequireUsernameToken passwordDigestRequired="false" nonceRequired="false"/>
...
</xwss:SecurityConfiguration>
----
If the username token is not present, the `XwsSecurityInterceptor` will return a SOAP Fault to the sender. If it is present, it will fire a `PasswordValidationCallback` with a `PlainTextPasswordRequest` to the registered handlers. Within Spring-WS, there are three classes which handle this particular callback.
[[security-simple-password-validation-callback-handler]]
===== SimplePasswordValidationCallbackHandler
The simplest password validation handler is the `SimplePasswordValidationCallbackHandler`. This handler validates passwords against an in-memory `Properties` object, which you can specify using the `users` property, like so:
[source,xml]
----
<bean id="passwordValidationHandler"
class="org.springframework.ws.soap.security.xwss.callback.SimplePasswordValidationCallbackHandler">
<property name="users">
<props>
<prop key="Bert">Ernie</prop>
</props>
</property>
</bean>
----
In this case, we are only allowing the user "Bert" to log in using the password "Ernie".
===== SpringPlainTextPasswordValidationCallbackHandler
The `SpringPlainTextPasswordValidationCallbackHandler` uses http://project.spring.io/spring-security[_Spring Security_] to authenticate users. It is beyond the scope of this document to describe Spring Security, but suffice it to say that it is a full-fledged security framework. You can read more about it in the https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/[_Spring Security reference documentation_].
The `SpringPlainTextPasswordValidationCallbackHandler` requires an `AuthenticationManager` to operate. It uses this manager to authenticate against a `UsernamePasswordAuthenticationToken` that it creates. If authentication is successful, the token is stored in the `SecurityContextHolder`. You can set the authentication manager using the `authenticationManager`property:
[source,xml]
----
<beans>
<bean id="springSecurityHandler"
class="org.springframework.ws.soap.security.xwss.callback.SpringPlainTextPasswordValidationCallbackHandler">
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<bean class="org.springframework.security.providers.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
</property>
</bean>
<bean id="userDetailsService" class="com.mycompany.app.dao.UserDetailService" />
...
</beans>
----
===== JaasPlainTextPasswordValidationCallbackHandler
The `JaasPlainTextPasswordValidationCallbackHandler` is based on the standard http://java.sun.com/products/jaas/[_Java Authentication and Authorization Service_]. It is beyond the scope of this document to provide a full introduction into JAAS, but there is a http://www.javaworld.com/javaworld/jw-09-2002/jw-0913-jaas.html[_good tutorial_] available.
The `JaasPlainTextPasswordValidationCallbackHandler` requires only a `loginContextName` to operate. It creates a new JAAS `LoginContext` using this name, and handles the standard JAAS `NameCallback` and `PasswordCallback` using the username and password provided in the SOAP message. This means that this callback handler integrates with any JAAS `LoginModule` that fires these callbacks during the `login()` phase, which is standard behavior.
You can wire up a `JaasPlainTextPasswordValidationCallbackHandler` as follows:
[source,xml]
----
<bean id="jaasValidationHandler"
class="org.springframework.ws.soap.security.xwss.callback.jaas.JaasPlainTextPasswordValidationCallbackHandler">
<property name="loginContextName" value="MyLoginModule" />
</bean>
----
In this case, the callback handler uses the `LoginContext` named "MyLoginModule". This module should be defined in your `jaas.config` file, as explained in the abovementioned tutorial.
==== Digest Username Authentication
When using password digests, the SOAP message also contains a `UsernameToken` element, which itself contains a `Username` element and a `Password` element. The difference is that the password is not sent as plain text, but as a *digest*. The recipient compares this digest to the digest he calculated from the known password of the user, and if they are the same, the user is authenticated. It can be compared to the Digest Authentication provided by HTTP servers.
To require that every incoming message contains a `UsernameToken` element with a password digest, the security policy file should contain a `RequireUsernameToken` element, with the `passwordDigestRequired` attribute set to`true`. Additionally, the `nonceRequired` should be set to`true`: You can find a reference of possible child elements http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp567459[_here_].
[source,xml]
----
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
...
<xwss:RequireUsernameToken passwordDigestRequired="true" nonceRequired="true"/>
...
</xwss:SecurityConfiguration>
----
If the username token is not present, the `XwsSecurityInterceptor` will return a SOAP Fault to the sender. If it is present, it will fire a `PasswordValidationCallback` with a `DigestPasswordRequest` to the registered handlers. Within Spring-WS, there are two classes which handle this particular callback.
===== SimplePasswordValidationCallbackHandler
The `SimplePasswordValidationCallbackHandler` can handle both plain text passwords as well as password digests. It is described in <<security-simple-password-validation-callback-handler>>.
===== SpringDigestPasswordValidationCallbackHandler
The `SpringDigestPasswordValidationCallbackHandler` requires an Spring Security `UserDetailService` to operate. It uses this service to retrieve the password of the user specified in the token. The digest of the password contained in this details object is then compared with the digest in the message. If they are equal, the user has successfully authenticated, and a `UsernamePasswordAuthenticationToken` is stored in the `SecurityContextHolder`. You can set the service using the `userDetailsService`. Additionally, you can set a `userCache` property, to cache loaded user details.
[source,xml]
----
<beans>
<bean class="org.springframework.ws.soap.security.xwss.callback.SpringDigestPasswordValidationCallbackHandler">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
<bean id="userDetailsService" class="com.mycompany.app.dao.UserDetailService" />
...
</beans>
----
[[security-certificate-authentication]]
==== Certificate Authentication
A more secure way of authentication uses X509 certificates. In this scenerario, the SOAP message contains a`BinarySecurityToken`, which contains a Base 64-encoded version of a X509 certificate. The certificate is used by the recipient to authenticate. The certificate stored in the message is also used to sign the message (see <<security-verifying-signatures>>).
To make sure that all incoming SOAP messages carry a`BinarySecurityToken`, the security policy file should contain a `RequireSignature` element. This element can further carry other elements, which will be covered in <<security-verifying-signatures>>. You can find a reference of possible child elements http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565769[_here_].
[source,xml]
----
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
...
<xwss:RequireSignature requireTimestamp="false">
...
</xwss:SecurityConfiguration>
----
When a message arrives that carries no certificate, the `XwsSecurityInterceptor` will return a SOAP Fault to the sender. If it is present, it will fire a `CertificateValidationCallback`. There are three handlers within Spring-WS which handle this callback for authentication purposes.
[NOTE]
====
In most cases, certificate *authentication* should be preceded by certificate *validation*, since you only want to authenticate against valid certificates. Invalid certificates such as certificates for which the expiration date has passed, or which are not in your store of trusted certificates, should be ignored.
In Spring-WS terms, this means that the `SpringCertificateValidationCallbackHandler` or `JaasCertificateValidationCallbackHandler` should be preceded by `KeyStoreCallbackHandler`. This can be accomplished by setting the order of the `callbackHandlers` property in the configuration of the `XwsSecurityInterceptor`:
[source,xml]
----
<bean id="wsSecurityInterceptor"
class="org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor">
<property name="policyConfiguration" value="classpath:securityPolicy.xml"/>
<property name="callbackHandlers">
<list>
<ref bean="keyStoreHandler"/>
<ref bean="springSecurityHandler"/>
</list>
</property>
</bean>
----
Using this setup, the interceptor will first determine if the certificate in the message is valid using the keystore, and then authenticate against it.
====
===== KeyStoreCallbackHandler
The `KeyStoreCallbackHandler` uses a standard Java keystore to validate certificates. This certificate validation process consists of the following steps: .
. First, the handler will check whether the certificate is in the private `keyStore`. If it is, it is valid.
. If the certificate is not in the private keystore, the handler will check whether the current date and time are within the validity period given in the certificate. If they are not, the certificate is invalid; if it is, it will continue with the final step.
. Finally, a *certification path* for the certificate is created. This basically means that the handler will determine whether the certificate has been issued by any of the certificate authorities in the`trustStore`. If a certification path can be built successfully, the certificate is valid. Otherwise, the certificate is not.
To use the `KeyStoreCallbackHandler` for certificate validation purposes, you will most likely set only the `trustStore` property:
[source,xml]
----
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="trustStore" ref="trustStore"/>
</bean>
<bean id="trustStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:truststore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
----
Using this setup, the certificate that is to be validated must either be in the trust store itself, or the trust store must contain a certificate authority that issued the certificate.
===== SpringCertificateValidationCallbackHandler
The `SpringCertificateValidationCallbackHandler` requires an Spring Security `AuthenticationManager` to operate. It uses this manager to authenticate against a `X509AuthenticationToken` that it creates. The configured authentication manager is expected to supply a provider which can handle this token (usually an instance of `X509AuthenticationProvider`). If authentication is succesful, the token is stored in the `SecurityContextHolder`. You can set the authentication manager using the `authenticationManager` property:
[source,xml]
----
<beans>
<bean id="springSecurityCertificateHandler"
class="org.springframework.ws.soap.security.xwss.callback.SpringCertificateValidationCallbackHandler">
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<bean id="authenticationManager"
class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<bean class="org.springframework.ws.soap.security.x509.X509AuthenticationProvider">
<property name="x509AuthoritiesPopulator">
<bean class="org.springframework.ws.soap.security.x509.populator.DaoX509AuthoritiesPopulator">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="userDetailsService" class="com.mycompany.app.dao.UserDetailService" />
...
</beans>
----
In this case, we are using a custom user details service to obtain authentication details based on the certificate. Refer to the http://www.springframework.org/security[_Spring Security reference documentation_] for more information about authentication against X509 certificates.
===== JaasCertificateValidationCallbackHandler
The `JaasCertificateValidationCallbackHandler` requires a `loginContextName` to operate. It creates a new JAAS `LoginContext` using this name and with the `X500Principal` of the certificate. This means that this callback handler integrates with any JAAS `LoginModule` that handles X500 principals.
You can wire up a `JaasCertificateValidationCallbackHandler` as follows:
[source,xml]
----
<bean id="jaasValidationHandler"
class="org.springframework.ws.soap.security.xwss.callback.jaas.JaasCertificateValidationCallbackHandler">
<property name="loginContextName">MyLoginModule</property>
</bean>
----
In this case, the callback handler uses the `LoginContext` named "MyLoginModule". This module should be defined in your `jaas.config` file, and should be able to authenticate against X500 principals.
=== Digital Signatures
The *digital signature* of a message is a piece of information based on both the document and the signer's private key. There are two main tasks related to signatures in WS-Security: verifying signatures and signing messages.
[[security-verifying-signatures]]
==== Verifying Signatures
Just like <<security-certificate-authentication,certificate-based authentication>>, a signed message contains a `BinarySecurityToken`, which contains the certificate used to sign the message. Additionally, it contains a `SignedInfo` block, which indicates what part of the message was signed.
To make sure that all incoming SOAP messages carry a`BinarySecurityToken`, the security policy file should contain a `RequireSignature` element. It can also contain a `SignatureTarget` element, which specifies the target message part which was expected to be signed, and various other subelements. You can also define the private key alias to use, whether to use a symmetric instead of a private key, and many other properties. You can find a reference of possible child elements http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565769[_here_].
[source,xml]
----
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:RequireSignature requireTimestamp="false"/>
</xwss:SecurityConfiguration>
----
If the signature is not present, the `XwsSecurityInterceptor` will return a SOAP Fault to the sender. If it is present, it will fire a `SignatureVerificationKeyCallback` to the registered handlers. Within Spring-WS, there are is one class which handles this particular callback: the `KeyStoreCallbackHandler`.
===== KeyStoreCallbackHandler
As described in <<security-key-store-callback-handler>>, the `KeyStoreCallbackHandler` uses a `java.security.KeyStore` for handling various cryptographic callbacks, including signature verification. For signature verification, the handler uses the `trustStore` property:
[source,xml]
----
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="trustStore" ref="trustStore"/>
</bean>
<bean id="trustStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:org/springframework/ws/soap/security/xwss/test-truststore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
----
==== Signing Messages
When signing a message, the `XwsSecurityInterceptor` adds the `BinarySecurityToken` to the message, and a `SignedInfo` block, which indicates what part of the message was signed.
To sign all outgoing SOAP messages, the security policy file should contain a `Sign` element. It can also contain a `SignatureTarget` element, which specifies the target message part which was expected to be signed, and various other subelements. You can also define the private key alias to use, whether to use a symmetric instead of a private key, and many other properties. You can find a reference of possible child elements http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565497[_here_].
[source,xml]
----
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:Sign includeTimestamp="false" />
</xwss:SecurityConfiguration>
----
The `XwsSecurityInterceptor` will fire a `SignatureKeyCallback` to the registered handlers. Within Spring-WS, there are is one class which handles this particular callback: the `KeyStoreCallbackHandler`.
===== KeyStoreCallbackHandler
As described in <<security-key-store-callback-handler>>, the `KeyStoreCallbackHandler` uses a `java.security.KeyStore` for handling various cryptographic callbacks, including signing messages. For adding signatures, the handler uses the `keyStore` property. Additionally, you must set the `privateKeyPassword` property to unlock the private key used for signing.
[source,xml]
----
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="keyStore" ref="keyStore"/>
<property name="privateKeyPassword" value="changeit"/>
</bean>
<bean id="keyStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:keystore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
----
=== Encryption and Decryption
When *encrypting*, the message is transformed into a form that can only be read with the appropriate key. The message can be *decrypted* to reveal the original, readable message.
==== Decryption
To decrypt incoming SOAP messages, the security policy file should contain a `RequireEncryption` element. This element can further carry a `EncryptionTarget` element which indicates which part of the message should be encrypted, and a `SymmetricKey` to indicate that a shared secret instead of the regular private key should be used to decrypt the message. You can read a description of the other elements http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565951[_here_].
[source,xml]
----
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:RequireEncryption />
</xwss:SecurityConfiguration>
----
If an incoming message is not encrypted, the `XwsSecurityInterceptor` will return a SOAP Fault to the sender. If it is present, it will fire a `DecryptionKeyCallback` to the registered handlers. Within Spring-WS, there is one class which handled this particular callback: the`KeyStoreCallbackHandler`.
===== KeyStoreCallbackHandler
As described in <<security-key-store-callback-handler>>, the `KeyStoreCallbackHandler` uses a `java.security.KeyStore` for handling various cryptographic callbacks, including decryption. For decryption, the handler uses the `keyStore` property. Additionally, you must set the `privateKeyPassword` property to unlock the private key used for decryption. For decryption based on symmetric keys, it will use the `symmetricStore`.
[source,xml]
----
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="keyStore" ref="keyStore"/>
<property name="privateKeyPassword" value="changeit"/>
</bean>
<bean id="keyStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:keystore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
----
==== Encryption
To encrypt outgoing SOAP messages, the security policy file should contain a `Encrypt` element. This element can further carry a `EncryptionTarget` element which indicates which part of the message should be encrypted, and a `SymmetricKey` to indicate that a shared secret instead of the regular public key should be used to encrypt the message. You can read a description of the other elements http://java.sun.com/webservices/docs/1.6/tutorial/doc/XWS-SecurityIntro4.html#wp565951[_here_].
[source,xml]
----
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:Encrypt />
</xwss:SecurityConfiguration>
----
The `XwsSecurityInterceptor` will fire a `EncryptionKeyCallback` to the registered handlers in order to retrieve the encryption information. Within Spring-WS, there is one class which handled this particular callback: the `KeyStoreCallbackHandler`.
===== KeyStoreCallbackHandler
As described in <<security-key-store-callback-handler>>, the `KeyStoreCallbackHandler` uses a `java.security.KeyStore` for handling various cryptographic callbacks, including encryption. For encryption based on public keys, the handler uses the `trustStore` property. For encryption based on symmetric keys, it will use the`symmetricStore`.
[source,xml]
----
<beans>
<bean id="keyStoreHandler" class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="trustStore" ref="trustStore"/>
</bean>
<bean id="trustStore" class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:truststore.jks"/>
<property name="password" value="changeit"/>
</bean>
</beans>
----
[[security-xws-exception-handling]]
=== Security Exception Handling
When a securement or validation action fails, the `XwsSecurityInterceptor` will throw a `WsSecuritySecurementException` or `WsSecurityValidationException` respectively. These exceptions bypass the <<server-endpoint-exception-resolver,standard exception handling mechanism>>, but are handled in the interceptor itself.
`WsSecuritySecurementException` exceptions are handled in the `handleSecurementException` method of the `XwsSecurityInterceptor`. By default, this method will simply log an error, and stop further processing of the message.
Similarly, `WsSecurityValidationException` exceptions are handled in the `handleValidationException` method of the `XwsSecurityInterceptor`. By default, this method will create a SOAP 1.1 Client or SOAP 1.2 Sender Fault, and send that back as a response.
NOTE: Both `handleSecurementException` and `handleValidationException` are protected methods, which you can override to change their default behavior.
[[security-wss4j-security-interceptor]]
== `Wss4jSecurityInterceptor`
The `Wss4jSecurityInterceptor` is an `EndpointInterceptor` (see <<server-endpoint-interceptor>>) that is based on https://ws.apache.org/wss4j/[Apache's WSS4J].
WSS4J implements the following standards:
* OASIS Web Serives Security: SOAP Message Security 1.0 Standard 200401, March 2004
* Username Token profile V1.0
* X.509 Token Profile V1.0
This interceptor supports messages created by the `AxiomSoapMessageFactory` and the `SaajSoapMessageFactory`.
=== Configuring `Wss4jSecurityInterceptor`
WSS4J uses no external configuration file; the interceptor is entirely configured by properties. The validation and securement actions executed by this interceptor are specified via `validationActions` and `securementActions` properties, respectively. Actions are passed as a space-separated strings. Here is an example configuration:
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="UsernameToken Encrypt"/>
...
<property name="securementActions" value="Encrypt"/>
...
</bean>
----
Validation actions are:
[cols="2", options="header"]
|===
| Validation action
| Description
| `UsernameToken`
| Validates username token
| `Timestamp`
| Validates the timestamp
| `Encrypt`
| Decrypts the message
| `Signature`
| Validates the signature
| `NoSecurity`
| No action performed
|===
Securement actions are:
[cols="2", options="header"]
|===
| Securement action
| Description
| `UsernameToken`
| Adds a username token
| `UsernameTokenSignature`
| Adds a username token and a signature username token secret key
| `Timestamp`
| Adds a timestamp
| `Encrypt`
| Encrypts the response
| `Signature`
| Signs the response
| `NoSecurity`
| No action performed
|===
The order of the actions is significant and is enforced by the interceptor. The interceptor will reject an incoming SOAP message if its security actions were performed in a different order than the one specified by`validationActions`.
=== Handling Digital Certificates
For cryptographic operations requiring interaction with a keystore or certificate handling (signature, encryption and decryption operations), WSS4J requires an instance of`org.apache.ws.security.components.crypto.Crypto`.
`Crypto` instances can be obtained from WSS4J's `CryptoFactory` or more conveniently with the Spring-WS`CryptoFactoryBean`.
==== CryptoFactoryBean
Spring-WS provides a convenient factory bean, `CryptoFactoryBean` that constructs and configures `Crypto` instances via strong-typed properties (prefered) or through a `Properties` object.
By default, `CryptoFactoryBean` returns instances of `org.apache.ws.security.components.crypto.Merlin`. This can be changed by setting the `cryptoProvider` property (or its equivalent `org.apache.ws.security.crypto.provider` string property).
Here is a simple example configuration:
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="mypassword"/>
<property name="keyStoreLocation" value="file:/path_to_keystore/keystore.jks"/>
</bean>
----
=== Authentication
==== Validating Username Token
Spring-WS provides a set of callback handlers to integrate with Spring Security. Additionally, a simple callback handler `SimplePasswordValidationCallbackHandler` is provided to configure users and passwords with an in-memory `Properties` object.
Callback handlers are configured via `Wss4jSecurityInterceptor`'s `validationCallbackHandler` property.
===== SimplePasswordValidationCallbackHandler
`SimplePasswordValidationCallbackHandler` validates plain text and digest username tokens against an in-memory `Properties` object. It is configured as follows:
[source,xml]
----
<bean id="callbackHandler"
class="org.springframework.ws.soap.security.wss4j.callback.SimplePasswordValidationCallbackHandler">
<property name="users">
<props>
<prop key="Bert">Ernie</prop>
</props>
</property>
</bean>
----
===== SpringSecurityPasswordValidationCallbackHandler
The `SpringSecurityPasswordValidationCallbackHandler` validates plain text and digest passwords using a Spring Security `UserDetailService` to operate. It uses this service to retrieve the (digest of ) the password of the user specified in the token. The (digest of) the password contained in this details object is then compared with the digest in the message. If they are equal, the user has successfully authenticated, and a `UsernamePasswordAuthenticationToken` is stored in the`SecurityContextHolder`. You can set the service using the `userDetailsService`. Additionally, you can set a `userCache` property, to cache loaded user details.
[source,xml]
----
<beans>
<bean class="org.springframework.ws.soap.security.wss4j.callback.SpringDigestPasswordValidationCallbackHandler">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
<bean id="userDetailsService" class="com.mycompany.app.dao.UserDetailService" />
...
</beans>
----
==== Adding Username Token
Adding a username token to an outgoing message is as simple as adding `UsernameToken` to the `securementActions` property of the `Wss4jSecurityInterceptor` and specifying `securementUsername` and`securementPassword`.
The password type can be set via the `securementPasswordType` property. Possible values are `PasswordText` for plain text passwords or `PasswordDigest` for digest passwords, which is the default.
The following example generates a username token with a digest password:
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="UsernameToken"/>
<property name="securementUsername" value="Ernie"/>
<property name="securementPassword" value="Bert"/>
</bean>
----
If plain text password type is chosen, it is possible to instruct the interceptor to add `Nonce` and/or `Created` elements using the `securementUsernameTokenElements` property. The value must be a list containing the desired elements' names separated by spaces (case sensitive).
The next example generates a username token with a plain text password, a `Nonce` and a `Created` element:
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="UsernameToken"/>
<property name="securementUsername" value="Ernie"/>
<property name="securementPassword" value="Bert"/>
<property name="securementPasswordType" value="PasswordText"/>
<property name="securementUsernameTokenElements" value="Nonce Created"/>
</bean>
----
==== Certificate Authentication
As certificate authentication is akin to digital signatures, WSS4J handles it as part of the signature validation and securement. Specifically, the `securementSignatureKeyIdentifier` property must be set to `DirectReference` in order to instruct WSS4J to generate a `BinarySecurityToken` element containing the X509 certificate and to include it in the outgoing message. The certificate's name and password are passed through the `securementUsername` and `securementPassword` properties respectively. See the next example:
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="Signature"/>
<property name="securementSignatureKeyIdentifier" value="DirectReference"/>
<property name="securementUsername" value="mycert"/>
<property name="securementPassword" value="certpass"/>
<property name="securementSignatureCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="classpath:/keystore.jks"/>
</bean>
</property>
</bean>
----
For the certificate validation, regular signature validation applies:
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="Signature"/>
<property name="validationSignatureCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="classpath:/keystore.jks"/>
</bean>
</property>
</bean>
----
At the end of the validation, the interceptor will automatically verify the validity of the certificate by delegating to the default WSS4J implementation. If needed, this behavior can be changed by redefining the `verifyCertificateTrust` method.
For more details, please refer to <<security-wss4j-digital-signatures>>.
=== Security Timestamps
This section describes the various timestamp options available in the `Wss4jSecurityInterceptor`.
==== Validating Timestamps
To validate timestamps add `Timestamp` to the `validationActions` property. It is possible to override timestamp semantics specified by the initiator of the SOAP message by setting `timestampStrict` to `true` and specifying a server-side time to live in seconds (defaults to 300) via the `timeToLive` property footnote:[The interceptor will always reject already expired timestamps whatever the value of `timeToLive` is.] .
In the following example, the interceptor will limit the timestamp validity window to 10 seconds, rejecting any valid timestamp token outside that window:
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="Timestamp"/>
<property name="timestampStrict" value="true"/>
<property name="timeToLive" value="10"/>
</bean>
----
==== Adding Timestamps
Adding `Timestamp` to the `securementActions` property generates a timestamp header in outgoing messages. The `timestampPrecisionInMilliseconds` property specifies whether the precision of the generated timestamp is in milliseconds. The default value is`true`.
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="Timestamp"/>
<property name="timestampPrecisionInMilliseconds" value="true"/>
</bean>
----
[[security-wss4j-digital-signatures]]
=== Digital Signatures
This section describes the various signature options available in the `Wss4jSecurityInterceptor`.
==== Verifying Signatures
To instruct the`Wss4jSecurityInterceptor`, `validationActions` must contain the `Signature` action. Additionally, the `validationSignatureCrypto` property must point to the keystore containing the public certificates of the initiator:
[source,xml]
----
<bean id="wsSecurityInterceptor" class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="Signature"/>
<property name="validationSignatureCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="classpath:/keystore.jks"/>
</bean>
</property>
</bean>
----
==== Signing Messages
Signing outgoing messages is enabled by adding `Signature` action to the`securementActions`. The alias and the password of the private key to use are specified by the `securementUsername` and `securementPassword` properties respectively. `securementSignatureCrypto` must point to the keystore containing the private key:
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="Signature"/>
<property name="securementUsername" value="mykey"/>
<property name="securementPassword" value="123456"/>
<property name="securementSignatureCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="classpath:/keystore.jks"/>
</bean>
</property>
</bean>
----
Furthermore, the signature algorithm can be defined via the `securementSignatureAlgorithm`.
The key identifier type to use can be customized via the `securementSignatureKeyIdentifier` property. Only `IssuerSerial` and `DirectReference` are valid for signature.
`securementSignatureParts` property controls which part of the message shall be signed. The value of this property is a list of semi-colon separated element names that identify the elements to sign. The general form of a signature part is `{}{namespace}Element` footnote:[The first empty brackets are used for encryption parts only.] . The default behavior is to sign the SOAP body.
As an example, here is how to sign the `echoResponse` element in the Spring Web Services echo sample:
[source,xml]
----
<property name="securementSignatureParts"
value="{}{http://www.springframework.org/spring-ws/samples/echo}echoResponse"/>
----
To specify an element without a namespace use the string `Null` as the namespace name (case sensitive).
If there is no other element in the request with a local name of `Body` then the SOAP namespace identifier can be empty (`{}`).
==== Signature Confirmation
Signature confirmation is enabled by setting `enableSignatureConfirmation` to `true`. Note that signature confirmation action spans over the request and the response. This implies that `secureResponse` and `validateRequest` must be set to true (which is the default value) even if there are no corresponding security actions.
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="Signature"/>
<property name="enableSignatureConfirmation" value="true"/>
<property name="validationSignatureCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="file:/keystore.jks"/>
</bean>
</property>
</bean>
----
=== Encryption and Decryption
This section describes the various encryption and descryption options available in the `Wss4jSecurityInterceptor`.
==== Decryption
Decryption of incoming SOAP messages requires `Encrypt` action be added to the `validationActions` property. The rest of the configuration depends on the key information that appears in the message footnote:[This is because WSS4J needs only a Crypto for encypted keys, whereas embedded key name validation is delegated to a callback handler.] .
To decrypt messages with an embedded encypted symmetric key ( `xenc:EncryptedKey` element), `validationDecryptionCrypto` needs to point to a keystore containing the decryption private key. Additionally, `validationCallbackHandler` has to be injected with a `org.springframework.ws.soap.security.wss4j.callback.KeyStoreCallbackHandler` specifying the key's password:
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="Encrypt"/>
<property name="validationDecryptionCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="classpath:/keystore.jks"/>
</bean>
</property>
<property name="validationCallbackHandler">
<bean class="org.springframework.ws.soap.security.wss4j.callback.KeyStoreCallbackHandler">
<property name="privateKeyPassword" value="mykeypass"/>
</bean>
</property>
</bean>
----
To support decryption of messages with an embedded *key name* ( `ds:KeyName` element), configure a `KeyStoreCallbackHandler` that points to the keystore with the symmetric secret key. The property `symmetricKeyPassword` indicates the key's password, the key name being the one specified by `ds:KeyName` element:
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="Encrypt"/>
<property name="validationCallbackHandler">
<bean class="org.springframework.ws.soap.security.wss4j.callback.KeyStoreCallbackHandler">
<property name="keyStore">
<bean class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="classpath:keystore.jks"/>
<property name="type" value="JCEKS"/>
<property name="password" value="123456"/>
</bean>
</property>
<property name="symmetricKeyPassword" value="mykeypass"/>
</bean>
</property>
</bean>
----
==== Encryption
Adding `Encrypt` to the `securementActions` enables encryption of outgoing messages. The certifacte's alias to use for the encryption is set via the `securementEncryptionUser` property. The keystore where the certificate reside is accessed using the `securementEncryptionCrypto` property. As encryption relies on public certificates, no password needs to be passed.
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="Encrypt"/>
<property name="securementEncryptionUser" value="mycert"/>
<property name="securementEncryptionCrypto">
<bean class="org.springframework.ws.soap.security.wss4j.support.CryptoFactoryBean">
<property name="keyStorePassword" value="123456"/>
<property name="keyStoreLocation" value="file:/keystore.jks"/>
</bean>
</property>
</bean>
----
Encryption can be customized in several ways: The key identifier type to use is defined by`securementEncryptionKeyIdentifier`. Possible values are`IssuerSerial`,`X509KeyIdentifier`, `DirectReference`,`Thumbprint`, `SKIKeyIdentifier` or`EmbeddedKeyName`.
If the `EmbeddedKeyName` type is chosen, you need to specify the *secret key* to use for the encryption. The alias of the key is set via the `securementEncryptionUser` property just as for the other key identifier types. However, WSS4J requires a callback handler to fetch the secret key. Thus, `securementCallbackHandler` must be provided with a `KeyStoreCallbackHandler` pointing to the appropriate keystore. By default, the `ds:KeyName` element in the resulting WS-Security header takes the value of the `securementEncryptionUser` property. To indicate a different name, set the `securementEncryptionEmbeddedKeyName` with the desired value. In the next example, the outgoing message will be encrypted with a key aliased `secretKey` whereas `myKey` will appear in `ds:KeyName` element:
[source,xml]
----
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="Encrypt"/>
<property name="securementEncryptionKeyIdentifier" value="EmbeddedKeyName"/>
<property name="securementEncryptionUser" value="secretKey"/>
<property name="securementEncryptionEmbeddedKeyName" value="myKey"/>
<property name="securementCallbackHandler">
<bean class="org.springframework.ws.soap.security.wss4j.callback.KeyStoreCallbackHandler">
<property name="symmetricKeyPassword" value="keypass"/>
<property name="keyStore">
<bean class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="location" value="file:/keystore.jks"/>
<property name="type" value="jceks"/>
<property name="password" value="123456"/>
</bean>
</property>
</bean>
</property>
</bean>
----
The `securementEncryptionKeyTransportAlgorithm` property defines which algorithm to use to encrypt the generated symmetric key. Supported values are `http://www.w3.org/2001/04/xmlenc#rsa-1_5`, which is the default, and `http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p`.
The symmetric encryption algorithm to use can be set via the `securementEncryptionSymAlgorithm` property. Supported values are `http://www.w3.org/2001/04/xmlenc#aes128-cbc` (default value), `http://www.w3.org/2001/04/xmlenc#tripledes-cbc`, `http://www.w3.org/2001/04/xmlenc#aes256-cbc`, `http://www.w3.org/2001/04/xmlenc#aes192-cbc`.
Finally, the `securementEncryptionParts` property defines which parts of the message will be encrypted. The value of this property is a list of semi-colon separated element names that identify the elements to encrypt. An encryption mode specifier and a namespace identification, each inside a pair of curly brackets, may precede each element name. The encryption mode specifier is either `{Content}` or `{Element}` footnote:[Please refer to the W3C XML Encryption specification about the differences between Element and Content encryption.] . The following example identifies the `echoResponse` from the echo sample:
[source,xml]
----
<property name="securementEncryptionParts"
value="{Content}{http://www.springframework.org/spring-ws/samples/echo}echoResponse"/>
----
Be aware that the element name, the namespace identifier, and the encryption modifier are case sensitive. The encryption modifier and the namespace identifier can be omitted. In this case the encryption mode defaults to `Content` and the namespace is set to the SOAP namespace.
To specify an element without a namespace use the value `Null` as the namespace name (case sensitive). If no list is specified, the handler encrypts the SOAP Body in `Content` mode by default.
=== Security Exception Handling
The exception handling of the `Wss4jSecurityInterceptor` is identical to that of the `XwsSecurityInterceptor`. See <<security-xws-exception-handling>> for more information.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,570 @@
[[tutorial]]
= Writing Contract-First Web Services
== Introduction
This tutorial shows you how to write <<why-contract-first,contract-first Web services>>, that is, developing web services that start with the XML Schema/WSDL contract first 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 <<tutorial-creating-project,second part>> focuses 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 Human Resources department. Clients can send holiday request forms to this service to book a holiday.
== 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.
=== Holiday
In the scenario, we have to deal with holiday requests, so it makes sense to determine what a holiday looks like in XML:
[source,xml]
----
<Holiday xmlns="http://mycompany.com/hr/schemas">
<StartDate>2006-07-03</StartDate>
<EndDate>2006-07-07</EndDate>
</Holiday>
----
A holiday consists of a start date and an end date. We have also decided to use the standard https://www.cl.cam.ac.uk/~mgk25/iso-time.html[ISO 8601] date format for the dates, because that will save a lot of parsing hassle. We have also added a namespace to the element, to make sure our elements can used within other XML documents.
=== Employee
There is also the notion of an employee in the scenario. Here is what it looks like in XML:
[source,xml]
----
<Employee xmlns="http://mycompany.com/hr/schemas">
<Number>42</Number>
<FirstName>Arjen</FirstName>
<LastName>Poutsma</LastName>
</Employee>
----
We have used the same namespace as before. If this `<Employee/>` element could be used in other scenarios, it might make sense to use a different namespace, such as `http://mycompany.com/employees/schemas`.
=== HolidayRequest
Both the holiday and employee element can be put in a `<HolidayRequest/>`:
[source,xml]
----
<HolidayRequest xmlns="http://mycompany.com/hr/schemas">
<Holiday>
<StartDate>2006-07-03</StartDate>
<EndDate>2006-07-07</EndDate>
</Holiday>
<Employee>
<Number>42</Number>
<FirstName>Arjen</FirstName>
<LastName>Poutsma</LastName>
</Employee>
</HolidayRequest>
----
The order of the two elements does not matter: `<Employee/>` could have been the first element just as well. What is important is that all of the data is there. In fact, the data is the only thing that is important: we are taking a *data-driven* approach.
[[tutorial.xsd]]
== 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:
* DTDs
* https://www.w3.org/XML/Schema[XML Schema (XSD)]
* http://www.relaxng.org/[RELAX NG]
* http://www.schematron.com/[Schematron]
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.
Using the sample described above, we end up with the following generated schema:
[source,xml]
----
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace="http://mycompany.com/hr/schemas"
xmlns:hr="http://mycompany.com/hr/schemas">
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:sequence>
<xs:element ref="hr:Holiday"/>
<xs:element ref="hr:Employee"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Holiday">
<xs:complexType>
<xs:sequence>
<xs:element ref="hr:StartDate"/>
<xs:element ref="hr:EndDate"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="StartDate" type="xs:NMTOKEN"/>
<xs:element name="EndDate" type="xs:NMTOKEN"/>
<xs:element name="Employee">
<xs:complexType>
<xs:sequence>
<xs:element ref="hr:Number"/>
<xs:element ref="hr:FirstName"/>
<xs:element ref="hr:LastName"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Number" type="xs:integer"/>
<xs:element name="FirstName" type="xs:NCName"/>
<xs:element name="LastName" type="xs:NCName"/>
</xs:schema>
----
This generated schema obviously can be improved. The first thing to notice is that every type has a root-level element declaration. This means that the Web service should be able to accept all of these elements as data. This is not desirable: we only want to accept a `<HolidayRequest/>`. By removing the wrapping element tags (thus keeping the types), and inlining the results, we can accomplish this.
[source,xml]
----
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:hr="http://mycompany.com/hr/schemas"
elementFormDefault="qualified"
targetNamespace="http://mycompany.com/hr/schemas">
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="Holiday" type="hr:HolidayType"/>
<xs:element name="Employee" type="hr:EmployeeType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="HolidayType">
<xs:sequence>
<xs:element name="StartDate" type="xs:NMTOKEN"/>
<xs:element name="EndDate" type="xs:NMTOKEN"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="EmployeeType">
<xs:sequence>
<xs:element name="Number" type="xs:integer"/>
<xs:element name="FirstName" type="xs:NCName"/>
<xs:element name="LastName" type="xs:NCName"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
----
The schema still has one problem: with a schema like this, you can expect the following messages to validate:
[source,xml]
----
<HolidayRequest xmlns="http://mycompany.com/hr/schemas">
<Holiday>
<StartDate>this is not a date</StartDate>
<EndDate>neither is this</EndDate>
</Holiday>
PlainText Section qName:lineannotation level:4, chunks:[<, !-- ... --, >] attrs:[:]
</HolidayRequest>
----
Clearly, we must make sure that the start and end date are really dates. XML Schema has an excellent built-in `date` type which we can use. We also change the `NCName` s to `string` s. Finally, we change the `sequence` in `<HolidayRequest/>` to `all`. This tells the XML parser that the order of `<Holiday/>` and `<Employee/>` is not significant. Our final XSD now looks like this:
[source,xml]
----
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:hr="http://mycompany.com/hr/schemas"
elementFormDefault="qualified"
targetNamespace="http://mycompany.com/hr/schemas">
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:all>
<xs:element name="Holiday" type="hr:HolidayType"/> <!--1-->
<xs:element name="Employee" type="hr:EmployeeType"/> <!--1-->
</xs:all>
</xs:complexType>
</xs:element>
<xs:complexType name="HolidayType">
<xs:sequence>
<xs:element name="StartDate" type="xs:date"/> <!--2-->
<xs:element name="EndDate" type="xs:date"/> <!--2-->
</xs:sequence>
</xs:complexType>
<xs:complexType name="EmployeeType">
<xs:sequence>
<xs:element name="Number" type="xs:integer"/>
<xs:element name="FirstName" type="xs:string"/> <!--3-->
<xs:element name="LastName" type="xs:string"/> <!--3-->
</xs:sequence>
</xs:complexType>
</xs:schema>
----
<1> `all` tells the XML parser that the order of `<Holiday/>` and `<Employee/>` is not significant.
<2> We use the `xs:date` data type, which consist of a year, month, and day, for `<StartDate/>` and `<EndDate/>`.
<3> `xs:string` is used for the first and last name.
We store this file as `hr.xsd`.
[[tutorial-service-contract]]
== Service contract
A service contract is generally expressed as a https://www.w3.org/TR/wsdl[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 <<tutorial.implementing.endpoint>>. You can skip to <<tutorial-creating-project,the next section>> if you want to; the remainder of this section will show you how to write your own WSDL by hand.
We start our WSDL with the standard preamble, and by importing our existing XSD. To separate the schema from the definition, we will use a separate namespace for the WSDL definitions: `http://mycompany.com/hr/definitions`.
[source,xml]
----
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:schema="http://mycompany.com/hr/schemas"
xmlns:tns="http://mycompany.com/hr/definitions"
targetNamespace="http://mycompany.com/hr/definitions">
<wsdl:types>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:import namespace="http://mycompany.com/hr/schemas" schemaLocation="hr.xsd"/>
</xsd:schema>
</wsdl:types>
----
Next, we add our messages based on the written schema types. We only have one message: one with the `<HolidayRequest/>` we put in the schema:
[source,xml]
----
<wsdl:message name="HolidayRequest">
<wsdl:part element="schema:HolidayRequest" name="HolidayRequest"/>
</wsdl:message>
----
We add the message to a port type as an operation:
[source,xml]
----
<wsdl:portType name="HumanResource">
<wsdl:operation name="Holiday">
<wsdl:input message="tns:HolidayRequest" name="HolidayRequest"/>
</wsdl:operation>
</wsdl:portType>
----
That finished the abstract part of the WSDL (the interface, as it were), and leaves the concrete part. The concrete part consists of a `binding`, which tells the client *how* to invoke the operations you've just defined; and a `service`, which tells it _where_ to invoke it.
Adding a concrete part is pretty standard: just refer to the abstract part you defined previously, make sure you use *document/literal* for the `soap:binding` elements (`rpc/encoded` is deprecated), pick a `soapAction` for the operation (in this case `http://mycompany.com/RequestHoliday`, but any URI will do), and determine the `location` URL where you want request to come in (in this case `http://mycompany.com/humanresources`):
[source,xml]
----
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:schema="http://mycompany.com/hr/schemas"
xmlns:tns="http://mycompany.com/hr/definitions"
targetNamespace="http://mycompany.com/hr/definitions">
<wsdl:types>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:import namespace="http://mycompany.com/hr/schemas" <!--1-->
schemaLocation="hr.xsd"/>
</xsd:schema>
</wsdl:types>
<wsdl:message name="HolidayRequest"> <!--2-->
<wsdl:part element="schema:HolidayRequest" name="HolidayRequest"/> <!--3-->
</wsdl:message>
<wsdl:portType name="HumanResource"> <!--4-->
<wsdl:operation name="Holiday">
<wsdl:input message="tns:HolidayRequest" name="HolidayRequest"/> <!--2-->
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="HumanResourceBinding" type="tns:HumanResource"> <!--4--><!--5-->
<soap:binding style="document" <!--6-->
transport="http://schemas.xmlsoap.org/soap/http"/> <!--7-->
<wsdl:operation name="Holiday">
<soap:operation soapAction="http://mycompany.com/RequestHoliday"/> <!--8-->
<wsdl:input name="HolidayRequest">
<soap:body use="literal"/> <!--6-->
</wsdl:input>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="HumanResourceService">
<wsdl:port binding="tns:HumanResourceBinding" name="HumanResourcePort"> <!--5-->
<soap:address location="http://localhost:8080/holidayService/"/> <!--9-->
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
----
<1> We import the schema defined in <<tutorial.xsd>>.
<2> We define the `HolidayRequest` message, which gets used in the `portType`.
<3> The `HolidayRequest` type is defined in the schema.
<4> We define the `HumanResource` port type, which gets used in the `binding`.
<5> We define the `HumanResourceBinding` binding, which gets used in the `port`.
<6> We use a document/literal style.
<7> The literal `http://schemas.xmlsoap.org/soap/http` signifies a HTTP transport.
<8> The `soapAction` attribute signifies the `SOAPAction` HTTP header that will be sent with every request.
<9> The `http://localhost:8080/holidayService/` 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.
[[tutorial-creating-project]]
== Creating the project
In this section, we will be using https://maven.apache.org/[Maven3] 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 Maven3 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= \
-DgroupId=com.mycompany.hr \
-DartifactId=holidayService
----
This command will create a new directory called `holidayService`. 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.
[source,xml,subs="verbatim,quotes"]
----
<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>MyCompany HR Holiday Service</display-name>
_<!-- take special notice of the name of this servlet -->_
<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>/*</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/spring-ws-servlet.xml'`. This file contains all of the Spring-WS-specific beans such as `EndPoints`, `WebServiceMessageReceivers`, and suchlike, 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 `'spring-ws'`) with `'-servlet.xml'` appended to it. So if you defined a `MessageDispatcherServlet` with the name `'dynamite'`, the name of the Spring-WS-specific configuration file would be `'WEB-INF/dynamite-servlet.xml'`.
(You can see the contents of the `'WEB-INF/spring-ws-servlet.xml'` file for this example in <<tutorial.example.sws-conf-file>>.)
Once you had the project structure created, you can put the schema and wsdl from previous section into `'WEB-INF/'` folder.
[[tutorial.implementing.endpoint]]
== Implementing the Endpoint
In Spring-WS, you will implement _Endpoints_ to handle incoming XML messages. An endpoint is typically created by annotating a class with the `@Endpoint` annotation. In this endpoint class, you will create one or more methods that handle incoming request. The method signatures can be quite flexible: you can include just about any sort of parameter type related to the incoming XML message, as will be explained later.
=== Handling the XML Message
In this sample application, we are going to use http://www.jdom.org/[JDom 2] to handle the XML message. We are also using https://www.w3.org/TR/xpath20/[XPath], because it allows us to select particular parts of the XML JDOM tree, without requiring strict schema conformance.
[source,java]
----
package com.mycompany.hr.ws;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import com.mycompany.hr.service.HumanResourceService;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
@Endpoint // <1>
public class HolidayEndpoint {
private static final String NAMESPACE_URI = "http://mycompany.com/hr/schemas";
private XPathExpression<Element> startDateExpression;
private XPathExpression<Element> endDateExpression;
private XPathExpression<Element> firstNameExpression;
private XPathExpression<Element> lastNameExpression;
private HumanResourceService humanResourceService;
@Autowired // <2>
public HolidayEndpoint(HumanResourceService humanResourceService) throws JDOMException {
this.humanResourceService = humanResourceService;
Namespace namespace = Namespace.getNamespace("hr", NAMESPACE_URI);
XPathFactory xPathFactory = XPathFactory.instance();
startDateExpression = xPathFactory.compile("//hr:StartDate", Filters.element(), null, namespace);
endDateExpression = xPathFactory.compile("//hr:EndDate", Filters.element(), null, namespace);
firstNameExpression = xPathFactory.compile("//hr:FirstName", Filters.element(), null, namespace);
lastNameExpression = xPathFactory.compile("//hr:LastName", Filters.element(), null, namespace);
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "HolidayRequest") // <3>
public void handleHolidayRequest(@RequestPayload Element holidayRequest) throws Exception {// <4>
Date startDate = parseDate(startDateExpression, holidayRequest);
Date endDate = parseDate(endDateExpression, holidayRequest);
String name = firstNameExpression.evaluateFirst(holidayRequest).getText() + " " + lastNameExpression.evaluateFirst(holidayRequest).getText();
humanResourceService.bookHoliday(startDate, endDate, name);
}
private Date parseDate(XPathExpression<Element> expression, Element element) throws ParseException {
Element result = expression.evaluateFirst(element);
if (result != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.parse(result.getText());
} else {
throw new IllegalArgumentException("Could not evaluate [" + expression + "] on [" + element + "]");
}
}
}
----
<1> The `HolidayEndpoint` is annotated with `@Endpoint`. This marks the class as a special sort of `@Component`, suitable for handling XML messages in Spring-WS, and also making it eligible for suitable for component scanning.
<2> The `HolidayEndpoint` requires the `HumanResourceService` business service to operate, so we inject the dependency via the constructor and annotate it with `@Autowired`.
Next, we set up XPath expressions using the JDOM2 API. There are four expressions: `//hr:StartDate` for extracting the `<StartDate>` text value, `//hr:EndDate` for extracting the end date and two for extracting the names of the employee.
<3> The `@PayloadRoot` annotation tells Spring-WS that the `handleHolidayRequest` method is suitable for handling XML messages. The sort of message that this method can handle is indicated by the annotation values, in this case, it can
handle XML elements that have the `HolidayRequest` local part and the `http://mycompany.com/hr/schemas` namespace.
More information about mapping messages to endpoints is provided in the next section.
<4> The `handleHolidayRequest(..)` method is the main handling method method, which gets passed with the `<HolidayRequest/>`
element from the incoming XML message. The `@RequestPayload` annotation indicates that the `holidayRequest` parameter should be mapped to the payload of the
request message. We use the XPath expressions to extract the string values from the XML messages, and convert these values to `Date` objects using a
`SimpleDateFormat` (the `parseData` method). With these values, we invoke a method on the business service.
Typically, this will result in a database transaction being started, and some records being altered in the database.
Finally, we define a `void` return type, which indicates to Spring-WS that we do not want to send a response message.
If we wanted a response message, we could have returned a JDOM Element that represents the payload of the response message.
Using JDOM is just one of the options to handle the XML: other options include DOM, dom4j, XOM, SAX, and StAX, but also marshalling techniques like JAXB, Castor, XMLBeans, JiBX, and XStream, as is explained in the next chapter. We chose JDOM because it gives us access to the raw XML, and because it is based on classes (not interfaces and factory methods as with W3C DOM and dom4j), which makes the code less verbose. We use XPath because it is less fragile than marshalling technologies: we don't care for strict schema conformance, as long as we can find the dates and the name.
Because we use JDOM, we must add some dependencies to the Maven `pom.xml`, which is in the root of our project directory. Here is the relevant section of the POM:
[source,xml]
----
<dependencies>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version></version>
</dependency>
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
----
Here is how we would configure these classes in our `spring-ws-servlet.xml` Spring XML configuration file, by using component scanning. We also instruct Spring-WS to use annotation-driven endpoints, with the `<sws:annotation-driven>` element.
[source,xml]
----
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sws="http://www.springframework.org/schema/web-services"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.mycompany.hr"/>
<sws:annotation-driven/>
</beans>
----
=== Routing the Message to the Endpoint
As part of writing the endpoint, we also used the `@PayloadRoot` annotation to indicate which sort of messages can be handled by the `handleHolidayRequest` method. In Spring-WS, this process is the responsibility of an `EndpointMapping`. Here we route messages based on their content, by using a `PayloadRootAnnotationMethodEndpointMapping`. The annotation used above:
[source,java]
----
@PayloadRoot(namespace = "http://mycompany.com/hr/schemas", localPart = "HolidayRequest")
----
basically means that whenever an XML message is received with the namespace `http://mycompany.com/hr/schemas` and the `HolidayRequest` local name, it will be routed to the `handleHolidayRequest` method. By using the `<sws:annotation-driven>` element in our configuration, we enable the detection of the `@PayloadRoot` annotations. It is possible (and quite common) to have multiple, related handling methods in an endpoint, each of them handling different XML messages.
There are also other ways to map endpoints to XML messages, which will be described in the next chapter.
=== Providing the Service and Stub implementation
Now that we have the *Endpoint*, we need `HumanResourceService` and its implementation for use by `HolidayEndpoint`.
[source,java]
----
package com.mycompany.hr.service;
import java.util.Date;
public interface HumanResourceService {
void bookHoliday(Date startDate, Date endDate, String name);
}
----
For tutorial purposes, we will use a simple stub implementation of the `HumanResourceService`.
[source,java]
----
package com.mycompany.hr.service;
import java.util.Date;
import org.springframework.stereotype.Service;
@Service // <1>
public class StubHumanResourceService implements HumanResourceService {
public void bookHoliday(Date startDate, Date endDate, String name) {
System.out.println("Booking holiday for [" + startDate + "-" + endDate + "] for [" + name + "] ");
}
}
----
<1> The `StubHumanResourceService` is annotated with `@Service`. This marks the class as a business facade, which makes this a candidate for injection by `@Autowired` in `HolidayEndpoint`.
[[tutorial-publishing-wsdl]]
== Publishing the WSDL
Finally, we need to publish the WSDL. As stated in <<tutorial-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:
[source,xml]
----
<sws:dynamic-wsdl id="holiday" <!--1-->
portTypeName="HumanResource" <!--3-->
locationUri="/holidayService/" <!--4-->
targetNamespace="http://mycompany.com/hr/definitions"> <!--5-->
<sws:xsd location="/WEB-INF/hr.xsd"/> <!--2-->
</sws:dynamic-wsdl>
----
<1> The id determines the URL where the WSDL can be retrieved. In this case, the 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/holidayService/holiday.wsdl`.
<2> Next, we set the WSDL port type to be `HumanResource`.
<3> We set the location where the service can be reached: `/holidayService/`. We use 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.
For more information, please refer to <<server-automatic-wsdl-exposure, the section called “Automatic WSDL exposure”>>. For the location transformation to work, we need to add an init parameter to `spring-ws`
servlet in `web.xml` (shown below).
<4> We define the target namespace for the WSDL definition itself. Setting this attribute is not required. If not set, the WSDL will have the same namespace as the XSD schema.
<5> The `xsd` element refers to the human resource schema we defined in <<tutorial.xsd>>. We simply placed the schema in the `WEB-INF` directory of the application.
[source,xml]
----
<init-param>
<param-name>transformWsdlLocations</param-name>
<param-value>true</param-value>
</init-param>
----
You can create a WAR file using *mvn install*. If you deploy the application (to Tomcat, Jetty, etc.), and point your browser at http://localhost:8080/holidayService/holiday.wsdl[this location], you will see the generated WSDL. This WSDL is ready to be used by clients, such as http://www.soapui.org/[soapUI], or other SOAP frameworks.
That concludes this tutorial. The tutorial code can be found in the full distribution of Spring-WS. The next step would be to look at the echo sample application that is part of the distribution. After that, look at the airline sample, which is a bit more complicated, because it uses JAXB, WS-Security, Hibernate, and a transactional service layer. Finally, you can read the rest of the reference documentation.

View File

@@ -0,0 +1,64 @@
[[what-is-spring-ws]]
= What is Spring Web Services?
== Introduction
Spring Web Services (Spring-WS) is a product of the Spring community focused on creating document-driven Web services. Spring Web Services aims to facilitate contract-first SOAP service development, allowing for the creation of flexible web services using one of the many ways to manipulate XML payloads. The product is based on Spring itself, which means you can use the Spring concepts such as dependency injection as an integral part of your Web service.
People use Spring-WS for many reasons, but most are drawn to it after finding alternative SOAP stacks lacking when it comes to following Web service best practices. Spring-WS makes the best practice an easy practice. This includes practices such as the WS-I basic profile, Contract-First development, and having a loose coupling between contract and implementation. The other key features of Spring Web services are:
=== Powerful mappings
You can distribute incoming XML requests to any object, depending on message payload, SOAP Action header, or an XPath expression.
=== XML API support
Incoming XML messages can be handled not only with standard JAXP APIs such as DOM, SAX, and StAX, but also JDOM, dom4j, XOM, or even marshalling technologies.
=== Flexible XML Marshalling
Spring Web Services builds on the Object/XML Mapping module in the Spring Framework, which supports JAXB 1 and 2, Castor, XMLBeans, JiBX, and XStream.
=== Reuses your Spring expertise
Spring-WS uses Spring application contexts for all configuration, which should help Spring developers get up-to-speed nice and quickly. Also, the architecture of Spring-WS resembles that of Spring-MVC.
=== Supports WS-Security
WS-Security allows you to sign SOAP messages, encrypt and decrypt them, or authenticate against them.
=== Integrates with Spring Security
The WS-Security implementation of Spring Web Services provides integration with Spring Security. This means you can use your existing Spring Security configuration for your SOAP service as well.
=== Apache license
You can confidently use Spring-WS in your project.
== Runtime environment
Spring Web Services requires a standard Java 7 Runtime Environment. Java 8 is also supported. Spring-WS is built on Spring Framework 4.0.9, but higher versions are supported.
Spring-WS consists of a number of modules, which are described in the remainder of this section.
* The XML module (`spring-xml.jar`) contains various XML support classes for Spring Web Services. This module is mainly intended for the Spring-WS framework itself, and not a Web service developers.
* The Core module (`spring-ws-core.jar`) is the central part of the Spring's Web services functionality. It provides the central <<web-service-messages,`WebServiceMessage`>> and <<soap-message,`SoapMessage`>> interfaces, the <<server,server-side>> framework, with powerful message dispatching, and the various support classes for implementing Web service endpoints; and the <<client,client-side>> `WebServiceTemplate`.
* The Support module (`spring-ws-support.jar`) contains additional transports (JMS, Email, and others).
* The <<security,Security>> package (`spring-ws-security.jar`) provides a WS-Security implementation that integrates with the core Web service package. It allows you to add principal tokens, sign, and decrypt and encrypt SOAP messages. Additionally, it allows you to leverage your existing Spring Security security implementation for authentication and authorization.
The following figure illustrates the Spring-WS modules and the dependencies between them. Arrows indicate dependencies, i.e. Spring-WS Core depends on Spring-XML and the OXM module found in Spring 3 and higher.
image::spring-deps.png[align="center"]
== Supported standards
Spring Web Services supports the following standards:
* SOAP 1.1 and 1.2
* WSDL 1.1 and 2.0 (XSD-based generation only supported for WSDL 1.1)
* WS-I Basic Profile 1.0, 1.1, 1.2 and 2.0
* WS-Addressing 1.0 and the August 2004 draft
* SOAP Message Security 1.1, Username Token Profile 1.1, X.509 Certificate Token Profile 1.1, SAML Token Profile 1.1, Kerberos Token Profile 1.1, Basic Security Profile 1.1

View File

@@ -0,0 +1,172 @@
[[why-contract-first]]
= Why Contract First?
== Introduction
When creating Web services, there are two development styles: *Contract Last* and *Contract First*. When using a contract-last approach, you start with the Java code, and let the Web service contract (*WSDL*, see sidebar) be generated from that. When using contract-first, you start with the WSDL contract, and use Java to implement said contract.
****
*What is WSDL?*
WSDL stands for Web Services Description Language. A WSDL file is an XML document that describes a Web service. It specifies the location of the service and the operations (or methods) the service exposes. For more information about WSDL, refer to the https://www.w3.org/TR/wsdl[WSDL specification].
****
Spring-WS only supports the contract-first development style, and this section explains why.
== Object/XML Impedance Mismatch
Similar to the field of ORM, where we have an https://en.wikipedia.org/wiki/Object-Relational_impedance_mismatch[Object/Relational impedance mismatch], there is a similar problem when converting Java objects to XML. At first glance, the O/X mapping problem appears simple: create an XML element for each Java object, converting all Java properties and fields to sub-elements or attributes. However, things are not as simple as they appear: there is a fundamental difference between hierarchical languages such as XML (and especially XSD) and the graph model of Javafootnote:[Most of the contents in this section was inspired by <<alpine>> and <<effective-enterprise-java>>.].
=== XSD extensions
In Java, the only way to change the behavior of a class is to subclass it, adding the new behavior to that subclass. In XSD, you can extend a data type by restricting it: that is, constraining the valid values for the elements and attributes. For instance, consider the following example:
[source,xml]
----
<simpleType name="AirportCode">
<restriction base="string">
<pattern value="[A-Z][A-Z][A-Z]"/>
</restriction>
</simpleType>
----
This type restricts a XSD string by ways of a regular expression, allowing only three upper case letters. If this type is converted to Java, we will end up with an ordinary `java.lang.String`; the regular expression is lost in the conversion process, because Java does not allow for these sorts of extensions.
=== Unportable types
One of the most important goals of a Web service is to be interoperable: to support multiple platforms such as Java, .NET, Python, etc. Because all of these languages have different class libraries, you must use some common, interlingual format to communicate between them. That format is XML, which is supported by all of these languages.
Because of this conversion, you must make sure that you use portable types in your service implementation. Consider, for example, a service that returns a `java.util.TreeMap`, like so:
[source,java]
----
public Map getFlights() {
// use a tree map, to make sure it's sorted
TreeMap map = new TreeMap();
map.put("KL1117", "Stockholm");
...
return map;
}
----
Undoubtedly, the contents of this map can be converted into some sort of XML, but since there is no *standard* way to describe a map in XML, it will be proprietary. Also, even if it can be converted to XML, many platforms do not have a data structure similar to the `TreeMap`. So when a .NET client accesses your Web service, it will probably end up with a `System.Collections.Hashtable`, which has different semantics.
This problem is also present when working on the client side. Consider the following XSD snippet, which describes a service contract:
[source,xml]
----
<element name="GetFlightsRequest">
<complexType>
<all>
<element name="departureDate" type="date"/>
<element name="from" type="string"/>
<element name="to" type="string"/>
</all>
</complexType>
</element>
----
This contract defines a request that takes an `date`, which is a XSD datatype representing a year, month, and day. If we call this service from Java, we will probably use either a `java.util.Date` or `java.util.Calendar`. However, both of these classes actually describe times, rather than dates. So, we will actually end up sending data that represents the fourth of April 2007 at midnight (`2007-04-04T00:00:00`), which is not the same as `2007-04-04`.
=== Cyclic graphs
Imagine we have the following simple class structure:
[source,java]
----
public class Flight {
private String number;
private List<Passenger> passengers;
// getters and setters omitted
}
public class Passenger {
private String name;
private Flight flight;
// getters and setters omitted
}
----
This is a cyclic graph: the `Flight` refers to the `Passenger`, which refers to the `Flight` again. Cyclic graphs like these are quite common in Java. If we took a naive approach to converting this to XML, we will end up with something like:
[source,xml]
----
<flight number="KL1117">
<passengers>
<passenger>
<name>Arjen Poutsma</name>
<flight number="KL1117">
<passengers>
<passenger>
<name>Arjen Poutsma</name>
<flight number="KL1117">
<passengers>
<passenger>
<name>Arjen Poutsma</name>
...
----
which will take a pretty long time to finish, because there is no stop condition for this loop.
One way to solve this problem is to use references to objects that were already marshalled, like so:
[source,xml]
----
<flight number="KL1117">
<passengers>
<passenger>
<name>Arjen Poutsma</name>
<flight href="KL1117" />
</passenger>
...
</passengers>
</flight>
----
This solves the recursiveness problem, but introduces new ones. For one, you cannot use an XML validator to validate this structure. Another issue is that the standard way to use these references in SOAP (RPC/encoded) has been deprecated in favor of document/literal (see WS-I http://www.ws-i.org/Profiles/BasicProfile-1.1.html#SOAP_encodingStyle_Attribute[Basic Profile]).
These are just a few of the problems when dealing with O/X mapping. It is important to respect these issues when writing Web services. The best way to respect them is to focus on the XML completely, while using Java as an implementation language. This is what contract-first is all about.
== Contract-first versus Contract-last
Besides the Object/XML Mapping issues mentioned in the previous section, there are other reasons for preferring a contract-first development style.
=== Fragility
As mentioned earlier, the contract-last development style results in your web service contract (WSDL and your XSD) being generated from your Java contract (usually an interface). If you are using this approach, you will have no guarantee that the contract stays constant over time. Each time you change your Java contract and redeploy it, there might be subsequent changes to the web service contract.
Aditionally, not all SOAP stacks generate the same web service contract from a Java contract. This means changing your current SOAP stack for a different one (for whatever reason), might also change your web service contract.
When a web service contract changes, users of the contract will have to be instructed to obtain the new contract and potentially change their code to accommodate for any changes in the contract.
In order for a contract to be useful, it must remain constant for as long as possible. If a contract changes, you will have to contact all of the users of your service, and instruct them to get the new version of the contract.
=== Performance
When Java is automatically transformed into XML, there is no way to be sure as to what is sent across the wire. An object might reference another object, which refers to another, etc. In the end, half of the objects on the heap in your virtual machine might be converted into XML, which will result in slow response times.
When using contract-first, you explicitly describe what XML is sent where, thus making sure that it is exactly what you want.
=== Reusability
Defining your schema in a separate file allows you to reuse that file in different scenarios. If you define an `AirportCode` in a file called `airline.xsd`, like so:
[source,xml]
----
<simpleType name="AirportCode">
<restriction base="string">
<pattern value="[A-Z][A-Z][A-Z]"/>
</restriction>
</simpleType>
----
You can reuse this definition in other schemas, or even WSDL files, using an `import` statement.
=== Versioning
Even though a contract must remain constant for as long as possible, they *do* need to be changed sometimes. In Java, this typically results in a new Java interface, such as `AirlineService2`, and a (new) implementation of that interface. Of course, the old service must be kept around, because there might be clients who have not migrated yet.
If using contract-first, we can have a looser coupling between contract and implementation. Such a looser coupling allows us to implement both versions of the contract in one class. We could, for instance, use an XSLT stylesheet to convert any "old-style" messages to the "new-style" messages.

View File

@@ -1,99 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<bibliography
xmlns="http://docbook.org/ns/docbook" version="5.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd">
<title>Bibliography</title>
<biblioentry xml:id="waldo-94">
<authorgroup>
<author>
<personname>
<firstname>Jim</firstname>
<surname>Waldo</surname>
</personname>
</author>
<author>
<personname>
<firstname>Ann</firstname>
<surname>Wollrath</surname>
</personname>
</author>
<author>
<personname>
<firstname>Sam</firstname>
<surname>Kendall</surname>
</personname>
</author>
</authorgroup>
<title>A Note on Distributed Computing</title>
<publisher>
<publishername>Springer Verlag</publishername>
</publisher>
<date>1994</date>
</biblioentry>
<biblioentry xml:id="alpine">
<authorgroup>
<author>
<personname>
<firstname>Steve</firstname>
<surname>Loughran</surname>
</personname>
</author>
<author>
<personname>
<firstname>Edmund</firstname>
<surname>Smith</surname>
</personname>
</author>
</authorgroup>
<title>Rethinking the Java SOAP Stack</title>
<date>May 17, 2005</date>
<copyright>
<year>2005</year>
<holder>IEEE Telephone Laboratories, Inc.</holder>
</copyright>
</biblioentry>
<biblioentry xml:id="effective-enterprise-java">
<authorgroup>
<author>
<personname>
<firstname>Ted</firstname>
<surname>Neward</surname>
</personname>
</author>
</authorgroup>
<editor>
<personname>
<firstname>Scott</firstname>
<surname>Meyers</surname>
</personname>
</editor>
<title>Effective Enterprise Java</title>
<publisher>
<publishername>Addison-Wesley</publishername>
</publisher>
<date>2004</date>
</biblioentry>
<biblioentry xml:id="effective-xml">
<authorgroup>
<author>
<personname>
<firstname>Elliotte Rusty</firstname>
<surname>Harold</surname>
</personname>
</author>
</authorgroup>
<editor>
<personname>
<firstname>Scott</firstname>
<surname>Meyers</surname>
</personname>
</editor>
<title>Effective XML</title>
<publisher>
<publishername>Addison-Wesley</publishername>
</publisher>
<date>2004</date>
</biblioentry>
</bibliography>

View File

@@ -1,871 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<chapter xml:id="client"
xmlns="http://docbook.org/ns/docbook" version="5.0"
xmlns:xl="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd
http://www.w3.org/1999/xlink http://www.docbook.org/xml/5.0/xsd/xlink.xsd">
<title>Using Spring Web Services on the Client</title>
<section>
<title>Introduction</title>
<para>
Spring-WS provides a client-side Web service API that allows for consistent, XML-driven access to
Web services. It also caters for the use of marshallers and unmarshallers
so that your service tier code can deal exclusively with Java objects.
</para>
<para>
The <package>org.springframework.ws.client.core</package> package provides the core functionality
for using the client-side access API. It contains template classes that simplify the use of Web
services, much like the core Spring <classname>JdbcTemplate</classname> does for JDBC. The
design principle common to Spring template classes is to provide helper methods to perform common
operations, and for more sophisticated usage, delegate to user implemented callback interfaces.
The Web service template follows the same design. The classes offer various convenience methods
for the sending and receiving of XML messages, marshalling objects to XML before sending, and
allows for multiple transport options.
</para>
</section>
<section>
<title>Using the client-side API</title>
<section xml:id="client-web-service-template">
<title><classname>WebServiceTemplate</classname></title>
<para>
The <classname>WebServiceTemplate</classname> is the core class for client-side Web service
access in Spring-WS. It contains methods for sending <classname>Source</classname> objects,
and receiving response messages as either <classname>Source</classname> or
<classname>Result</classname>. Additionally, it can marshal objects to XML before sending
them across a transport, and unmarshal any response XML into an object again.
</para>
<section xml:id="client-transports">
<title>URIs and Transports</title>
<para>
The <classname>WebServiceTemplate</classname> class uses an URI as the message destination.
You can either set a <property>defaultUri</property> property on the template itself,
or supply an URI explicitly when calling a method on the template. The URI will be
resolved into a <interfacename>WebServiceMessageSender</interfacename>, which is
responsible for sending the XML message across a transport layer. You can set one or
more message senders using the <property>messageSender</property> or
<property>messageSenders</property> properties of the
<classname>WebServiceTemplate</classname> class.
</para>
<section>
<title>HTTP transports</title>
<para>
There are two implementations of the <classname>WebServiceMessageSender</classname>
interface for sending messages via HTTP. The default implementation is the
<classname>HttpUrlConnectionMessageSender</classname>, which uses the facilities provided
by Java itself. The alternative is the <classname>HttpComponentsMessageSender</classname>,
which uses the
<link xl:href="http://hc.apache.org/httpcomponents-client-ga">Apache HttpComponents HttpClient</link>.
Use the latter if you need more advanced and easy-to-use functionality (such as authentication,
HTTP connection pooling, and so forth).
</para>
<para>
To use the HTTP transport, either set the <property>defaultUri</property> to something like
<uri>http://example.com/services</uri>, or supply the <parameter>uri</parameter> parameter
for one of the methods.
</para>
<para>
The following example shows how the default configuration can be used for HTTP transports:
<programlisting><![CDATA[<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="defaultUri" value="http://example.com/WebService"/>
</bean>
</beans>]]></programlisting>
</para>
<para>
The following example shows how override the default configuration, and to use Apache HttpClient to
authenticate using HTTP authentication:
<programlisting><![CDATA[<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
<property name="credentials">
<bean class="org.apache.http.auth.UsernamePasswordCredentials">
<constructor-arg value="john:secret"/>
</bean>
</property>
</bean>
</property>
<property name="defaultUri" value="http://example.com/WebService"/>
</bean>]]></programlisting>
</para>
</section>
<section>
<title>JMS transport</title>
<para>
For sending messages over JMS, Spring Web Services provides the
<classname>JmsMessageSender</classname>. This class uses the facilities of the Spring framework
to transform the <interfacename>WebServiceMessage</interfacename> into a JMS
<interfacename>Message</interfacename>, send it on its way on a
<interfacename>Queue</interfacename> or <interfacename>Topic</interfacename>, and receive a
response (if any).
</para>
<para>
To use the <classname>JmsMessageSender</classname>, you need to set the
<property>defaultUri</property> or <parameter>uri</parameter> parameter to a JMS URI, which - at a
minimum - consists of the <literal>jms:</literal> prefix and a destination name. Some examples of
JMS URIs are: <uri>jms:SomeQueue</uri>,
<uri>jms:SomeTopic?priority=3&amp;deliveryMode=NON_PERSISTENT</uri>, and
<uri>jms:RequestQueue?replyToName=ResponseName</uri>.
For more information on this URI syntax, refer to the class level Javadoc of the
<classname>JmsMessageSender</classname>.
</para>
<para>
By default, the <classname>JmsMessageSender</classname> send JMS
<interfacename>BytesMessage</interfacename>, but
this can be overriden to use <interfacename>TextMessages</interfacename> by using the
<literal>messageType</literal> parameter on the JMS URI. For example:
<uri>jms:Queue?messageType=TEXT_MESSAGE</uri>.
Note that <interfacename>BytesMessages</interfacename> are the preferred type, because
<interfacename>TextMessages</interfacename> do not support attachments and character
encodings reliably.
</para>
<para>
The following example shows how to use the JMS transport in combination with an ActiceMQ
connection factory:<programlisting><![CDATA[<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost?broker.persistent=false"/>
</bean>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.jms.JmsMessageSender">
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
</property>
<property name="defaultUri" value="jms:RequestQueue?deliveryMode=NON_PERSISTENT"/>
</bean>
</beans>]]></programlisting>
</para>
</section>
<section>
<title>Email transport</title>
<para>
Spring Web Services also provides an email transport, which can be used to send web service
messages via SMTP, and retrieve them via either POP3 or IMAP. The client-side email
functionality is contained in the <classname>MailMessageSender</classname> class.
This class creates an email message from the request
<interfacename>WebServiceMessage</interfacename>, and sends it via SMTP. It then waits for a
response message to arrive in the incoming POP3 or IMAP server.
</para>
<para>
To use the <classname>MailMessageSender</classname>, set the <property>defaultUri</property> or
<parameter>uri</parameter> parameter to a <literal>mailto</literal> URI. Here are some URI
examples: <uri>mailto:john@example.com</uri>, and
<uri>mailto:server@localhost?subject=SOAP%20Test</uri>. Make sure that the message sender is
properly configured with a <property>transportUri</property>, which indicates the server to use for
sending requests (typically a SMTP server), and a <property>storeUri</property>, which indicates
the server to poll for responses (typically a POP3 or IMAP server).
</para>
<para>
The following example shows how to use the email transport:<programlisting><![CDATA[<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.mail.MailMessageSender">
<property name="from" value="Spring-WS SOAP Client &lt;client@example.com&gt;"/>
<property name="transportUri" value="smtp://client:s04p@smtp.example.com"/>
<property name="storeUri" value="imap://client:s04p@imap.example.com/INBOX"/>
</bean>
</property>
<property name="defaultUri" value="mailto:server@example.com?subject=SOAP%20Test"/>
</bean>
</beans>]]></programlisting>
</para>
</section>
<section>
<title>XMPP transport</title>
<para>
Spring Web Services 2.0 introduced an XMPP (Jabber) transport, which can be used to send and
receive web service messages via XMPP. The client-side XMPP
functionality is contained in the <classname>XmppMessageSender</classname> class.
This class creates an XMPP message from the request
<interfacename>WebServiceMessage</interfacename>, and sends it via XMPP. It then listens for a
response message to arrive.
</para>
<para>
To use the <classname>XmppMessageSender</classname>, set the <property>defaultUri</property> or
<parameter>uri</parameter> parameter to a <literal>xmpp</literal> URI, for example
<uri>xmpp:johndoe@jabber.org</uri>. The sender also requires an
<classname>XMPPConnection</classname> to work, which can be conveniently created using the
<classname>org.springframework.ws.transport.xmpp.support.XmppConnectionFactoryBean</classname>.
</para>
<para>
The following example shows how to use the xmpp transport:<programlisting><![CDATA[<beans>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="connection" class="org.springframework.ws.transport.xmpp.support.XmppConnectionFactoryBean">
<property name="host" value="jabber.org"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
</bean>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.xmpp.XmppMessageSender">
<property name="connection" ref="connection"/>
</bean>
</property>
<property name="defaultUri" value="xmpp:user@jabber.org"/>
</bean>
</beans>]]></programlisting>
</para>
</section>
</section>
<section>
<title>Message factories</title>
<para>
In addition to a message sender, the <classname>WebServiceTemplate</classname> requires a Web
service message factory. There are two message factories for SOAP:
<classname>SaajSoapMessageFactory</classname> and <classname>AxiomSoapMessageFactory</classname>.
If no message factory is specified (via the <property>messageFactory</property> property),
Spring-WS will use the <classname>SaajSoapMessageFactory</classname> by default.
</para>
</section>
</section>
<section>
<title>Sending and receiving a <interfacename>WebServiceMessage</interfacename>
</title>
<para>
The <classname>WebServiceTemplate</classname> contains many convenience methods to send and receive
web service messages. There are methods that accept and return a <interfacename>Source</interfacename>
and those that return a <interfacename>Result</interfacename>. Additionally, there are methods which
marshal and unmarshal objects to XML. Here is an example that sends a simple XML message to a Web
service.
</para>
<programlisting><![CDATA[
import java.io.StringReader;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.ws.WebServiceMessageFactory;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.transport.WebServiceMessageSender;
public class WebServiceClient {
private static final String MESSAGE =
"<message xmlns=\"http://tempuri.org\">Hello Web Service World</message>";
private final WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
public void setDefaultUri(String defaultUri) {
webServiceTemplate.setDefaultUri(defaultUri);
}
]]><lineannotation>// send to the configured default URI</lineannotation><![CDATA[
public void simpleSendAndReceive() {
StreamSource source = new StreamSource(new StringReader(MESSAGE));
StreamResult result = new StreamResult(System.out);
webServiceTemplate.sendSourceAndReceiveToResult(source, result);
}
]]><lineannotation>// send to an explicit URI</lineannotation><![CDATA[
public void customSendAndReceive() {
StreamSource source = new StreamSource(new StringReader(MESSAGE));
StreamResult result = new StreamResult(System.out);
webServiceTemplate.sendSourceAndReceiveToResult("http://localhost:8080/AnotherWebService",
source, result);
}
}]]></programlisting>
<programlisting><![CDATA[
<beans xmlns="http://www.springframework.org/schema/beans">
<bean id="webServiceClient" class="WebServiceClient">
<property name="defaultUri" value="http://localhost:8080/WebService"/>
</bean>
</beans>]]></programlisting>
<para>
The above example uses the <classname>WebServiceTemplate</classname> to send a hello
world message to the web service located at <uri>http://localhost:8080/WebService</uri>
(in the case of the <methodname>simpleSendAndReceive()</methodname> method),
and writes the result to the console. The <classname>WebServiceTemplate</classname> is
injected with the default URI, which is used because no URI was supplied explicitly
in the Java code.
</para>
<para>
Please note that the <classname>WebServiceTemplate</classname> class is thread-safe once
configured (assuming that all of it's dependencies are thread-safe too, which is the case for
all of the dependencies that ship with Spring-WS), and so multiple objects can use the same
shared <classname>WebServiceTemplate</classname> instance if so desired.
The <classname>WebServiceTemplate</classname> exposes a zero argument constructor and
<property>messageFactory</property>/<property>messageSender</property> bean properties which
can be used for constructing the instance (using a Spring container or plain Java code).
Alternatively, consider deriving from Spring-WS's <classname>WebServiceGatewaySupport</classname>
convenience base class, which exposes convenient bean properties to enable easy configuration.
(You do <emphasis>not</emphasis> have to extend this base class... it is provided as a convenience
class only.)
</para>
</section>
<section>
<title>Sending and receiving POJOs - marshalling and unmarshalling</title>
<para>
In order to facilitate the sending of plain Java objects, the
<classname>WebServiceTemplate</classname> has a number of <literal>send(..)</literal> methods
that take an <classname>Object</classname> as an argument for a message's data content.
The method <methodname>marshalSendAndReceive(..)</methodname> in the
<classname>WebServiceTemplate</classname> class delegates the conversion of the request object
to XML to a <interfacename>Marshaller</interfacename>, and the conversion of the response
XML to an object to an <interfacename>Unmarshaller</interfacename>. (For more information
about marshalling and unmarshaller, refer to
<link xl:href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/oxm.html">the Spring documentation</link>.)
By using the
marshallers, your application code can focus on the business object that is being sent or
received and not be concerned with the details of how it is represented as XML. In order to
use the marshalling functionality, you have to set a marshaller and unmarshaller with the
<property>marshaller</property>/<property>unmarshaller</property> properties of the
<classname>WebServiceTemplate</classname> class.
</para>
</section>
<section>
<title>
<interfacename>WebServiceMessageCallback</interfacename>
</title>
<para>
To accommodate the setting of SOAP headers and other settings on the message, the
<interfacename>WebServiceMessageCallback</interfacename> interface gives you access to the
message <emphasis>after</emphasis> it has been created, but <emphasis>before</emphasis> it
is sent. The example below demonstrates how to set the SOAP Action header on a message
that is created by marshalling an object.
</para>
<programlisting><![CDATA[
public void marshalWithSoapActionHeader(MyObject o) {
webServiceTemplate.marshalSendAndReceive(o, new WebServiceMessageCallback() {
public void doWithMessage(WebServiceMessage message) {
((SoapMessage)message).setSoapAction("http://tempuri.org/Action");
}
});
}]]></programlisting>
<note>
<para>
Note that you can also use the
<classname>org.springframework.ws.soap.client.core.SoapActionCallback</classname> to set the SOAP
Action header.
</para>
</note>
<section>
<title>WS-Addressing</title>
<para>
In addition to the <link linkend="server-ws-addressing">server-side WS-Addressing</link> support,
Spring Web Services also has support for this specification on the client-side.
</para>
<para>
For setting WS-Addressing headers on the client, you can use the
<classname>org.springframework.ws.soap.addressing.client.ActionCallback</classname>. This callback
takes the desired Action header as a parameter. It also has constructors for specifying the
WS-Addressing version, and a <literal>To</literal> header. If not specified, the
<literal>To</literal> header will default to the URL of the connection being made.
</para>
<para>
Here is an example of setting the <literal>Action</literal> header to
<uri>http://samples/RequestOrder</uri>:<programlisting><![CDATA[
webServiceTemplate.marshalSendAndReceive(o, new ActionCallback("http://samples/RequestOrder"));
]]></programlisting>
</para>
</section>
</section>
<section>
<title>
<interfacename>WebServiceMessageExtractor</interfacename>
</title>
<para>
The <interfacename>WebServiceMessageExtractor</interfacename> interface is a low-level
callback interface that allows you to have full control over the process to extract an
<classname>Object</classname> from a received <interfacename>WebServiceMessage</interfacename>.
The <classname>WebServiceTemplate</classname> will invoke the <methodname>extractData(..)</methodname>
method on a supplied <interfacename>WebServiceMessageExtractor</interfacename>
<emphasis>while the underlying connection to the serving resource is still open</emphasis>.
The following example illustrates the <interfacename>WebServiceMessageExtractor</interfacename>
in action:
</para>
<programlisting><![CDATA[
public void marshalWithSoapActionHeader(final Source s) {
final Transformer transformer = transformerFactory.newTransformer();
webServiceTemplate.sendAndReceive(new WebServiceMessageCallback() {
public void doWithMessage(WebServiceMessage message) {
transformer.transform(s, message.getPayloadResult());
},
new WebServiceMessageExtractor() {
public Object extractData(WebServiceMessage message) throws IOException
]]><lineannotation>// do your own transforms with message.getPayloadResult()</lineannotation><![CDATA[
]]><lineannotation>// or message.getPayloadSource()</lineannotation><![CDATA[
}
});
}]]></programlisting>
</section>
</section>
<section>
<title>Client-side testing</title>
<para>
When it comes to testing your Web service clients (i.e. classes that uses the
<classname>WebServiceTemplate</classname> to access a Web service), there are two possible
approaches:
</para>
<itemizedlist>
<listitem>
<para>
Write <emphasis>Unit Tests</emphasis>, which simply mock away the
<classname>WebServiceTemplate</classname> class,
<interfacename>WebServiceOperations</interfacename> interface, or the complete client class.
</para>
<para>
The advantage of this approach is that it's quite easy to accomplish; the disadvantage is that
you are not really testing the exact content of the XML messages that are sent over the wire,
especially when mocking out the entire client class.
</para>
</listitem>
<listitem>
<para>
Write <emphasis>Integrations Tests</emphasis>, which do test the contents of the message.
</para>
</listitem>
</itemizedlist>
<para>
The first approach can easily be accomplished with mocking frameworks such as EasyMock, JMock, etc.
The next section will focus on writing integration tests, using the test features introduced in Spring
Web Services 2.0.
</para>
<section>
<title>Writing client-side integration tests</title>
<para>
Spring Web Services 2.0 introduced support for creating Web service client integration tests.
In this context, a client is a class that uses the <classname>WebServiceTemplate</classname>
to access a Web service.
</para>
<para>
The integration test support lives in the <package>org.springframework.ws.test.client</package> package.
The core class in that package is the <classname>MockWebServiceServer</classname>.
The underlying idea is that the web service template connects to this mock server, sends it request
message, which the mock server then verifies against the registered expectations.
If the expectations are met, the mock server then prepares a response message, which is send back to the
template.
</para>
<para>
The typical usage of the <classname>MockWebServiceServer</classname> is:
<orderedlist>
<listitem>
<para>
Create a <classname>MockWebServiceServer</classname> instance by calling
<methodname>MockWebServiceServer.createServer(WebServiceTemplate)</methodname>,
<methodname>MockWebServiceServer.createServer(WebServiceGatewaySupport)</methodname>, or
<methodname>MockWebServiceServer.createServer(ApplicationContext)</methodname>.
</para>
</listitem>
<listitem>
<para>
Set up request expectations by calling <methodname>expect(RequestMatcher)</methodname>,
possibly by using the default <interfacename>RequestMatcher</interfacename> implementations
provided in <classname>RequestMatchers</classname> (which can be statically imported).
Multiple expectations can be set up by chaining
<methodname>andExpect(RequestMatcher)</methodname> calls.
</para>
</listitem>
<listitem>
<para>
Create an appropriate response message by calling
<methodname>andRespond(ResponseCreator)</methodname>, possibly by using the default
<interfacename>ResponseCreator</interfacename> implementations provided in
<classname>ResponseCreators</classname> (which can be statically imported).
</para>
</listitem>
<listitem>
<para>
Use the <classname>WebServiceTemplate</classname> as normal, either directly of through
client code.
</para>
</listitem>
<listitem>
<para>
Call <methodname>MockWebServiceServer.verify()</methodname> to make sure that all
expectations have been met.
</para>
</listitem>
</orderedlist>
</para>
<note>
<para>
Note that the <classname>MockWebServiceServer</classname> (and related classes) offers a
'fluent' API, so you can typically use the Code Completion features (i.e. ctrl-space) in your IDE
to guide you through the process of setting up the mock server.
</para>
</note>
<note>
<para>
Also note that you rely on the standard logging features available in Spring Web Services in your
unit tests.
Sometimes it might be useful to inspect the request or response message to find out why a
particular tests failed.
See <xref linkend="logging"/> for more information.
</para>
</note>
<para>
Consider, for example, this Web service client class:
</para>
<programlistingco>
<areaspec>
<area xml:id="client.test.client.gateway" coords="3"/>
<area xml:id="client.test.client.request" coords="6"/>
<area xml:id="client.test.client.response" coords="10"/>
</areaspec>
<programlisting><![CDATA[import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
public class CustomerClient extends WebServiceGatewaySupport {
public int getCustomerCount() {
CustomerCountRequest request = new CustomerCountRequest();
request.setCustomerName("John Doe");
CustomerCountResponse response =
(CustomerCountResponse) getWebServiceTemplate().marshalSendAndReceive(request);
return response.getCustomerCount();
}
}]]></programlisting>
<calloutlist>
<callout arearefs="client.test.client.gateway">
<para>
The <classname>CustomerClient</classname> extends
<classname>WebServiceGatewaySupport</classname>, which provides it with a
<property>webServiceTemplate</property> property.
</para>
</callout>
<callout arearefs="client.test.client.request">
<para>
<classname>CustomerCountRequest</classname> is an object supported by a marshaller.
For instance, it can have a <interfacename>@XmlRootElement</interfacename> annotation
to be supported by JAXB2.
</para>
</callout>
<callout arearefs="client.test.client.response">
<para>
The <classname>CustomerClient</classname> uses the <classname>WebServiceTemplate</classname>
offered by <classname>WebServiceGatewaySupport</classname> to marshal the request object
into a SOAP message, and sends that to the web service.
The response object is unmarshalled into a <classname>CustomerCountResponse</classname>.
</para>
</callout>
</calloutlist>
</programlistingco>
<para>
A typical test for <classname>CustomerClient</classname> would look like this:
</para>
<programlistingco>
<areaspec>
<areaset xml:id="client.test.test.imports">
<area xml:id="client.test.test.imports.server" coords="13"/>
<area xml:id="client.test.test.imports.requestMatchers" coords="14"/>
<area xml:id="client.test.test.imports.responseCreators" coords="15"/>
</areaset>
<areaset xml:id="client.test.test.spring">
<area xml:id="client.test.test.spring.runwith" coords="17"/>
<area xml:id="client.test.test.spring.configuration" coords="18"/>
</areaset>
<area xml:id="client.test.test.client" coords="22"/>
<area xml:id="client.test.test.mockserver" coords="24"/>
<area xml:id="client.test.test.expectAndRespond" coords="42"/>
<areaset xml:id="client.test.test.client.invoke">
<area xml:id="client.test.test.client.invoke.actual" coords="44"/>
<area xml:id="client.test.test.client.invoke.assert" coords="45"/>
</areaset>
<area xml:id="client.test.test.client.verify" coords="47"/>
</areaspec>
<programlisting><![CDATA[import javax.xml.transform.Source;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.xml.transform.StringSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import org.springframework.ws.test.client.MockWebServiceServer;
import static org.springframework.ws.test.client.RequestMatchers.*;
import static org.springframework.ws.test.client.ResponseCreators.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("integration-test.xml")
public class CustomerClientIntegrationTest {
@Autowired
private CustomerClient client;
private MockWebServiceServer mockServer;
@Before
public void createServer() throws Exception {
mockServer = MockWebServiceServer.createServer(client);
}
@Test
public void customerClient() throws Exception {
Source requestPayload = new StringSource(
"<customerCountRequest xmlns='http://springframework.org/spring-ws'>" +
"<customerName>John Doe</customerName>" +
"</customerCountRequest>");
Source responsePayload = new StringSource(
"<customerCountResponse xmlns='http://springframework.org/spring-ws'>" +
"<customerCount>10</customerCount>" +
"</customerCountResponse>");
mockServer.expect(payload(requestPayload)).andRespond(withPayload(responsePayload));
int result = client.getCustomerCount();
assertEquals(10, result);
mockServer.verify();
}
}]]></programlisting>
<calloutlist>
<callout arearefs="client.test.test.imports">
<para>
The <classname>CustomerClientIntegrationTest</classname> imports the
<classname>MockWebServiceServer</classname>, and statically imports
<classname>RequestMatchers</classname> and <classname>ResponseCreators</classname>.
</para>
</callout>
<callout arearefs="client.test.test.spring">
<para>
This test uses the standard testing facilities provided in the Spring Framework.
This is not required, but is generally the easiest way to set up the test.
</para>
</callout>
<callout arearefs="client.test.test.client">
<para>
The <classname>CustomerClient</classname> is configured in
<filename>integration-test.xml</filename>, and wired into this test using
<interfacename>@Autowired</interfacename>.
</para>
</callout>
<callout arearefs="client.test.test.mockserver">
<para>
In a <interfacename>@Before</interfacename> method, we create a
<classname>MockWebServiceServer</classname> by using the
<methodname>createServer</methodname> factory method.
</para>
</callout>
<callout arearefs="client.test.test.expectAndRespond">
<para>
We define expectations by calling <methodname>expect()</methodname> with a
<methodname>payload()</methodname> <interfacename>RequestMatcher</interfacename> provided
by the statically imported <classname>RequestMatchers</classname> (see <xref
linkend="client-test-request-matcher"/>).
</para>
<para>
We also set up a response by calling <methodname>andRespond()</methodname> with a
<methodname>withPayload()</methodname> <interfacename>ResponseCreator</interfacename>
provided by the statically imported <classname>ResponseCreators</classname> (see
<xref linkend="client-test-response-creator"/>).
</para>
<para>
This part of the test might look a bit confusing, but the Code Completion features of your
IDE are of great help.
After typing <methodname>expect(</methodname>, simply type ctrl-space, and your IDE will
provide you with a list of possible request matching strategies, provided you
statically imported <classname>RequestMatchers</classname>.
The same applies to <methodname>andRespond(</methodname>, provided you statically imported
<classname>ResponseCreators</classname>.
</para>
</callout>
<callout arearefs="client.test.test.client.invoke">
<para>
We call <methodname>getCustomerCount()</methodname> on the
<classname>CustomerClient</classname>, thus using the
<classname>WebServiceTemplate</classname>.
The template has been set up for 'testing mode' by now, so no real
(HTTP) connection is made by this method call.
We also make some JUnit assertions based on the result of the method call.
</para>
</callout>
<callout arearefs="client.test.test.client.verify">
<para>
We call <methodname>verify()</methodname> on the
<classname>MockWebServiceServer</classname>, thus verifying that the expected
message was actually received.
</para>
</callout>
</calloutlist>
</programlistingco>
</section>
<section xml:id="client-test-request-matcher">
<title><interfacename>RequestMatcher</interfacename> and <classname>RequestMatchers</classname></title>
<para>
To verify whether the request message meets certain expectations, the
<classname>MockWebServiceServer</classname> uses the <interfacename>RequestMatcher</interfacename>
strategy interface.
The contract defined by this interface is quite simple:
</para>
<programlisting><![CDATA[public interface RequestMatcher {
void match(URI uri,
WebServiceMessage request)
throws IOException,
AssertionError;
}]]></programlisting>
<para>
You can write your own implementations of this interface, throwing
<classname>AssertionError</classname>s when the message does not meet your expectations, but you
certainly do not have to.
The <classname>RequestMatchers</classname> class provides standard
<interfacename>RequestMatcher</interfacename> implementations for you to use in your tests.
You will typically statically import this class.
</para>
<para>
The <classname>RequestMatchers</classname> class provides the following request matchers:
<informaltable>
<tgroup cols="2">
<thead>
<row>
<entry><classname>RequestMatchers</classname> method</entry>
<entry>Description</entry>
</row>
</thead>
<tbody>
<row>
<entry><methodname>anything()</methodname></entry>
<entry>Expects any sort of request.</entry>
</row>
<row>
<entry><methodname>payload()</methodname></entry>
<entry>Expects a given request payload.</entry>
</row>
<row>
<entry><methodname>validPayload()</methodname></entry>
<entry>Expects the request payload to validate against given XSD schema(s).</entry>
</row>
<row>
<entry><methodname>xpath()</methodname></entry>
<entry>
Expects a given XPath expression to exist, not exist, or evaluate to a given
value.
</entry>
</row>
<row>
<entry><methodname>soapHeader()</methodname></entry>
<entry>Expects a given SOAP header to exist in the request message.</entry>
</row>
<row>
<entry><methodname>connectionTo()</methodname></entry>
<entry>Expects a connection to the given URL.</entry>
</row>
</tbody>
</tgroup>
</informaltable>
You can set up multiple request expectations by chaining <methodname>andExpect()</methodname> calls,
like so:
<programlisting>mockServer.expect(connectionTo("http://example.com")).
andExpect(payload(expectedRequestPayload)).
andExpect(validPayload(schemaResource)).
andRespond(...);
</programlisting>
</para>
<para>
For more information on the request matchers provided by <classname>RequestMatchers</classname>,
refer to the class level Javadoc.
</para>
</section>
<section xml:id="client-test-response-creator">
<title><interfacename>ResponseCreator</interfacename> and <classname>ResponseCreators</classname></title>
<para>
When the request message has been verified and meets the defined expectations, the
<classname>MockWebServiceServer</classname> will create a response message for the
<classname>WebServiceTemplate</classname> to consume.
The server uses the <interfacename>ResponseCreator</interfacename>
strategy interface for this purpose:
</para>
<programlisting><![CDATA[public interface ResponseCreator {
WebServiceMessage createResponse(URI uri,
WebServiceMessage request,
WebServiceMessageFactory messageFactory)
throws IOException;
}]]></programlisting>
<para>
Once again you can write your own implementations of this interface, creating a response message
by using the message factory, but you certainly do not have to, as the
<classname>ResponseCreators</classname> class provides standard
<interfacename>ResponseCreator</interfacename> implementations for you to use in your tests.
You will typically statically import this class.
</para>
<para>
The <classname>ResponseCreators</classname> class provides the following responses:
<informaltable>
<tgroup cols="2">
<thead>
<row>
<entry><classname>ResponseCreators</classname> method</entry>
<entry>Description</entry>
</row>
</thead>
<tbody>
<row>
<entry><methodname>withPayload()</methodname></entry>
<entry>Creates a response message with a given payload.</entry>
</row>
<row>
<entry><methodname>withError()</methodname></entry>
<entry>
Creates an error in the response connection.
This method gives you the opportunity to test your error handling.
</entry>
</row>
<row>
<entry><methodname>withException()</methodname></entry>
<entry>
Throws an exception when reading from the response connection.
This method gives you the opportunity to test your exception handling.
</entry>
</row>
<row>
<entry>
<methodname>withMustUnderstandFault()</methodname>,
<methodname>withClientOrSenderFault()</methodname>,
<methodname>withServerOrReceiverFault()</methodname>, and
<methodname>withVersionMismatchFault()</methodname>
</entry>
<entry>
Creates a response message with a given SOAP fault.
This method gives you the opportunity to test your Fault handling.
</entry>
</row>
</tbody>
</tgroup>
</informaltable>
</para>
<para>
For more information on the request matchers provided by <classname>RequestMatchers</classname>,
refer to the class level Javadoc.
</para>
</section>
</section>
</chapter>

View File

@@ -1,455 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<chapter xml:id="common"
xmlns="http://docbook.org/ns/docbook" version="5.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd">
<title>Shared components</title>
<para>
In this chapter, we will explore the components which are shared between client- and server-side
Spring-WS development. These interfaces and classes represent the building blocks of Spring-WS, so
it is important to understand what they do, even if you do not use them directly.
</para>
<section xml:id="web-service-messages">
<title>Web service messages</title>
<section xml:id="web-service-message">
<title><interfacename>WebServiceMessage</interfacename></title>
<para>
One of the core interfaces of Spring Web Services is the <interfacename>WebServiceMessage</interfacename>.
This interface represents a protocol-agnostic XML message. The interface contains methods that provide
access to the payload of the message, in the form of a
<interfacename>javax.xml.transform.Source</interfacename> or a
<interfacename>javax.xml.transform.Result</interfacename>. <interfacename>Source</interfacename> and
<interfacename>Result</interfacename> are tagging interfaces that represent an abstraction over XML
input and output. Concrete implementations wrap various XML representations, as indicated in the
following table.
<informaltable>
<tgroup cols="2">
<thead>
<row>
<entry>Source/Result implementation</entry>
<entry>Wraps XML representation</entry>
</row>
</thead>
<tbody>
<row>
<entry><classname>javax.xml.transform.dom.DOMSource</classname></entry>
<entry><interfacename>org.w3c.dom.Node</interfacename></entry>
</row>
<row>
<entry><classname>javax.xml.transform.dom.DOMResult</classname></entry>
<entry><interfacename>org.w3c.dom.Node</interfacename></entry>
</row>
<row>
<entry><classname>javax.xml.transform.sax.SAXSource</classname></entry>
<entry><classname>org.xml.sax.InputSource</classname> and
<interfacename>org.xml.sax.XMLReader</interfacename>
</entry>
</row>
<row>
<entry><classname>javax.xml.transform.sax.SAXResult</classname></entry>
<entry><interfacename>org.xml.sax.ContentHandler</interfacename></entry>
</row>
<row>
<entry><classname>javax.xml.transform.stream.StreamSource</classname></entry>
<entry>
<classname>java.io.File</classname>, <classname>java.io.InputStream</classname>, or
<classname>java.io.Reader</classname>
</entry>
</row>
<row>
<entry>
<classname>javax.xml.transform.stream.StreamResult</classname>
</entry>
<entry>
<classname>java.io.File</classname>, <classname>java.io.OutputStream</classname>, or
<classname>java.io.Writer</classname>
</entry>
</row>
</tbody>
</tgroup>
</informaltable>
In addition to reading from and writing to the payload, a Web service message can write itself to an
output stream.
</para>
</section>
<section xml:id="soap-message">
<title><interfacename>SoapMessage</interfacename></title>
<para>
The <interfacename>SoapMessage</interfacename> is a subclass of
<interfacename>WebServiceMessage</interfacename>. It contains SOAP-specific methods, such as getting
SOAP Headers, SOAP Faults, etc.
Generally, your code should not be dependent on <interfacename>SoapMessage</interfacename>, because
the content of the SOAP Body (the payload of the message) can be obtained via
<methodname>getPayloadSource()</methodname> and <methodname>getPayloadResult()</methodname> in the
<interfacename>WebServiceMessage</interfacename>.
Only when it is necessary to perform SOAP-specific actions, such as adding a header, getting an
attachment, etc., should you need to cast <interfacename>WebServiceMessage</interfacename> to
<interfacename>SoapMessage</interfacename>.
</para>
</section>
<section xml:id="message-factories">
<title>Message Factories</title>
<para>
Concrete message implementations are created by a <interfacename>WebServiceMessageFactory</interfacename>.
This factory can create an empty message, or read a message based on an input stream. There are two
concrete implementations of <interfacename>WebServiceMessageFactory</interfacename>; one is based on
SAAJ, the SOAP with Attachments API for Java, the other based on Axis 2's AXIOM, the AXis Object Model.
</para>
<section>
<title><classname>SaajSoapMessageFactory</classname></title>
<para>
The <classname>SaajSoapMessageFactory</classname> uses the SOAP with Attachments API for Java to
create <classname>SoapMessage</classname> implementations. <acronym>SAAJ</acronym> is part of
<acronym>J2EE</acronym> 1.4, so it should be supported under most modern application servers.
Here is an overview of the <acronym>SAAJ</acronym> versions supplied
by common application servers:
<informaltable>
<tgroup cols="2">
<thead>
<row>
<entry>Application Server</entry>
<entry><acronym>SAAJ</acronym> Version</entry>
</row>
</thead>
<tbody>
<row>
<entry>BEA WebLogic 8</entry>
<entry>1.1</entry>
</row>
<row>
<entry>BEA WebLogic 9</entry>
<entry>1.1/1.2<footnote>
<para>
Weblogic 9 has a known bug in the <acronym>SAAJ</acronym> 1.2
implementation: it implement all the 1.2 interfaces, but throws a
<classname>UnsupportedOperationException</classname> when called.
Spring Web Services has a workaround: it uses <acronym>SAAJ</acronym> 1.1
when operating on WebLogic 9.
</para>
</footnote></entry>
</row>
<row>
<entry>IBM WebSphere 6</entry>
<entry>1.2</entry>
</row>
<row>
<entry>SUN Glassfish 1</entry>
<entry>1.3</entry>
</row>
</tbody>
</tgroup>
</informaltable>
Additionally, Java SE 6 includes <acronym>SAAJ</acronym> 1.3.
You wire up a
<classname>SaajSoapMessageFactory</classname> like so:
<programlisting><![CDATA[<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory" />]]></programlisting>
</para>
<note>
<para>
<acronym>SAAJ</acronym> is based on DOM, the Document Object Model. This means that all SOAP messages are
stored <emphasis>in memory</emphasis>. For larger SOAP messages, this may not be very performant.
In that case, the <classname>AxiomSoapMessageFactory</classname> might be more applicable.
</para>
</note>
</section>
<section>
<title><classname>AxiomSoapMessageFactory</classname></title>
<para>
The <classname>AxiomSoapMessageFactory</classname> uses the AXis 2 Object Model to create
<interfacename>SoapMessage</interfacename> implementations. <acronym>AXIOM</acronym> is based on
<acronym>StAX</acronym>, the Streaming API for XML. StAX provides a pull-based mechanism for
reading XML messages, which can be more efficient for larger messages.
</para>
<para>
To increase reading performance on the <classname>AxiomSoapMessageFactory</classname>,
you can set the <property>payloadCaching</property> property to false (default is true).
This will read the contents of the SOAP body directly from the socket stream.
When this setting is enabled, the payload can only be read once.
This means that you have to make sure that any pre-processing (logging etc.) of the message does
not consume it.
</para>
<para>
You use the <classname>AxiomSoapMessageFactory</classname> as follows:
<programlisting><![CDATA[
<bean id="messageFactory" class="org.springframework.ws.soap.axiom.AxiomSoapMessageFactory">
<property name="payloadCaching" value="true"/>
</bean>]]></programlisting>
</para>
<para>
In addition to payload caching, <acronym>AXIOM</acronym> also supports full streaming messages,
as defined in the <interfacename>StreamingWebServiceMessage</interfacename>.
This means that the payload can be directly set on the response message, rather than being written
to a DOM tree or buffer.
</para>
<para>
Full streaming for <acronym>AXIOM</acronym> is used when a handler method returns a
<acronym>JAXB2</acronym>-supported object.
It will automatically set this marshalled object into the response message, and write it out to
the outgoing socket stream when the response is going out.
</para>
<para>
For more information about full streaming, refer to the class-level Javadoc for
<interfacename>StreamingWebServiceMessage</interfacename> and
<interfacename>StreamingPayload</interfacename>.
</para>
</section>
<section xml:id="soap_11_or_12">
<title><acronym>SOAP</acronym> 1.1 or 1.2</title>
<para>
Both the <classname>SaajSoapMessageFactory</classname> and the
<classname>AxiomSoapMessageFactory</classname> have a <property>soapVersion</property> property,
where you can inject a <interfacename>SoapVersion</interfacename> constant. By default, the version
is 1.1, but you can set it to 1.2 like so:
</para>
<programlisting><![CDATA[
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<property name="soapVersion">
<util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_12"/>
</property>
</bean>
</beans>]]></programlisting>
<para>
In the example above, we define a <classname>SaajSoapMessageFactory</classname> that only accepts
<acronym>SOAP</acronym> 1.2 messages.
</para>
<caution>
<para>
Even though both versions of <acronym>SOAP</acronym> are quite similar in format, the 1.2
version is not backwards compatible with 1.1 because it uses a different XML namespace.
Other major differences between <acronym>SOAP</acronym> 1.1 and 1.2 include the different structure
of a Fault, and the fact that <literal>SOAPAction</literal> HTTP headers are effectively
deprecated, thought they still work.
</para>
<para>
One important thing to note with <acronym>SOAP</acronym> version numbers, or WS-* specification
version numbers in general, is that the latest version of a specification is
generally not the most popular version.
For <acronym>SOAP</acronym>, this means that currently, the best version to use is 1.1.
Version 1.2 might become more popular in the future, but currently 1.1 is the safest bet.
</para>
</caution>
</section>
</section>
<section xml:id="message-context">
<title><interfacename>MessageContext</interfacename></title>
<para>
Typically, messages come in pairs: a request and a response. A request is created on the client-side,
which is sent over some transport to the server-side, where a response is generated. This response gets
sent back to the client, where it is read.
</para>
<para>
In Spring Web Services, such a conversation is contained in a
<interfacename>MessageContext</interfacename>, which has properties to get request and response
messages.
On the client-side, the message context is created by the <link linkend="client-web-service-template">
<classname>WebServiceTemplate</classname></link>.
On the server-side, the message context is read from the transport-specific input stream.
For example, in HTTP, it is read from the <interfacename>HttpServletRequest</interfacename> and the
response is written back to the <interfacename>HttpServletResponse</interfacename>.
</para>
</section>
</section>
<section xml:id="transport-context">
<title><interfacename>TransportContext</interfacename></title>
<para>
One of the key properties of the SOAP protocol is that it tries to be transport-agnostic. This is why, for
instance, Spring-WS does not support mapping messages to endpoints by HTTP request URL, but
rather by mesage content.
</para>
<para>
However, sometimes it is necessary to get access to the underlying transport, either on the client or server
side. For this, Spring Web Services has the <interfacename>TransportContext</interfacename>. The transport
context allows access to the underlying <interfacename>WebServiceConnection</interfacename>, which typically
is a <classname>HttpServletConnection</classname> on the server side; or a
<classname>HttpUrlConnection</classname> or <classname>CommonsHttpConnection</classname> on the client side.
For example, you can obtain the IP address of the current request in a server-side endpoint or
interceptor like so:
</para>
<programlisting><![CDATA[
TransportContext context = TransportContextHolder.getTransportContext();
HttpServletConnection connection = (HttpServletConnection )context.getConnection();
HttpServletRequest request = connection.getHttpServletRequest();
String ipAddress = request.getRemoteAddr();]]></programlisting>
</section>
<section xml:id="xpath">
<title>Handling XML With XPath</title>
<para>
One of the best ways to handle XML is to use XPath.
Quoting <xref linkend="effective-xml"/>, item 35:
</para>
<blockquote>
<para>
XPath is a fourth generation declarative language that allows you to specify which nodes you want to
process without specifying exactly how the processor is supposed to navigate to those nodes. XPath's
data model is very well designed to support exactly what almost all developers want from XML. For
instance, it merges all adjacent text including that in CDATA sections, allows values to be
calculated that skip over comments and processing instructions` and include text from child and
descendant elements, and requires all external entity references to be resolved. In practice, XPath
expressions tend to be much more robust against unexpected but perhaps insignificant changes in the
input document.
</para>
<attribution>Elliotte Rusty Harold</attribution>
</blockquote>
<para>
Spring Web Services has two ways to use XPath within your application: the faster
<interfacename>XPathExpression</interfacename> or the more flexible <classname>XPathTemplate</classname>.
</para>
<section xml:id="xpath-expression">
<title><interfacename>XPathExpression</interfacename></title>
<para>
The <interfacename>XPathExpression</interfacename> is an abstraction over a compiled XPath expression,
such as the Java 5 <interfacename>javax.xml.xpath.XPathExpression</interfacename>, or the Jaxen
<classname>XPath</classname> class.
To construct an expression in an application context, there is the
<classname>XPathExpressionFactoryBean</classname>. Here is an example which uses this factory bean:
</para>
<programlisting><![CDATA[<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="nameExpression" class="org.springframework.xml.xpath.XPathExpressionFactoryBean">
<property name="expression" value="/Contacts/Contact/Name"/>
</bean>
<bean id="myEndpoint" class="sample.MyXPathClass">
<constructor-arg ref="nameExpression"/>
</bean>
</beans>]]></programlisting>
<para>
The expression above does not use namespaces, but we could set those using the
<property>namespaces</property> property of the factory bean. The expression
can be used in the code as follows:
</para>
<programlisting><![CDATA[package sample;
public class MyXPathClass {
private final XPathExpression nameExpression;
public MyXPathClass(XPathExpression nameExpression) {
this.nameExpression = nameExpression;
}
public void doXPath(Document document) {
String name = nameExpression.evaluateAsString(document.getDocumentElement());
System.out.println("Name: " + name);
}
}]]></programlisting>
<para>
For a more flexible approach, you can use a <interfacename>NodeMapper</interfacename>, which is similar
to the <interfacename>RowMapper</interfacename> in Spring's JDBC support. The following
example shows how we can use it:
</para>
<programlisting><![CDATA[package sample;
public class MyXPathClass {
private final XPathExpression contactExpression;
public MyXPathClass(XPathExpression contactExpression) {
this.contactExpression = contactExpression;
}
public void doXPath(Document document) {
List contacts = contactExpression.evaluate(document,
new NodeMapper() {
public Object mapNode(Node node, int nodeNum) throws DOMException {
Element contactElement = (Element) node;
Element nameElement = (Element) contactElement.getElementsByTagName("Name").item(0);
Element phoneElement = (Element) contactElement.getElementsByTagName("Phone").item(0);
return new Contact(nameElement.getTextContent(), phoneElement.getTextContent());
}
});
]]><lineannotation>// do something with list of Contact objects</lineannotation><![CDATA[
}
}]]></programlisting>
<para>
Similar to mapping rows in Spring JDBC's <interfacename>RowMapper</interfacename>, each result node is
mapped using an anonymous inner class. In this case, we create a <classname>Contact</classname> object,
which we use later on.
</para>
</section>
<section xml:id="xpath-template">
<title><classname>XPathTemplate</classname></title>
<para>
The <interfacename>XPathExpression</interfacename> only allows you to evaluate a single, pre-compiled
expression. A more flexible, though slower, alternative is the <classname>XpathTemplate</classname>.
This class follows the common template pattern used throughout Spring (JdbcTemplate, JmsTemplate, etc.).
Here is an example:
</para>
<programlisting><![CDATA[package sample;
public class MyXPathClass {
private XPathOperations template = new Jaxp13XPathTemplate();
public void doXPath(Source source) {
String name = template.evaluateAsString("/Contacts/Contact/Name", request);
]]><lineannotation>// do something with name</lineannotation><![CDATA[
}
}]]></programlisting>
</section>
</section>
<section xml:id="logging">
<title>Message Logging and Tracing</title>
<para>
When developing or debugging a Web service, it can be quite useful to look at the content of a (SOAP)
message when it arrives, or just before it is sent. Spring Web Services offer this functionality, via the
standard Commons Logging interface.
</para>
<caution>
<para>
Make sure to use Commons Logging version 1.1 or higher. Earlier versions have class loading issues, and
do not integrate with the Log4J TRACE level.
</para>
</caution>
<para>
To log all server-side messages, simply set the
<literal>org.springframework.ws.server.MessageTracing</literal> logger to level DEBUG or TRACE. On the debug
level, only the payload root element is logged; on the TRACE level, the entire message content.
If you only want to log sent messages, use the
<literal>org.springframework.ws.server.MessageTracing.sent</literal> logger; or
<literal>org.springframework.ws.server.MessageTracing.received</literal> to log received messages.
</para>
<para>
On the client-side, similar loggers exist:
<literal>org.springframework.ws.client.MessageTracing.sent</literal> and
<literal>org.springframework.ws.client.MessageTracing.received</literal>.
</para>
<para>
Here is an example <filename>log4j.properties</filename> configuration, logging the full content of
sent messages on the client side, and only the payload root element for client-side received messages. On
the server-side, the payload root is logged for both sent and received messages:
</para>
<programlisting><![CDATA[log4j.rootCategory=INFO, stdout
log4j.logger.org.springframework.ws.client.MessageTracing.sent=TRACE
log4j.logger.org.springframework.ws.client.MessageTracing.received=DEBUG
log4j.logger.org.springframework.ws.server.MessageTracing=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%p [%c{3}] %m%n]]></programlisting>
<para>
With this configuration, a typical output will be:
</para>
<screen><![CDATA[TRACE [client.MessageTracing.sent] Sent request [<SOAP-ENV:Envelope xmlns:SOAP-ENV="...
DEBUG [server.MessageTracing.received] Received request [SaajSoapMessage {http://example.com}request] ...
DEBUG [server.MessageTracing.sent] Sent response [SaajSoapMessage {http://example.com}response] ...
DEBUG [client.MessageTracing.received] Received response [SaajSoapMessage {http://example.com}response] ...]]></screen>
</section>
</chapter>

View File

@@ -1,96 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<book xml:id="spring-framework-reference"
xmlns="http://docbook.org/ns/docbook" version="5.0"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd">
<info>
<title>Spring Web Services Reference Documentation</title>
<productname>Spring Web Services</productname>
<releaseinfo>${version}</releaseinfo>
<authorgroup>
<author>
<personname>
<firstname>Arjen</firstname>
<surname>Poutsma</surname>
</personname>
</author>
<author>
<personname>
<firstname>Rick</firstname>
<surname>Evans</surname>
</personname>
</author>
<author>
<personname>
<firstname>Tareq</firstname>
<surname>Abed Rabbo</surname>
</personname>
</author>
</authorgroup>
<copyright>
<year>2005-2014</year>
</copyright>
<legalnotice>
<para>
Copies of this document may be made for your own use and for distribution
to others, provided that you do not charge any fee for such copies and
further provided that each copy contains this Copyright Notice, whether
distributed in print or electronically.
</para>
</legalnotice>
</info>
<toc/>
<xi:include href="preface.xml"/>
<part>
<title>Introduction</title>
<partintro>
<para>
This first part of the reference documentation
<link linkend="what-is-spring-ws">is an overview</link> of
Spring Web Services and the underlying concepts. Spring-WS is
then introduced, and <link linkend="why-contract-first">the concepts</link>
behind contract-first Web service development are explained.
</para>
</partintro>
<xi:include href="what-is-spring-ws.xml"/>
<xi:include href="why-contract-first.xml"/>
<xi:include href="tutorial.xml"/>
</part>
<part>
<title>Reference</title>
<partintro>
<para>
This part of the reference documentation details the various components
that comprise Spring Web Services. This includes
<link linkend="common">a chapter</link> that discusses the parts common
to both client- and server-side WS, a chapter devoted to the specifics
of <link linkend="server">writing server-side Web services</link>,
a chapter about using Web services on
<link linkend="client">the client-side</link>, and a chapters on using
<link linkend="security">WS-Security</link>.
</para>
</partintro>
<xi:include href="common.xml"/>
<xi:include href="server.xml"/>
<xi:include href="client.xml"/>
<xi:include href="security.xml"/>
</part>
<part xml:id="resources">
<title>Other Resources</title>
<partintro>
<para>
In addition to this reference documentation, there exist a number of
other resources that may help you learn how to use Spring Web Services.
These additional, third-party resources are enumerated in this section.
</para>
</partintro>
<xi:include href="bibliography.xml"/>
</part>
</book>

View File

@@ -1,30 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<preface xml:id="overview"
xmlns="http://docbook.org/ns/docbook" version="5.0"
xmlns:xl="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd
http://www.w3.org/1999/xlink http://www.docbook.org/xml/5.0/xsd/xlink.xsd">
<title>Preface</title>
<para>
In the current age of Service Oriented Architectures, more and more people are using Web Services to
connect previously unconnected systems. Initially, Web services were considered to be just another way to do
a Remote Procedure Call (RPC). Over time however, people found out that there is a big difference
between RPCs and Web services. Especially when interoperability with other platforms is important, it is often
better to send encapsulated XML documents, containing all the data necessary to process the request.
Conceptually, XML-based Web services are better off being compared to message queues rather than remoting
solutions.
Overall, XML should be considered the platform-neutral representation of data, the
<foreignphrase>interlingua</foreignphrase> of SOA. When developing or using Web services, the focus should be
on this XML, and not on Java.
</para>
<para>
Spring Web Services focuses on creating these document-driven Web services.
Spring Web Services facilitates contract-first SOAP service development, allowing for the creation of
flexible web services using one of the many ways to manipulate XML payloads.
Spring-WS provides a powerful <link linkend="server">message dispatching framework</link>, a <link
linkend="security">WS-Security</link> solution that integrates with your existing application security
solution, and a <link linkend="client">Client-side API</link> that follows the familiar Spring template pattern.
</para>
</preface>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,898 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<chapter xml:id="tutorial"
xmlns="http://docbook.org/ns/docbook" version="5.0"
xmlns:xl="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd
http://www.w3.org/1999/xlink http://www.docbook.org/xml/5.0/xsd/xlink.xsd">
<title>Writing Contract-First Web Services</title>
<section>
<title>Introduction</title>
<para>
This tutorial shows you how to write
<link linkend="why-contract-first">contract-first Web services</link>, that is,
developing web services that start with the XML Schema/WSDL contract first
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 <link linkend="tutorial-creating-project">second part</link>
focuses on implementing this contract using Spring-WS .
</para>
<para>
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.
</para>
<para>
In this tutorial, we will define a Web service that is created by a Human Resources
department. Clients can send holiday request forms to this service to book a holiday.
</para>
</section>
<section>
<title>Messages</title>
<para>
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.
</para>
<section>
<title>Holiday</title>
<para>
In the scenario, we have to deal with holiday requests, so it makes sense
to determine what a holiday looks like in XML:
</para>
<programlisting><![CDATA[
<Holiday xmlns="http://mycompany.com/hr/schemas">
<StartDate>2006-07-03</StartDate>
<EndDate>2006-07-07</EndDate>
</Holiday>]]></programlisting>
<para>
A holiday consists of a start date and an end date. We have also decided to
use the standard
<link xl:href="http://www.cl.cam.ac.uk/~mgk25/iso-time.html">ISO 8601</link>
date format for the dates, because that will save a lot of parsing hassle.
We have also added a namespace to the element, to make sure our elements
can used within other XML documents.
</para>
</section>
<section>
<title>Employee</title>
<para>
There is also the notion of an employee in the scenario. Here is what it
looks like in XML:
</para>
<programlisting><![CDATA[
<Employee xmlns="http://mycompany.com/hr/schemas">
<Number>42</Number>
<FirstName>Arjen</FirstName>
<LastName>Poutsma</LastName>
</Employee>]]></programlisting>
<para>
We have used the same namespace as before. If this
<literal>&lt;Employee/&gt;</literal> element could be used in other
scenarios, it might make sense to use a different namespace, such as
<literal>http://mycompany.com/employees/schemas</literal>.
</para>
</section>
<section>
<title>HolidayRequest</title>
<para>
Both the holiday and employee element can be put in a
<literal>&lt;HolidayRequest/&gt;</literal>:
</para>
<programlisting><![CDATA[
<HolidayRequest xmlns="http://mycompany.com/hr/schemas">
<Holiday>
<StartDate>2006-07-03</StartDate>
<EndDate>2006-07-07</EndDate>
</Holiday>
<Employee>
<Number>42</Number>
<FirstName>Arjen</FirstName>
<LastName>Poutsma</LastName>
</Employee>
</HolidayRequest>]]></programlisting>
<para>
The order of the two elements does not matter: <literal>&lt;Employee/&gt;</literal>
could have been the first element just as well. What is important is
that all of the data is there. In fact, the data is the only thing
that is important: we are taking a <emphasis>data-driven</emphasis>
approach.
</para>
</section>
</section>
<section xml:id="tutorial.xsd">
<title>Data Contract</title>
<para>
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:
</para>
<itemizedlist>
<listitem><para>DTDs</para></listitem>
<listitem><para><link xl:href="http://www.w3.org/XML/Schema">XML Schema (XSD)</link></para></listitem>
<listitem><para><link xl:href="http://www.relaxng.org/">RELAX NG</link></para></listitem>
<listitem><para><link xl:href="http://www.schematron.com/">Schematron</link></para></listitem>
</itemizedlist>
<para>
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.
</para>
<para>
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.
</para>
<para>
Using the sample described above, we end up with the following
generated schema:
</para>
<programlisting><![CDATA[<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace="http://mycompany.com/hr/schemas"
xmlns:hr="http://mycompany.com/hr/schemas">
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:sequence>
<xs:element ref="hr:Holiday"/>
<xs:element ref="hr:Employee"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Holiday">
<xs:complexType>
<xs:sequence>
<xs:element ref="hr:StartDate"/>
<xs:element ref="hr:EndDate"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="StartDate" type="xs:NMTOKEN"/>
<xs:element name="EndDate" type="xs:NMTOKEN"/>
<xs:element name="Employee">
<xs:complexType>
<xs:sequence>
<xs:element ref="hr:Number"/>
<xs:element ref="hr:FirstName"/>
<xs:element ref="hr:LastName"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Number" type="xs:integer"/>
<xs:element name="FirstName" type="xs:NCName"/>
<xs:element name="LastName" type="xs:NCName"/>
</xs:schema>]]></programlisting>
<para>
This generated schema obviously can be improved. The first thing
to notice is that every type has a root-level element declaration.
This means that the Web service should be able to accept all of
these elements as data. This is not desirable: we only want to
accept a <literal>&lt;HolidayRequest/&gt;</literal>. By removing
the wrapping element tags (thus keeping the types), and inlining
the results, we can accomplish this.
</para>
<programlisting><![CDATA[<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:hr="http://mycompany.com/hr/schemas"
elementFormDefault="qualified"
targetNamespace="http://mycompany.com/hr/schemas">
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="Holiday" type="hr:HolidayType"/>
<xs:element name="Employee" type="hr:EmployeeType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="HolidayType">
<xs:sequence>
<xs:element name="StartDate" type="xs:NMTOKEN"/>
<xs:element name="EndDate" type="xs:NMTOKEN"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="EmployeeType">
<xs:sequence>
<xs:element name="Number" type="xs:integer"/>
<xs:element name="FirstName" type="xs:NCName"/>
<xs:element name="LastName" type="xs:NCName"/>
</xs:sequence>
</xs:complexType>
</xs:schema>]]></programlisting>
<para>
The schema still has one problem: with a schema like this, you
can expect the following messages to validate:
</para>
<programlisting>
<![CDATA[<HolidayRequest xmlns="http://mycompany.com/hr/schemas">
<Holiday>
<StartDate>this is not a date</StartDate>
<EndDate>neither is this</EndDate>
</Holiday>
]]><lineannotation>&lt;!-- ... --&gt;</lineannotation><![CDATA[
</HolidayRequest>]]></programlisting>
<para>
Clearly, we must make sure that the start and end date are really dates.
XML Schema has an excellent built-in <literal>date</literal> type which
we can use. We also change the <literal>NCName</literal>s to
<literal>string</literal>s. Finally, we change the <literal>sequence</literal> in
<literal>&lt;HolidayRequest/&gt;</literal> to <literal>all</literal>.
This tells the XML parser that the order of
<literal>&lt;Holiday/&gt;</literal> and
<literal>&lt;Employee/&gt;</literal> is not significant. Our final
XSD now looks like this:
</para>
<programlistingco>
<areaspec>
<area xml:id="tutorial.xsd.all" coords="8"/>
<areaset xml:id="tutorial.xsd.dates">
<area xml:id="tutorial.xsd.dates.1" coords="16"/>
<area xml:id="tutorial.xsd.dates.2" coords="17"/>
</areaset>
<areaset xml:id="tutorial.xsd.strings">
<area xml:id="tutorial.xsd.strings.1" coords="23"/>
<area xml:id="tutorial.xsd.strings.2" coords="24"/>
</areaset>
</areaspec>
<programlisting><![CDATA[<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:hr="http://mycompany.com/hr/schemas"
elementFormDefault="qualified"
targetNamespace="http://mycompany.com/hr/schemas">
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:all>
<xs:element name="Holiday" type="hr:HolidayType"/>
<xs:element name="Employee" type="hr:EmployeeType"/>
</xs:all>
</xs:complexType>
</xs:element>
<xs:complexType name="HolidayType">
<xs:sequence>
<xs:element name="StartDate" type="xs:date"/>
<xs:element name="EndDate" type="xs:date"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="EmployeeType">
<xs:sequence>
<xs:element name="Number" type="xs:integer"/>
<xs:element name="FirstName" type="xs:string"/>
<xs:element name="LastName" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>]]></programlisting>
<calloutlist>
<callout arearefs="tutorial.xsd.all">
<para>
<literal>all</literal> tells the XML parser that the order of
<literal>&lt;Holiday/&gt;</literal> and
<literal>&lt;Employee/&gt;</literal> is not significant.
</para>
</callout>
<callout arearefs="tutorial.xsd.dates">
<para>
We use the <literal>xsd:date</literal> data type, which consist of a year, month, and day, for
<literal>&lt;StartDate/&gt;</literal> and <literal>&lt;EndDate/&gt;</literal>.
</para>
</callout>
<callout arearefs="tutorial.xsd.strings">
<para>
<literal>xsd:string</literal> is used for the first and last name.
</para>
</callout>
</calloutlist>
</programlistingco>
<para>
We store this file as <filename>hr.xsd</filename>.
</para>
</section>
<section xml:id="tutorial-service-contract">
<title>Service contract</title>
<para>
A service contract is generally expressed as a <link xl:href="http://www.w3.org/TR/wsdl">WSDL</link> file.
Note that in Spring-WS, <emphasis>writing the WSDL by hand is not required</emphasis>. Based on the XSD and
some conventions, Spring-WS can create the WSDL for you, as explained in the section entitled
<xref linkend="tutorial.implementing.endpoint"/>.
You can skip to <link linkend="tutorial-creating-project">the next section</link> if you want to; the
remainder of this section will show you how to write your own WSDL by hand.
</para>
<para>
We start our WSDL with the standard preamble, and by importing our existing XSD. To
separate the schema from the definition, we will use a separate namespace for the WSDL definitions:
<uri>http://mycompany.com/hr/definitions</uri>.
</para>
<programlisting><![CDATA[<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:schema="http://mycompany.com/hr/schemas"
xmlns:tns="http://mycompany.com/hr/definitions"
targetNamespace="http://mycompany.com/hr/definitions">
<wsdl:types>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:import namespace="http://mycompany.com/hr/schemas" schemaLocation="hr.xsd"/>
</xsd:schema>
</wsdl:types>]]></programlisting>
<para>
Next, we add our messages based on the written schema types. We only have one message: one with the
<literal>&lt;HolidayRequest/&gt;</literal> we put in the schema:
</para>
<programlisting><![CDATA[
<wsdl:message name="HolidayRequest">
<wsdl:part element="schema:HolidayRequest" name="HolidayRequest"/>
</wsdl:message>]]></programlisting>
<para>
We add the message to a port type as an operation:
</para>
<programlisting><![CDATA[
<wsdl:portType name="HumanResource">
<wsdl:operation name="Holiday">
<wsdl:input message="tns:HolidayRequest" name="HolidayRequest"/>
</wsdl:operation>
</wsdl:portType>]]></programlisting>
<para>
That finished the abstract part of the WSDL (the interface, as it were), and leaves the concrete part.
The concrete part consists of a <literal>binding</literal>, which tells the client <emphasis>how</emphasis>
to invoke the operations you've just defined; and a <literal>service</literal>, which tells it
<emphasis>where</emphasis> to invoke it.
</para>
<para>
Adding a concrete part is pretty standard: just refer to the abstract part you defined previously, make sure
you use <emphasis>document/literal</emphasis> for the <literal>soap:binding</literal> elements
(<literal>rpc/encoded</literal> is deprecated), pick a <literal>soapAction</literal> for the operation
(in this case <uri>http://mycompany.com/RequestHoliday</uri>, but any URI will do), and determine the
<literal>location</literal> URL where you want request to come in (in this case
<uri>http://mycompany.com/humanresources</uri>):
</para>
<programlistingco>
<areaspec>
<area xml:id="tutorial.wsdl.import" coords="9"/>
<areaset xml:id="tutorial.wsdl.message">
<area xml:id="tutorial.wsdl.message.def" coords="13"/>
<area xml:id="tutorial.wsdl.message.ref" coords="18"/>
</areaset>
<area xml:id="tutorial.wsdl.message.part" coords="14"/>
<areaset xml:id="tutorial.wsdl.portType">
<area xml:id="tutorial.wsdl.portType.def" coords="16"/>
<area xml:id="tutorial.wsdl.portType.ref" coords="21"/>
</areaset>
<areaset xml:id="tutorial.wsdl.binding">
<area xml:id="tutorial.wsdl.binding.def" coords="21"/>
<area xml:id="tutorial.wsdl.binding.ref" coords="32"/>
</areaset>
<areaset xml:id="tutorial.wsdl.doclit">
<area xml:id="tutorial.wsdl.doclit.doc" coords="22"/>
<area xml:id="tutorial.wsdl.doclit.lit" coords="27"/>
</areaset>
<area xml:id="tutorial.wsdl.transport" coords="23"/>
<area xml:id="tutorial.wsdl.soapAction" coords="25"/>
<area xml:id="tutorial.wsdl.address" coords="33"/>
</areaspec>
<programlisting><![CDATA[
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:schema="http://mycompany.com/hr/schemas"
xmlns:tns="http://mycompany.com/hr/definitions"
targetNamespace="http://mycompany.com/hr/definitions">
<wsdl:types>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:import namespace="http://mycompany.com/hr/schemas"
schemaLocation="hr.xsd"/>
</xsd:schema>
</wsdl:types>
<wsdl:message name="HolidayRequest">
<wsdl:part element="schema:HolidayRequest" name="HolidayRequest"/>
</wsdl:message>
<wsdl:portType name="HumanResource">
<wsdl:operation name="Holiday">
<wsdl:input message="tns:HolidayRequest" name="HolidayRequest"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="HumanResourceBinding" type="tns:HumanResource">
<soap:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="Holiday">
<soap:operation soapAction="http://mycompany.com/RequestHoliday"/>
<wsdl:input name="HolidayRequest">
<soap:body use="literal"/>
</wsdl:input>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="HumanResourceService">
<wsdl:port binding="tns:HumanResourceBinding" name="HumanResourcePort">
<soap:address location="http://localhost:8080/holidayService/"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>]]></programlisting>
<calloutlist>
<callout arearefs="tutorial.wsdl.import">
<para>
We import the schema defined in <xref linkend="tutorial.xsd"/>.
</para>
</callout>
<callout arearefs="tutorial.wsdl.message">
<para>
We define the <literal>HolidayRequest</literal> message, which gets used in the
<literal>portType</literal>.
</para>
</callout>
<callout arearefs="tutorial.wsdl.message.part">
<para>
The <literal>HolidayRequest</literal> type is defined in the schema.
</para>
</callout>
<callout arearefs="tutorial.wsdl.portType">
<para>
We define the <literal>HumanResource</literal> port type, which gets used in the
<literal>binding</literal>.
</para>
</callout>
<callout arearefs="tutorial.wsdl.binding">
<para>
We define the <literal>HumanResourceBinding</literal> binding, which gets used in the
<literal>port</literal>.
</para>
</callout>
<callout arearefs="tutorial.wsdl.doclit">
<para>
We use a document/literal style.
</para>
</callout>
<callout arearefs="tutorial.wsdl.transport">
<para>
The literal <uri>http://schemas.xmlsoap.org/soap/http</uri> signifies a
HTTP transport.
</para>
</callout>
<callout arearefs="tutorial.wsdl.soapAction">
<para>
The <literal>soapAction</literal> attribute signifies the <literal>SOAPAction</literal> HTTP
header that will be sent with every request.
</para>
</callout>
<callout arearefs="tutorial.wsdl.address">
<para>
The <uri>http://localhost:8080/holidayService/</uri> address is the URL where the Web
service can be invoked.
</para>
</callout>
</calloutlist>
</programlistingco>
<para>
This is the final WSDL. We will describe how to implement the resulting schema and WSDL in the next section.
</para>
</section>
<section xml:id="tutorial-creating-project">
<title>Creating the project</title>
<para>
In this section, we will be using <link xl:href="http://maven.apache.org/">Maven3</link> 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.
</para>
<para>
The following command creates a Maven3 web application project for us, using the Spring-WS archetype
(that is, project template)
</para>
<screen>mvn archetype:create -DarchetypeGroupId=org.springframework.ws \
-DarchetypeArtifactId=spring-ws-archetype \
-DarchetypeVersion=<?eval ${project.version}?> \
-DgroupId=com.mycompany.hr \
-DartifactId=holidayService
</screen>
<para>
This command will create a new directory called <filename>holidayService</filename>. In this directory,
there is a <filename>'src/main/webapp'</filename> directory, which will contain the root of the WAR file.
You will find the standard web application deployment descriptor <filename>'WEB-INF/web.xml'</filename>
here, which defines a Spring-WS <classname>MessageDispatcherServlet</classname> and maps all incoming
requests to this servlet.
</para>
<programlisting><![CDATA[
<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>MyCompany HR Holiday Service</display-name>
]]><lineannotation>&lt;!-- take especial notice of the name of this servlet --&gt;</lineannotation><![CDATA[
<servlet>
<servlet-name>]]><lineannotation><emphasis role="bold">spring-ws</emphasis></lineannotation><![CDATA[</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-ws</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>]]></programlisting>
<para>
In addition to the above <filename>'WEB-INF/web.xml'</filename> file, you will also need another,
Spring-WS-specific configuration file, named <filename>'WEB-INF/spring-ws-servlet.xml'</filename>.
This file contains all of the Spring-WS-specific beans such as <literal>EndPoints</literal>,
<literal>WebServiceMessageReceivers</literal>, and suchlike, 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
<literal>'spring-ws'</literal>) with <literal>'-servlet.xml'</literal> appended to it.
So if you defined a <classname>MessageDispatcherServlet</classname> with the name
<literal>'dynamite'</literal>, the name of the Spring-WS-specific configuration file would be
<filename>'WEB-INF/dynamite-servlet.xml'</filename>.
</para>
<para>
(You can see the contents of the <filename>'WEB-INF/spring-ws-servlet.xml'</filename> file for this
example in <xref linkend="tutorial.example.sws-conf-file"/>.)
</para>
<para>
Once you had the project structure created, you can put the schema and wsdl from previous section into
<filename>'WEB-INF/'</filename> folder.
</para>
</section>
<section xml:id="tutorial.implementing.endpoint">
<title>Implementing the Endpoint</title>
<para>
In Spring-WS, you will implement <emphasis>Endpoints</emphasis> to handle incoming XML messages.
An endpoint is typically created by annotating a class with the <interfacename>@Endpoint</interfacename>
annotation.
In this endpoint class, you will create one or more methods that handle incoming request.
The method signatures can be quite flexible: you can include just about any sort of parameter type related
to the incoming XML message, as will be explained later.
</para>
<section>
<title>Handling the XML Message</title>
<para>
In this sample application, we are going to use <link xl:href="http://www.jdom.org">JDom 2</link> to handle
the XML message.
We are also using <link xl:href="https://www.w3.org/TR/xpath20/">XPath</link>, because it allows us to
select particular parts of the XML JDOM tree, without requiring strict schema conformance.
</para>
<programlistingco>
<areaspec>
<area xml:id="tutorial.endpoint.atEndpoint" coords="21"/>
<area xml:id="tutorial.endpoint.constr" coords="35"/>
<area xml:id="tutorial.endpoint.payloadRoot" coords="48"/>
<area xml:id="tutorial.endpoint.method" coords="49"/>
</areaspec>
<programlisting><![CDATA[package com.mycompany.hr.ws;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import com.mycompany.hr.service.HumanResourceService;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
@Endpoint
public class HolidayEndpoint {
private static final String NAMESPACE_URI = "http://mycompany.com/hr/schemas";
private XPathExpression<Element> startDateExpression;
private XPathExpression<Element> endDateExpression;
private XPathExpression<Element> firstNameExpression;
private XPathExpression<Element> lastNameExpression;
private HumanResourceService humanResourceService;
@Autowired
public HolidayEndpoint(HumanResourceService humanResourceService) throws JDOMException {
this.humanResourceService = humanResourceService;
Namespace namespace = Namespace.getNamespace("hr", NAMESPACE_URI);
XPathFactory xPathFactory = XPathFactory.instance();
startDateExpression = xPathFactory.compile("//hr:StartDate", Filters.element(), null, namespace);
endDateExpression = xPathFactory.compile("//hr:EndDate", Filters.element(), null, namespace);
firstNameExpression = xPathFactory.compile("//hr:FirstName", Filters.element(), null, namespace);
lastNameExpression = xPathFactory.compile("//hr:LastName", Filters.element(), null, namespace);
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "HolidayRequest")
public void handleHolidayRequest(@RequestPayload Element holidayRequest) throws Exception {
Date startDate = parseDate(startDateExpression, holidayRequest);
Date endDate = parseDate(endDateExpression, holidayRequest);
String name = firstNameExpression.evaluateFirst(holidayRequest).getText() + " " + lastNameExpression.evaluateFirst(holidayRequest).getText();
humanResourceService.bookHoliday(startDate, endDate, name);
}
private Date parseDate(XPathExpression<Element> expression, Element element) throws ParseException {
Element result = expression.evaluateFirst(element);
if (result != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.parse(result.getText());
} else {
throw new IllegalArgumentException("Could not evaluate [" + expression + "] on [" + element + "]");
}
}
}]]></programlisting>
<calloutlist>
<callout arearefs="tutorial.endpoint.atEndpoint">
<para>
The <classname>HolidayEndpoint</classname> is annotated with
<interfacename>@Endpoint</interfacename>.
This marks the class as a special sort of <interfacename>@Component</interfacename>,
suitable for handling XML messages in Spring-WS, and also making it eligible for suitable
for component scanning.
</para>
</callout>
<callout arearefs="tutorial.endpoint.constr">
<para>
The <classname>HolidayEndpoint</classname> requires the
<interfacename>HumanResourceService</interfacename> business service to operate, so we
inject the dependency via the constructor and annotate it with
<interfacename>@Autowired</interfacename>.
</para>
<para>
Next, we set up XPath expressions using the JDOM2 API.
There are four expressions: <literal>//hr:StartDate</literal> for
extracting the <literal>&lt;StartDate&gt;</literal> text value,
<literal>//hr:EndDate</literal> for
extracting the end date and two for extracting the names of
the employee.
</para>
</callout>
<callout arearefs="tutorial.endpoint.payloadRoot">
<para>
The <interfacename>@PayloadRoot</interfacename> annotation tells Spring-WS that the
<methodname>handleHolidayRequest</methodname> method is suitable for handling XML messages.
The sort of message that this method can handle is indicated by the annotation values,
in this case, it can handle XML elements that have the <literal>HolidayRequest</literal>
local part and the <literal>http://mycompany.com/hr/schemas</literal> namespace.
</para>
<para>
More information about mapping messages to endpoints is provided in the next section.
</para>
</callout>
<callout arearefs="tutorial.endpoint.method">
<para>
The <methodname>handleHolidayRequest(..)</methodname> method is the main handling method
method, which gets passed with the <literal>&lt;HolidayRequest/&gt;</literal> element from
the incoming XML message.
The <interfacename>@RequestPayload</interfacename> annotation indicates that the
<parameter>holidayRequest</parameter> parameter should be mapped to the payload of the
request message.
</para>
<para>
We use the XPath expressions to extract the string values from the XML messages,
and convert these values to <classname>Date</classname> objects using a
<classname>SimpleDateFormat</classname> (the <methodname>parseData</methodname> method).
</para>
<para>
With these values, we invoke a method on the business service.
Typically, this will result in a database transaction being started, and some records being
altered in the database.
</para>
<para>
Finally, we define a <literal>void</literal> return type, which indicates to Spring-WS
that we do not want to send a response message.
If we wanted a response message, we could have returned a JDOM Element
that represents the payload of the response message.
</para>
</callout>
</calloutlist>
</programlistingco>
<para>
Using JDOM is just one of the options to handle the XML: other options include DOM, dom4j, XOM,
SAX, and StAX, but also marshalling techniques like JAXB, Castor, XMLBeans,
JiBX, and XStream, as is explained in the next chapter.
We chose JDOM because it gives us access to the raw XML, and because it
is based on classes (not interfaces and factory methods as with W3C DOM and dom4j), which makes the
code less verbose. We use XPath because it is less fragile than marshalling technologies: we don't
care for strict schema conformance, as long as we can find the dates and the name.
</para>
<para>
Because we use JDOM, we must add some dependencies to the Maven <filename>pom.xml</filename>, which is in the
root of our project directory. Here is the relevant section of the POM:
</para>
<programlisting>&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.ws&lt;/groupId&gt;
&lt;artifactId&gt;spring-ws-core&lt;/artifactId&gt;
&lt;version&gt;<?eval ${project.version}?>&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;jdom&lt;/groupId&gt;
&lt;artifactId&gt;jdom&lt;/artifactId&gt;
&lt;version&gt;2.0.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;jaxen&lt;/groupId&gt;
&lt;artifactId&gt;jaxen&lt;/artifactId&gt;
&lt;version&gt;1.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;</programlisting>
<para>
Here is how we would configure these classes in our <filename>spring-ws-servlet.xml</filename>
Spring XML configuration file, by using component scanning.
We also instruct Spring-WS to use annotation-driven endpoints, with the
<literal>&lt;sws:annotation-driven&gt;</literal> element.
</para>
<programlisting xml:id="tutorial.example.sws-conf-file"><![CDATA[<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sws="http://www.springframework.org/schema/web-services"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.mycompany.hr"/>
<sws:annotation-driven/>
</beans>]]></programlisting>
</section>
<section>
<title>Routing the Message to the Endpoint</title>
<para>
As part of writing the endpoint, we also used the <interfacename>@PayloadRoot</interfacename>
annotation to indicate which sort of messages can be handled by the
<methodname>handleHolidayRequest</methodname> method.
In Spring-WS, this process is the responsibility of an
<interfacename>EndpointMapping</interfacename>.
Here we route messages based on
their content, by using a <classname>PayloadRootAnnotationMethodEndpointMapping</classname>.
The annotation used above:<programlisting>
@PayloadRoot(namespace = "http://mycompany.com/hr/schemas", localPart = "HolidayRequest")</programlisting>
basically means that whenever an XML message is received with the namespace
<literal>http://mycompany.com/hr/schemas</literal> and the
<literal>HolidayRequest</literal> local name, it will be routed to the
<methodname>handleHolidayRequest</methodname> method.
By using the <literal>&lt;sws:annotation-driven&gt;</literal> element in our configuration, we
enable the detection of the <interfacename>@PayloadRoot</interfacename> annotations.
It is possible (and quite common) to have multiple, related handling methods in an endpoint, each
of them handling different XML messages.
</para>
<para>
There are also other ways to map endpoints to XML messages, which will be described in the next
chapter.
</para>
</section>
<section>
<title>Providing the Service and Stub implementation</title>
<para>
Now that we have the <emphasis>Endpoint</emphasis>, we need
<interfacename>HumanResourceService</interfacename> and its implementation for use by
<classname>HolidayEndpoint</classname>.
</para>
<programlisting><![CDATA[package com.mycompany.hr.service;
import java.util.Date;
public interface HumanResourceService {
void bookHoliday(Date startDate, Date endDate, String name);
}]]></programlisting>
<para>
For tutorial purposes, we will use a simple stub implementation of the
<interfacename>HumanResourceService</interfacename>.
</para>
<programlistingco>
<areaspec>
<area xml:id="tutorial.stubimpl.atService" coords="7"/>
</areaspec>
<programlisting><![CDATA[package com.mycompany.hr.service;
import java.util.Date;
import org.springframework.stereotype.Service;
@Service
public class StubHumanResourceService implements HumanResourceService {
public void bookHoliday(Date startDate, Date endDate, String name) {
System.out.println("Booking holiday for [" + startDate + "-" + endDate + "] for [" + name + "] ");
}
}]]></programlisting>
<calloutlist>
<callout arearefs="tutorial.stubimpl.atService">
<para>
The <classname>StubHumanResourceService</classname> is annotated with
<interfacename>@Service</interfacename>.
This marks the class as a business facade, which makes this a candidate for injection
by <interfacename>@Autowired</interfacename> in <classname>HolidayEndpoint</classname>.
</para>
</callout>
</calloutlist>
</programlistingco>
</section>
</section>
<section xml:id="tutorial-publishing-wsdl">
<title>Publishing the WSDL</title>
<para>
Finally, we need to publish the WSDL. As stated in <xref linkend="tutorial-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:
</para>
<programlistingco>
<areaspec>
<area xml:id="tutorial.wsdl.gen.bean" coords="1"/>
<area xml:id="tutorial.wsdl.gen.schema" coords="5"/>
<area xml:id="tutorial.wsdl.gen.portType" coords="2"/>
<area xml:id="tutorial.wsdl.gen.locationUri" coords="3"/>
<area xml:id="tutorial.wsdl.gen.tns" coords="4"/>
</areaspec>
<programlisting><![CDATA[<sws:dynamic-wsdl id="holiday"
portTypeName="HumanResource"
locationUri="/holidayService/"
targetNamespace="http://mycompany.com/hr/definitions">
<sws:xsd location="/WEB-INF/hr.xsd"/>
</sws:dynamic-wsdl>]]></programlisting>
<calloutlist>
<callout arearefs="tutorial.wsdl.gen.bean">
<para>
The id determines the URL where the WSDL can be retrieved.
In this case, the id is <varname>holiday</varname>, which means that the WSDL can be retrieved
as <filename>holiday.wsdl</filename> in the servlet context.
The full URL will typically be <uri>http://localhost:8080/holidayService/holiday.wsdl</uri>.
</para>
</callout>
<callout arearefs="tutorial.wsdl.gen.portType">
<para>
Next, we set the WSDL port type to be <literal>HumanResource</literal>.
</para>
</callout>
<callout arearefs="tutorial.wsdl.gen.locationUri">
<para>
We set the location where the service can be reached:
<uri>/holidayService/</uri>.
We use 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.
For more information, please refer to <xref linkend="server-automatic-wsdl-exposure"/>
</para>
<para>
For the location transformation to work, we need to add an init parameter to <classname>spring-ws</classname>
servlet in <filename>web.xml</filename>:<programlisting><![CDATA[<init-param>
<param-name>transformWsdlLocations</param-name>
<param-value>true</param-value>
</init-param>]]></programlisting>
</para>
</callout>
<callout arearefs="tutorial.wsdl.gen.tns">
<para>
We define the target namespace for the WSDL definition itself.
Setting this attribute is not required.
If not set, the WSDL will have the same namespace as the XSD schema.
</para>
</callout>
<callout arearefs="tutorial.wsdl.gen.schema">
<para>
The <varname>xsd</varname> element refers to the human resource schema we defined in
<xref linkend="tutorial.xsd"/>.
We simply placed the schema in the <filename>WEB-INF</filename> directory of the application.
</para>
</callout>
</calloutlist>
</programlistingco>
<para>
You can create a WAR file using <command>mvn install</command>.
If you deploy the application (to Tomcat, Jetty, etc.), and point your browser at
<link xl:href="http://localhost:8080/holidayService/holiday.wsdl">this location</link>, you will
see the generated WSDL. This WSDL is ready to be used by clients, such as
<link xl:href="http://www.soapui.org/">soapUI</link>, or other SOAP frameworks.
</para>
</section>
<para>
That concludes this tutorial. The tutorial code can be found in the full distribution of Spring-WS.
The next step would be to look at the echo sample application that is part
of the distribution. After that, look at the airline sample, which is a bit more complicated, because it
uses JAXB, WS-Security, Hibernate, and a transactional service layer.
Finally, you can read the rest of the reference documentation.
</para>
</chapter>

View File

@@ -1,146 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<chapter xml:id="what-is-spring-ws"
xmlns="http://docbook.org/ns/docbook" version="5.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd">
<title>What is Spring Web Services?</title>
<section>
<title>Introduction</title>
<para>
Spring Web Services (Spring-WS) is a product of the Spring community focused on creating document-driven
Web services.
Spring Web Services aims to facilitate contract-first SOAP service development, allowing for the creation of
flexible web services using one of the many ways to manipulate XML payloads.
The product is based on Spring itself, which means you can use the Spring concepts such as dependency
injection as an integral part of your Web service.
</para>
<para>
People use Spring-WS for many reasons, but most are drawn to it after finding alternative SOAP stacks
lacking when it comes to following Web service best practices.
Spring-WS makes the best practice an easy practice. This includes practices such as the WS-I basic profile,
Contract-First development, and having a loose coupling between contract and implementation.
The other key features of Spring Web services are:
</para>
<formalpara>
<title>Powerful mappings</title>
<para>
You can distribute incoming XML requests to any object, depending on message payload, SOAP Action header,
or an XPath expression.
</para>
</formalpara>
<formalpara>
<title>XML API support</title>
<para>
Incoming XML messages can be handled not only with standard JAXP APIs such as DOM, SAX, and StAX, but also JDOM,
dom4j, XOM, or even marshalling technologies.
</para>
</formalpara>
<formalpara>
<title>Flexible XML Marshalling</title>
<para>
Spring Web Services builds on the Object/XML Mapping module in the Spring Framework, which supports JAXB 1 and 2, Castor,
XMLBeans, JiBX, and XStream.
</para>
</formalpara>
<formalpara>
<title>Reuses your Spring expertise</title>
<para>
Spring-WS uses Spring application contexts for all configuration, which should help Spring developers
get up-to-speed nice and quickly. Also, the architecture of Spring-WS resembles that of Spring-MVC.
</para>
</formalpara>
<formalpara>
<title>Supports WS-Security</title>
<para>
WS-Security allows you to sign SOAP messages, encrypt and decrypt them, or authenticate against them.
</para>
</formalpara>
<formalpara>
<title>Integrates with Spring Security</title>
<para>
The WS-Security implementation of Spring Web Services provides integration with Spring Security.
This means you can use your existing Spring Security configuration for your SOAP service as well.
</para>
</formalpara>
<formalpara>
<title>Apache license</title>
<para>
You can confidently use Spring-WS in your project.
</para>
</formalpara>
</section>
<section>
<title>Runtime environment</title>
<para>
Spring Web Services requires a standard Java 7 Runtime Environment. Java 8 is also supported.
Spring-WS is built on Spring Framework 4.0.9, but higher versions are supported.
</para>
<para>
Spring-WS consists of a number of modules, which are described in the remainder of this section.
</para>
<itemizedlist>
<listitem>
<para>
The XML module (<filename>spring-xml.jar</filename>) contains various XML support classes for Spring Web
Services. This module is mainly intended for the Spring-WS framework itself, and not a Web service
developers.
</para>
</listitem>
<listitem>
<para>
The Core module (<filename>spring-ws-core.jar</filename>) is the central part of the Spring's
Web services functionality.
It provides the central <link linkend="web-service-messages">
<classname>WebServiceMessage</classname></link> and <link linkend="soap-message">
<classname>SoapMessage</classname></link> interfaces, the <link linkend="server">server-side</link>
framework, with powerful message dispatching, and the various support classes for implementing Web
service endpoints; and the <link linkend="client">client-side</link>
<classname>WebServiceTemplate</classname>.
</para>
</listitem>
<listitem>
<para>
The Support module (<filename>spring-ws-support.jar</filename>) contains additional transports
(JMS, Email, and others).
</para>
</listitem>
<listitem>
<para>
The <link linkend="security">Security</link> package (<filename>spring-ws-security.jar</filename>)
provides a WS-Security implementation that integrates
with the core Web service package. It allows you to add principal tokens, sign, and decrypt and encrypt SOAP
messages. Additionally, it allows you to leverage your existing Spring Security security implementation for
authentication and authorization.
</para>
</listitem>
</itemizedlist>
<para>
The following figure illustrates the Spring-WS modules and the dependencies between them. Arrows indicate
dependencies, i.e. Spring-WS Core depends on Spring-XML and the OXM module found in Spring 3 and higher.
<mediaobject>
<imageobject>
<imagedata fileref="images/spring-deps.png"
format="PNG" align="center"/>
</imageobject>
<caption>
<para>
Dependencies between Spring-WS modules
</para>
</caption>
</mediaobject>
</para>
</section>
<section>
<title>Supported standards</title>
<para>
Spring Web Services supports the following standards:
</para>
<itemizedlist>
<listitem><para>SOAP 1.1 and 1.2</para></listitem>
<listitem><para>WSDL 1.1 and 2.0 (XSD-based generation only supported for WSDL 1.1)</para></listitem>
<listitem><para>WS-I Basic Profile 1.0, 1.1, 1.2 and 2.0</para></listitem>
<listitem><para>WS-Addressing 1.0 and the August 2004 draft</para></listitem>
<listitem><para>SOAP Message Security 1.1, Username Token Profile 1.1, X.509 Certificate Token Profile 1.1, SAML Token Profile 1.1, Kerberos Token Profile 1.1, Basic Security Profile 1.1</para></listitem>
</itemizedlist>
</section>
</chapter>

View File

@@ -1,245 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<chapter xml:id="why-contract-first"
xmlns="http://docbook.org/ns/docbook" version="5.0"
xmlns:xl="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd
http://www.w3.org/1999/xlink http://www.docbook.org/xml/5.0/xsd/xlink.xsd">
<title>Why Contract First?</title>
<section>
<title>Introduction</title>
<para>
When creating Web services, there are two development styles: <emphasis>Contract Last</emphasis> and
<emphasis>Contract First</emphasis>. When using a contract-last approach, you start with the Java code, and
let the Web service contract (<acronym>WSDL</acronym>, see sidebar) be generated from that.
When using contract-first, you start with the WSDL contract, and use Java to implement said contract.
</para>
<sidebar>
<title>What is WSDL?</title>
<para>
WSDL stands for Web Services Description Language. A WSDL file is an XML document that describes a Web
service. It specifies the location of the service and the operations (or methods) the service exposes.
For more information about WSDL, refer to the
<link xl:href="http://www.w3.org/TR/wsdl">WSDL specification</link>.
</para>
</sidebar>
<para>
Spring-WS only supports the contract-first development style, and this section explains why.
</para>
</section>
<section>
<title>Object/XML Impedance Mismatch</title>
<para>
Similar to the field of ORM, where we have an
<link xl:href="http://en.wikipedia.org/wiki/Object-Relational_impedance_mismatch">Object/Relational impedance mismatch</link>,
there is a similar problem when converting Java objects to XML.
At first glance, the O/X mapping problem appears simple: create an XML element for each Java object,
converting all Java properties and fields to sub-elements or attributes. However, things are not as
simple as they appear: there is a fundamental difference between hierarchical languages such as XML
(and especially XSD) and the graph model of Java<footnote>
<para>Most of the contents in this section was inspired by <xref linkend="alpine"/> and
<xref linkend="effective-enterprise-java"/>.</para></footnote>.
</para>
<section>
<title>XSD extensions</title>
<para>
In Java, the only way to change the behavior of a class is to subclass it, adding the new behavior to
that subclass. In XSD, you can extend a data type by restricting it: that is, constraining the valid values
for the elements and attributes.
For instance, consider the following example:<programlisting><![CDATA[
<simpleType name="AirportCode">
<restriction base="string">
<pattern value="[A-Z][A-Z][A-Z]"/>
</restriction>
</simpleType>]]></programlisting>
This type restricts a XSD string by ways of a regular expression, allowing only three upper case
letters. If this type is converted to Java, we will end up with an ordinary
<classname>java.lang.String</classname>; the regular expression is lost in the conversion process,
because Java does not allow for these sorts of extensions.
</para>
</section>
<section>
<title>Unportable types</title>
<para>
One of the most important goals of a Web service is to be interoperable: to support multiple platforms
such as Java, .NET, Python, etc. Because all of these languages have different class libraries, you
must use some common, interlingual format to communicate between them. That format is XML, which is
supported by all of these languages.
</para>
<para>
Because of this conversion, you must make sure that you use portable types in your service
implementation. Consider, for example, a service that returns a
<classname>java.util.TreeMap</classname>, like so:<programlisting><![CDATA[
public Map getFlights() {
// use a tree map, to make sure it's sorted
TreeMap map = new TreeMap();
map.put("KL1117", "Stockholm");
...
return map;
}]]></programlisting>
Undoubtedly, the contents of this map can be converted into some sort of
XML, but since there is no <emphasis>standard</emphasis> way to describe a map in XML, it will be
proprietary. Also, even if it can be converted to XML, many platforms do not have a data structure
similar to the <classname>TreeMap</classname>. So when a .NET client accesses your Web service, it
will probably end up with a <classname>System.Collections.Hashtable</classname>, which has different
semantics.
</para>
<para>
This problem is also present when working on the client side. Consider the following XSD snippet, which
describes a service contract:<programlisting><![CDATA[
<element name="GetFlightsRequest">
<complexType>
<all>
<element name="departureDate" type="date"/>
<element name="from" type="string"/>
<element name="to" type="string"/>
</all>
</complexType>
</element>]]></programlisting>
This contract defines a request that takes an <type>date</type>, which is a XSD datatype representing
a year, month, and day. If we call this service from Java, we will probably use
either a <classname>java.util.Date</classname> or <classname>java.util.Calendar</classname>. However,
both of these classes actually describe times, rather than dates. So, we will actually end up sending data that
represents the fourth of April 2007 at midnight (<literal>2007-04-04T00:00:00</literal>), which is not
the same as <literal>2007-04-04</literal>.
</para>
</section>
<section>
<title>Cyclic graphs</title>
<para>
Imagine we have the following simple class structure:<programlisting><![CDATA[
public class Flight {
private String number;
private List<Passenger> passengers;
// getters and setters omitted
}
public class Passenger {
private String name;
private Flight flight;
// getters and setters omitted
}]]></programlisting>
This is a cyclic graph: the <classname>Flight</classname> refers to the <classname>Passenger</classname>,
which refers to the <classname>Flight</classname> again. Cyclic graphs like these are quite common in
Java. If we took a naive approach to converting this to XML, we will end up with something
like:<programlisting><![CDATA[
<flight number="KL1117">
<passengers>
<passenger>
<name>Arjen Poutsma</name>
<flight number="KL1117">
<passengers>
<passenger>
<name>Arjen Poutsma</name>
<flight number="KL1117">
<passengers>
<passenger>
<name>Arjen Poutsma</name>
...]]></programlisting>
which will take a pretty long time to finish, because there is no stop condition for this loop.
</para>
<para>
One way to solve this problem is to use references to objects that were already marshalled, like
so:<programlisting><![CDATA[
<flight number="KL1117">
<passengers>
<passenger>
<name>Arjen Poutsma</name>
<flight href="KL1117" />
</passenger>
...
</passengers>
</flight>]]></programlisting>
This solves the recursiveness problem, but introduces new ones. For one, you cannot use an XML validator
to validate this structure. Another issue is that the standard way to use these references in SOAP
(RPC/encoded) has been deprecated in favor of document/literal (see WS-I
<link xl:href="http://www.ws-i.org/Profiles/BasicProfile-1.1.html#SOAP_encodingStyle_Attribute">Basic
Profile</link>).
</para>
</section>
<para>
These are just a few of the problems when dealing with O/X mapping. It is important to respect these issues
when writing Web services. The best way to respect them is to focus on the XML completely, while using Java
as an implementation language. This is what contract-first is all about.
</para>
</section>
<section>
<title>Contract-first versus Contract-last</title>
<para>
Besides the Object/XML Mapping issues mentioned in the previous section, there are other reasons for
preferring a contract-first development style.
</para>
<section>
<title>Fragility</title>
<para>
As mentioned earlier, the contract-last development style results in your web service contract
(WSDL and your XSD) being generated from your Java contract (usually an interface). If you are using
this approach, you will have no guarantee that the contract stays constant over time. Each time you
change your Java contract and redeploy it, there might be subsequent changes to the web service
contract.
</para>
<para>
Aditionally, not all SOAP stacks generate the same web service contract from a Java contract. This
means changing your current SOAP stack for a different one (for whatever reason), might also change
your web service contract.
</para>
<para>
When a web service contract changes, users of the contract will have to be instructed to obtain
the new contract and potentially change their code to accommodate for any changes in the contract.
</para>
<para>
In order for a contract to be useful, it must remain constant for as long as possible. If a contract
changes, you will have to contact all of the users of your service, and instruct them to get the new
version of the contract.
</para>
</section>
<section>
<title>Performance</title>
<para>
When Java is automatically transformed into XML, there is no way to be sure as to what is sent across
the wire. An object might reference another object, which refers to another, etc. In the end, half of
the objects on the heap in your virtual machine might be converted into XML,
which will result in slow response times.
</para>
<para>
When using contract-first, you explicitly describe what XML is sent where, thus making sure that it is
exactly what you want.
</para>
</section>
<section>
<title>Reusability</title>
<para>
Defining your schema in a separate file allows you to reuse that file in different scenarios. If you
define an <type>AirportCode</type> in a file called <filename>airline.xsd</filename>, like so:
</para>
<programlisting><![CDATA[
<simpleType name="AirportCode">
<restriction base="string">
<pattern value="[A-Z][A-Z][A-Z]"/>
</restriction>
</simpleType>]]></programlisting>
<para>
You can reuse this definition in other schemas, or even WSDL files, using an
<literal>import</literal> statement.
</para>
</section>
<section>
<title>Versioning</title>
<para>
Even though a contract must remain constant for as long as possible, they <emphasis>do</emphasis> need
to be changed sometimes. In Java, this typically results in a new Java interface, such as
<interfacename>AirlineService2</interfacename>, and a (new) implementation of that interface. Of
course, the old service must be kept around, because there might be clients who have not migrated
yet.
</para>
<para>
If using contract-first, we can have a looser coupling between contract and implementation. Such a
looser coupling allows us to implement both versions of the contract in one class. We could, for
instance, use an XSLT stylesheet to convert any "old-style" messages to the "new-style" messages.
</para>
</section>
</section>
</chapter>