diff --git a/.gitignore b/.gitignore index c2b1080..35cfb44 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,5 @@ atlassian-ide-plugin*.xml /*/*/build /*/*/*/build .gradle + +target \ No newline at end of file diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..01e6799 Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..7179346 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip diff --git a/airline/build.gradle b/airline/build.gradle deleted file mode 100644 index c7d8373..0000000 --- a/airline/build.gradle +++ /dev/null @@ -1,19 +0,0 @@ -subprojects { - apply plugin: 'java' - apply plugin: 'eclipse' - apply plugin: 'idea' - - repositories { - maven { url 'https://repo.spring.io/libs-release' } - } - - dependencies { - testCompile("junit:junit:4.10") - testCompile("org.easymock:easymock:3.1") - } - -} - -task wrapper(type: Wrapper) { - gradleVersion = '1.8' -} diff --git a/airline/client/axis1/.mvn/wrapper/maven-wrapper.jar b/airline/client/axis1/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..01e6799 Binary files /dev/null and b/airline/client/axis1/.mvn/wrapper/maven-wrapper.jar differ diff --git a/airline/client/axis1/.mvn/wrapper/maven-wrapper.properties b/airline/client/axis1/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..7179346 --- /dev/null +++ b/airline/client/axis1/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip diff --git a/airline/client/axis1/build.gradle b/airline/client/axis1/build.gradle deleted file mode 100644 index f11184d..0000000 --- a/airline/client/axis1/build.gradle +++ /dev/null @@ -1,62 +0,0 @@ -configurations { - axis -} - -ext.axisVersion = '1.4' - -task axis { - ext.sourcesDir = "${buildDir}/generated-sources/axis" - ext.classesDir = "${buildDir}/classes/axis" - ext.wsdl = "${projectDir}/../airline.wsdl" - - inputs.files wsdl - outputs.dir classesDir - - doLast() { - project.ant { - taskdef name: "axis", classname: "org.apache.axis.tools.ant.wsdl.Wsdl2javaAntTask", - classpath: configurations.axis.asPath - - mkdir(dir: sourcesDir) - mkdir(dir: classesDir) - - axis(output: sourcesDir, url: wsdl) { - mapping(namespace: "https://www.springframework.org/spring-ws/samples/airline/definitions", - package: "org.springframework.ws.samples.airline.client.axis1") - mapping(namespace: "https://www.springframework.org/spring-ws/samples/airline/schemas/messages", - package: "org.springframework.ws.samples.airline.client.axis1") - mapping(namespace: "https://www.springframework.org/spring-ws/samples/airline/schemas/types", - package: "org.springframework.ws.samples.airline.client.axis1") - } - - javac(destdir: classesDir, source: 1.6, target: 1.6, debug: true, - debugLevel: "lines,vars,source", - classpath: configurations.axis.asPath) { - src(path: sourcesDir) - include(name: "**/*.java") - include(name: "*.java") - } - - copy(todir: classesDir) { - fileset(dir: sourcesDir, erroronmissingdir: false) { - exclude(name: "**/*.java") - } - } - - } - } -} - -dependencies { - compile("axis:axis:$axisVersion") - compile("axis:axis-jaxrpc:$axisVersion") - compile(files(axis.classesDir).builtBy(axis)) - runtime("log4j:log4j:1.2.16") - axis("axis:axis:$axisVersion") - axis("axis:axis-ant:$axisVersion") -} - -task runClient(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.airline.client.axis1.Main" - classpath = sourceSets.main.runtimeClasspath -} \ No newline at end of file diff --git a/airline/client/axis1/mvnw b/airline/client/axis1/mvnw new file mode 100755 index 0000000..5551fde --- /dev/null +++ b/airline/client/axis1/mvnw @@ -0,0 +1,286 @@ +#!/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 Mingw, 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 + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +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 "$@" diff --git a/airline/client/axis1/mvnw.cmd b/airline/client/axis1/mvnw.cmd new file mode 100644 index 0000000..e5cfb0a --- /dev/null +++ b/airline/client/axis1/mvnw.cmd @@ -0,0 +1,161 @@ +@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 set title of command window +title %0 +@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 + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%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% diff --git a/airline/client/axis1/pom.xml b/airline/client/axis1/pom.xml new file mode 100644 index 0000000..9a4df3f --- /dev/null +++ b/airline/client/axis1/pom.xml @@ -0,0 +1,173 @@ + + + 4.0.0 + + + org.springframework.ws + spring-ws-samples + 1.0.0.BUILD-SNAPSHOT + ../../../ + + + org.springframework.ws + airline-client-axis1 + 0.0.1-SNAPSHOT + Spring Web Services Samples - Airline - Client - Axis1 + Demo project for Spring Web Services + + + 1.8 + 1.4 + 1.2.16 + ${project.basedir}/target/generated-sources/axis + ${project.basedir}/target/classes + ${project.basedir}/../airline.wsdl + + + + + + axis + axis + ${axis.version} + + + + axis + axis-jaxrpc + ${axis.version} + + + + log4j + log4j + ${log4j.version} + runtime + + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + axis + axis + ${axis.version} + + + axis + axis-ant + ${axis.version} + + + + + generate-sources + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + run + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.1 + + + add-source + process-sources + + add-source + + + + ${sourcesDir} + + + + + + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + diff --git a/airline/client/axis1/src/main/java/org/springframework/ws/samples/airline/client/axis1/AxisMain.java b/airline/client/axis1/src/main/java/org/springframework/ws/samples/airline/client/axis1/AxisMain.java new file mode 100644 index 0000000..6c191ea --- /dev/null +++ b/airline/client/axis1/src/main/java/org/springframework/ws/samples/airline/client/axis1/AxisMain.java @@ -0,0 +1,99 @@ +/* + * Copyright 2006 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. + */ + +package org.springframework.ws.samples.airline.client.axis1; + +import java.rmi.RemoteException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +import javax.xml.rpc.ServiceException; + +/** + * Simple client that calls the GetFlights and BookFlight operations using JAX-RPC (Axis 1). + * + * @author Arjen Poutsma + */ +public class AxisMain { + + public static void main(String[] args) throws ServiceException, RemoteException { + + AirlineServiceLocator service = new AirlineServiceLocator(); + if (args.length > 0) { + service.setAirlineSoap11EndpointAddress(args[0]); + } + Airline airline = service.getAirlineSoap11(); + GetFlightsRequest request = new GetFlightsRequest(); + request.setFrom("AMS"); + request.setTo("VCE"); + Calendar departureCalendar = Calendar.getInstance(); + departureCalendar.set(Calendar.YEAR, 2006); + departureCalendar.set(Calendar.MONTH, Calendar.JANUARY); + departureCalendar.set(Calendar.DATE, 31); + Date departureDate = departureCalendar.getTime(); + request.setDepartureDate(departureDate); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + System.out.println("Requesting flights on " + dateFormat.format(departureDate)); + Flight[] flights = airline.getFlights(request); + System.out.println("Got " + flights.length + " results"); + if (flights.length > 0) { + // Book the first flight using John Doe as a frequent flyer + BookFlightRequest bookFlightRequest = new BookFlightRequest(); + bookFlightRequest.setFlightNumber(flights[0].getNumber()); + bookFlightRequest.setDepartureTime(flights[0].getDepartureTime()); + BookFlightRequestPassengers passengers = new BookFlightRequestPassengers(); + passengers.setUsername("john"); + bookFlightRequest.setPassengers(passengers); + Ticket ticket = airline.bookFlight(bookFlightRequest); + writeTicket(ticket); + } + } + + private static void writeTicket(Ticket ticket) { + + System.out.println("Ticket " + ticket.getId()); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + System.out.println("Ticket issue date:\t" + dateFormat.format(ticket.getIssueDate())); + for (int i = 0; i < ticket.getPassengers().length; i++) { + writeName(ticket.getPassengers()[i]); + + } + writeFlight(ticket.getFlight()); + } + + private static void writeName(Name name) { + + System.out.println("Passenger Name:"); + System.out.println(name.getFirst() + " " + name.getLast()); + System.out.println("------------"); + } + + private static void writeFlight(Flight flight) { + + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + System.out.println(dateFormat.format(flight.getDepartureTime().getTime())); + System.out.println(flight.getNumber() + "\t" + flight.getServiceClass()); + System.out.println("------------"); + System.out.println("Depart:\t" + flight.getFrom().getCode() + "-" + flight.getFrom().getName() + "\t" + + dateFormat.format(flight.getDepartureTime().getTime())); + System.out.println("\t" + flight.getFrom().getCity()); + System.out.println("Arrive:\t" + flight.getTo().getCode() + "-" + flight.getTo().getName() + "\t" + + dateFormat.format(flight.getArrivalTime().getTime())); + System.out.println("\t" + flight.getTo().getCity()); + } + +} diff --git a/airline/client/axis1/src/main/java/org/springframework/ws/samples/airline/client/axis1/Main.java b/airline/client/axis1/src/main/java/org/springframework/ws/samples/airline/client/axis1/Main.java deleted file mode 100644 index 18c25b4..0000000 --- a/airline/client/axis1/src/main/java/org/springframework/ws/samples/airline/client/axis1/Main.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2006 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. - */ - -package org.springframework.ws.samples.airline.client.axis1; - -import java.rmi.RemoteException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Calendar; -import javax.xml.rpc.ServiceException; - -/** - * Simple client that calls the GetFlights and BookFlight operations using JAX-RPC (Axis 1). - * - * @author Arjen Poutsma - */ -public class Main { - - public static void main(String[] args) throws ServiceException, RemoteException { - AirlineServiceLocator service = new AirlineServiceLocator(); - if (args.length > 0) { - service.setAirlineSoap11EndpointAddress(args[0]); - } - Airline airline = service.getAirlineSoap11(); - GetFlightsRequest request = new GetFlightsRequest(); - request.setFrom("AMS"); - request.setTo("VCE"); - Calendar departureCalendar = Calendar.getInstance(); - departureCalendar.set(Calendar.YEAR, 2006); - departureCalendar.set(Calendar.MONTH, Calendar.JANUARY); - departureCalendar.set(Calendar.DATE, 31); - Date departureDate = departureCalendar.getTime(); - request.setDepartureDate(departureDate); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - System.out.println("Requesting flights on " + dateFormat.format(departureDate)); - Flight[] flights = airline.getFlights(request); - System.out.println("Got " + flights.length + " results"); - if (flights.length > 0) - { - // Book the first flight using John Doe as a frequent flyer - BookFlightRequest bookFlightRequest = new BookFlightRequest(); - bookFlightRequest.setFlightNumber(flights[0].getNumber()); - bookFlightRequest.setDepartureTime(flights[0].getDepartureTime()); - BookFlightRequestPassengers passengers = new BookFlightRequestPassengers(); - passengers.setUsername("john"); - bookFlightRequest.setPassengers(passengers); - Ticket ticket = airline.bookFlight(bookFlightRequest); - writeTicket(ticket); - } - } - - private static void writeTicket(Ticket ticket) { - System.out.println("Ticket " + ticket.getId()); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - System.out.println("Ticket issue date:\t" + dateFormat.format(ticket.getIssueDate())); - for (int i = 0; i < ticket.getPassengers().length; i++) { - writeName(ticket.getPassengers()[i]); - - } - writeFlight(ticket.getFlight()); - } - - private static void writeName(Name name) { - System.out.println("Passenger Name:"); - System.out.println(name.getFirst() + " " + name.getLast()); - System.out.println("------------"); - } - - private static void writeFlight(Flight flight) { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - System.out.println(dateFormat.format(flight.getDepartureTime().getTime())); - System.out.println(flight.getNumber() + "\t" + flight.getServiceClass()); - System.out.println("------------"); - System.out.println("Depart:\t" + flight.getFrom().getCode() + "-" + flight.getFrom().getName() + "\t" + dateFormat.format(flight.getDepartureTime().getTime())); - System.out.println("\t" + flight.getFrom().getCity()); - System.out.println("Arrive:\t" + flight.getTo().getCode() + "-" + flight.getTo().getName() + "\t" + dateFormat.format(flight.getArrivalTime().getTime())); - System.out.println("\t" + flight.getTo().getCity()); - } - - -} diff --git a/airline/client/jax-ws/.mvn/wrapper/maven-wrapper.jar b/airline/client/jax-ws/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..01e6799 Binary files /dev/null and b/airline/client/jax-ws/.mvn/wrapper/maven-wrapper.jar differ diff --git a/airline/client/jax-ws/.mvn/wrapper/maven-wrapper.properties b/airline/client/jax-ws/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..7179346 --- /dev/null +++ b/airline/client/jax-ws/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip diff --git a/airline/client/jax-ws/build.gradle b/airline/client/jax-ws/build.gradle deleted file mode 100644 index 5179794..0000000 --- a/airline/client/jax-ws/build.gradle +++ /dev/null @@ -1,38 +0,0 @@ -configurations { - wsimport -} - -ext.springWsVersion = '2.1.4.RELEASE' - -task wsImport { - ext.outputDir = "${buildDir}/classes/wsimport" - ext.wsdl = "${projectDir}/../airline.wsdl" - - inputs.files wsdl - outputs.dir outputDir - - doLast() { - project.ant { - taskdef name: "wsimport", classname: "com.sun.tools.ws.ant.WsImport", - classpath: configurations.wsimport.asPath - mkdir(dir: outputDir) - - wsimport(destdir: outputDir, wsdl: wsdl, - package: "org.springframework.ws.samples.airline.client.jaxws") { - produces(dir: outputDir, includes: "**/*.class") - } - } - } -} - -dependencies { - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - compile(files(wsImport.outputDir).builtBy(wsImport)) - runtime("log4j:log4j:1.2.16") - wsimport "com.sun.xml.ws:jaxws-tools:2.1.7" -} - -task runClient(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.airline.client.jaxws.Main" - classpath = sourceSets.main.runtimeClasspath -} \ No newline at end of file diff --git a/airline/client/jax-ws/mvnw b/airline/client/jax-ws/mvnw new file mode 100755 index 0000000..5551fde --- /dev/null +++ b/airline/client/jax-ws/mvnw @@ -0,0 +1,286 @@ +#!/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 Mingw, 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 + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +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 "$@" diff --git a/airline/client/jax-ws/mvnw.cmd b/airline/client/jax-ws/mvnw.cmd new file mode 100644 index 0000000..e5cfb0a --- /dev/null +++ b/airline/client/jax-ws/mvnw.cmd @@ -0,0 +1,161 @@ +@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 set title of command window +title %0 +@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 + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%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% diff --git a/airline/client/jax-ws/pom.xml b/airline/client/jax-ws/pom.xml new file mode 100644 index 0000000..23ee83a --- /dev/null +++ b/airline/client/jax-ws/pom.xml @@ -0,0 +1,120 @@ + + + 4.0.0 + + + org.springframework.ws + spring-ws-samples + 1.0.0.BUILD-SNAPSHOT + ../../../ + + + org.springframework.ws + airline-client-jax-ws + 0.0.1-SNAPSHOT + Spring Web Services Samples - Airline - Client - JAX-WS + Demo project for Spring Web Services + + + 1.8 + 2.1.7 + 1.2.16 + 2.1.4.RELEASE + ${project.basedir}/target/generated-sources/jaxws + ${project.basedir}/target/classes + ${project.basedir}/../airline.wsdl + + + + + + org.springframework.ws + spring-ws-core + ${spring-ws.version} + + + + log4j + log4j + ${log4j.version} + runtime + + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + com.sun.xml.ws + jaxws-tools + ${jax-ws.version} + + + com.sun + tools + 1.5.0 + system + ${env.JAVA_HOME}/lib/tools.jar + + + + + generate-sources + + + + + + + + + + + + + + + + run + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.1 + + + add-source + process-sources + + add-source + + + + ${sourcesDir} + + + + + + + + + + diff --git a/airline/client/jax-ws/src/main/java/org/springframework/ws/samples/airline/client/jaxws/JaxWsMain.java b/airline/client/jax-ws/src/main/java/org/springframework/ws/samples/airline/client/jaxws/JaxWsMain.java new file mode 100644 index 0000000..a2b31fe --- /dev/null +++ b/airline/client/jax-ws/src/main/java/org/springframework/ws/samples/airline/client/jaxws/JaxWsMain.java @@ -0,0 +1,108 @@ +/* + * Copyright 2006 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. + */ + +package org.springframework.ws.samples.airline.client.jaxws; + +import java.net.MalformedURLException; +import java.net.URL; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeConstants; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; +import javax.xml.ws.soap.SOAPFaultException; + +/** + * Simple client that calls the GetFlights and BookFlight operations using JAX-WS. + * + * @author Arjen Poutsma + */ +public class JaxWsMain { + + public static void main(String[] args) throws MalformedURLException, DatatypeConfigurationException { + + try { + AirlineService service; + if (args.length == 0) { + service = new AirlineService(); + } else { + QName serviceName = new QName("http://www.springframework.org/spring-ws/samples/airline/definitions", + "AirlineService"); + service = new AirlineService(new URL(args[0]), serviceName); + } + Airline airline = service.getAirlineSoap11(); + GetFlightsRequest request = new GetFlightsRequest(); + request.setFrom("AMS"); + request.setTo("VCE"); + XMLGregorianCalendar departureDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(2006, 1, 31, + DatatypeConstants.FIELD_UNDEFINED); + request.setDepartureDate(departureDate); + System.out.format("Requesting flights on %1tD%n", departureDate.toGregorianCalendar()); + GetFlightsResponse response = airline.getFlights(request); + System.out.format("Got %1d results%n", response.getFlight().size()); + if (!response.getFlight().isEmpty()) + // Book the first flight using John Doe as a frequent flyer + { + Flight flight = response.getFlight().get(0); + BookFlightRequest bookFlightRequest = new BookFlightRequest(); + bookFlightRequest.setFlightNumber(flight.getNumber()); + bookFlightRequest.setDepartureTime(flight.getDepartureTime()); + BookFlightRequest.Passengers passengers = new BookFlightRequest.Passengers(); + passengers.getPassengerOrUsername().add("john"); + bookFlightRequest.setPassengers(passengers); + Ticket ticket = airline.bookFlight(bookFlightRequest); + writeTicket(ticket); + } + } catch (SOAPFaultException ex) { + System.out.format("SOAP Fault Code %1s%n", ex.getFault().getFaultCodeAsQName()); + System.out.format("SOAP Fault String: %1s%n", ex.getFault().getFaultString()); + + } + } + + private static void writeTicket(Ticket ticket) { + + System.out.format("Ticket %1d%n", ticket.getId()); + System.out.format("Ticket issue date:\t%1tD%n", ticket.getIssueDate().toGregorianCalendar()); + for (Name passenger : ticket.getPassengers().getPassenger()) { + writeName(passenger); + + } + writeFlight(ticket.flight); + } + + private static void writeName(Name name) { + + System.out.format("Passenger Name:%n"); + System.out.format("%1s %2s%n", name.getFirst(), name.getLast()); + System.out.format("------------%n"); + } + + private static void writeFlight(Flight flight) { + + System.out.format("%1tD%n", flight.getDepartureTime().toGregorianCalendar()); + System.out.format("%1s\t%2s%n", flight.getNumber(), flight.getServiceClass()); + System.out.format("------------%n"); + System.out.format("Depart:\t%1s-%2s\t%tR%n", flight.getFrom().getCode(), flight.getFrom().getName(), + flight.getDepartureTime().toGregorianCalendar()); + System.out.format("\t%1s%n", flight.getFrom().getCity()); + System.out.format("Arrive:\t%1s-%2s\t%tR%n", flight.getTo().getCode(), flight.getTo().getName(), + flight.getArrivalTime().toGregorianCalendar()); + System.out.format("\t%1s%n", flight.getTo().getCity()); + } + +} diff --git a/airline/client/jax-ws/src/main/java/org/springframework/ws/samples/airline/client/jaxws/Main.java b/airline/client/jax-ws/src/main/java/org/springframework/ws/samples/airline/client/jaxws/Main.java deleted file mode 100644 index 12e2d2b..0000000 --- a/airline/client/jax-ws/src/main/java/org/springframework/ws/samples/airline/client/jaxws/Main.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2006 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. - */ - -package org.springframework.ws.samples.airline.client.jaxws; - -import java.net.MalformedURLException; -import java.net.URL; -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeConstants; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; -import javax.xml.ws.soap.SOAPFaultException; - -/** - * Simple client that calls the GetFlights and BookFlight operations using JAX-WS. - * - * @author Arjen Poutsma - */ -public class Main { - - public static void main(String[] args) throws MalformedURLException, DatatypeConfigurationException { - try { - AirlineService service; - if (args.length == 0) { - service = new AirlineService(); - } - else { - QName serviceName = new QName("http://www.springframework.org/spring-ws/samples/airline/definitions", - "AirlineService"); - service = new AirlineService(new URL(args[0]), serviceName); - } - Airline airline = service.getAirlineSoap11(); - GetFlightsRequest request = new GetFlightsRequest(); - request.setFrom("AMS"); - request.setTo("VCE"); - XMLGregorianCalendar departureDate = - DatatypeFactory.newInstance().newXMLGregorianCalendarDate(2006, 1, 31, - DatatypeConstants.FIELD_UNDEFINED); - request.setDepartureDate(departureDate); - System.out.format("Requesting flights on %1tD%n", departureDate.toGregorianCalendar()); - GetFlightsResponse response = airline.getFlights(request); - System.out.format("Got %1d results%n", response.getFlight().size()); - if (!response.getFlight().isEmpty()) - // Book the first flight using John Doe as a frequent flyer - { - Flight flight = response.getFlight().get(0); - BookFlightRequest bookFlightRequest = new BookFlightRequest(); - bookFlightRequest.setFlightNumber(flight.getNumber()); - bookFlightRequest.setDepartureTime(flight.getDepartureTime()); - BookFlightRequest.Passengers passengers = new BookFlightRequest.Passengers(); - passengers.getPassengerOrUsername().add("john"); - bookFlightRequest.setPassengers(passengers); - Ticket ticket = airline.bookFlight(bookFlightRequest); - writeTicket(ticket); - } - } - catch (SOAPFaultException ex) { - System.out.format("SOAP Fault Code %1s%n", ex.getFault().getFaultCodeAsQName()); - System.out.format("SOAP Fault String: %1s%n", ex.getFault().getFaultString()); - - } - } - - private static void writeTicket(Ticket ticket) { - System.out.format("Ticket %1d%n", ticket.getId()); - System.out.format("Ticket issue date:\t%1tD%n", ticket.getIssueDate().toGregorianCalendar()); - for (Name passenger : ticket.getPassengers().getPassenger()) { - writeName(passenger); - - } - writeFlight(ticket.flight); - } - - private static void writeName(Name name) { - System.out.format("Passenger Name:%n"); - System.out.format("%1s %2s%n", name.getFirst(), name.getLast()); - System.out.format("------------%n"); - } - - private static void writeFlight(Flight flight) { - System.out.format("%1tD%n", flight.getDepartureTime().toGregorianCalendar()); - System.out.format("%1s\t%2s%n", flight.getNumber(), flight.getServiceClass()); - System.out.format("------------%n"); - System.out.format("Depart:\t%1s-%2s\t%tR%n", flight.getFrom().getCode(), flight.getFrom().getName(), flight.getDepartureTime().toGregorianCalendar()); - System.out.format("\t%1s%n", flight.getFrom().getCity()); - System.out.format("Arrive:\t%1s-%2s\t%tR%n", flight.getTo().getCode(), flight.getTo().getName(), flight.getArrivalTime().toGregorianCalendar()); - System.out.format("\t%1s%n", flight.getTo().getCity()); - } - -} diff --git a/airline/client/jms/build.gradle b/airline/client/jms/build.gradle deleted file mode 100644 index e2cf3a8..0000000 --- a/airline/client/jms/build.gradle +++ /dev/null @@ -1,14 +0,0 @@ -ext.springWsVersion = '2.1.4.RELEASE' - -dependencies { - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - compile("org.springframework.ws:spring-ws-support:$springWsVersion") - compile("org.apache.geronimo.specs:geronimo-jms_1.1_spec:1.1") - runtime("log4j:log4j:1.2.16") - runtime("org.apache.activemq:activemq-core:4.1.2") -} - -task runClient(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.airline.client.jms.JmsClient" - classpath = sourceSets.main.runtimeClasspath -} \ No newline at end of file diff --git a/airline/client/jms/pom.xml b/airline/client/jms/pom.xml new file mode 100644 index 0000000..985c24e --- /dev/null +++ b/airline/client/jms/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + + org.springframework.ws + spring-ws-samples + 1.0.0.BUILD-SNAPSHOT + ../../../ + + + org.springframework.ws + airline-client-jms + 0.0.1-SNAPSHOT + Spring Web Services Samples - Airline - Client - JMS + Demo project for Spring Web Services + + + 4.1.2 + 1.8 + 1.1 + 1.2.16 + ${project.basedir}/target/generated-sources/jaxws + ${project.basedir}/target/classes + ${project.basedir}/../airline.wsdl + + + + + + org.springframework.ws + spring-ws-core + + + + org.springframework.ws + spring-ws-support + + + + org.apache.geronimo.specs + geronimo-jms_1.1_spec + ${jms.version} + + + + log4j + log4j + ${log4j.version} + runtime + + + + org.apache.activemq + activemq-core + ${activemq.version} + + + + + diff --git a/airline/client/jms/src/main/java/org/springframework/ws/samples/airline/client/jms/JmsClient.java b/airline/client/jms/src/main/java/org/springframework/ws/samples/airline/client/jms/JmsClient.java index 34c5f68..9a3570e 100644 --- a/airline/client/jms/src/main/java/org/springframework/ws/samples/airline/client/jms/JmsClient.java +++ b/airline/client/jms/src/main/java/org/springframework/ws/samples/airline/client/jms/JmsClient.java @@ -16,10 +16,6 @@ package org.springframework.ws.samples.airline.client.jms; -import java.io.IOException; -import javax.jms.JMSException; -import javax.xml.soap.SOAPException; -import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamResult; import org.springframework.context.ApplicationContext; @@ -30,19 +26,11 @@ import org.springframework.xml.transform.StringSource; /** @author Arjen Poutsma */ public class JmsClient extends WebServiceGatewaySupport { - private static final String PAYLOAD = - "" + - "AMS" + "VCE" + - "2006-01-31" + ""; + private static final String PAYLOAD = "" + + "AMS" + "VCE" + + "2006-01-31" + ""; - public void getFlights() throws SOAPException, IOException, TransformerException, JMSException { - getWebServiceTemplate().sendSourceAndReceiveToResult(new StringSource(PAYLOAD), new StreamResult(System.out)); - } - - public static void main(String[] args) throws Exception { - ApplicationContext applicationContext = - new ClassPathXmlApplicationContext("applicationContext.xml", JmsClient.class); - JmsClient jmsClient = (JmsClient) applicationContext.getBean("jmsClient", JmsClient.class); - jmsClient.getFlights(); - } -} \ No newline at end of file + public void getFlights() { + getWebServiceTemplate().sendSourceAndReceiveToResult(new StringSource(PAYLOAD), new StreamResult(System.out)); + } +} diff --git a/airline/client/jms/src/main/java/org/springframework/ws/samples/airline/client/jms/JmsConfiguration.java b/airline/client/jms/src/main/java/org/springframework/ws/samples/airline/client/jms/JmsConfiguration.java new file mode 100644 index 0000000..7ef3376 --- /dev/null +++ b/airline/client/jms/src/main/java/org/springframework/ws/samples/airline/client/jms/JmsConfiguration.java @@ -0,0 +1,52 @@ +/* + * Copyright 2020 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. + */ + +package org.springframework.ws.samples.airline.client.jms; + +import javax.jms.ConnectionFactory; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.ws.transport.jms.JmsMessageSender; + +/** + * Java configuration for setting up a JMS-based client. + * + * @author Greg Turnquist + */ +@Configuration(proxyBeanMethods = false) +public class JmsConfiguration { + + @Bean + ConnectionFactory connectionFactory() { + return new ActiveMQConnectionFactory("tcp://localhost:61616"); + } + + @Bean + JmsMessageSender jmsMessageSender(ConnectionFactory connectionFactory) { + return new JmsMessageSender(connectionFactory); + } + + @Bean + JmsClient jmsClient(JmsMessageSender messageSender) { + + JmsClient jmsClient = new JmsClient(); + jmsClient.setDefaultUri("jms:RequestQueue"); + jmsClient.setMessageSender(messageSender); + return jmsClient; + } +} diff --git a/airline/client/jms/src/main/java/org/springframework/ws/samples/airline/client/jms/JmsMain.java b/airline/client/jms/src/main/java/org/springframework/ws/samples/airline/client/jms/JmsMain.java new file mode 100644 index 0000000..2257462 --- /dev/null +++ b/airline/client/jms/src/main/java/org/springframework/ws/samples/airline/client/jms/JmsMain.java @@ -0,0 +1,34 @@ +/* + * Copyright 2020 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. + */ + +package org.springframework.ws.samples.airline.client.jms; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +/** + * "Main" that creates a {@link JmsClient} and uses it to talk to the SOAP-based server. + * + * @author Greg Turnquist + */ +public class JmsMain { + + public static void main(String[] args) { + + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(JmsConfiguration.class); + + ctx.getBean(JmsClient.class).getFlights(); + } +} diff --git a/airline/client/jms/src/main/resources/org/springframework/ws/samples/airline/client/jms/applicationContext.xml b/airline/client/jms/src/main/resources/org/springframework/ws/samples/airline/client/jms/applicationContext.xml deleted file mode 100644 index 11067d7..0000000 --- a/airline/client/jms/src/main/resources/org/springframework/ws/samples/airline/client/jms/applicationContext.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/airline/client/saaj/build.gradle b/airline/client/saaj/build.gradle deleted file mode 100644 index ef6d75d..0000000 --- a/airline/client/saaj/build.gradle +++ /dev/null @@ -1,10 +0,0 @@ -dependencies { - compile("com.sun.xml.wss:xws-security:3.0") { - exclude group: 'javax.xml.crypto', module: 'xmldsig' - } -} - -task runClient(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.airline.client.saaj.Driver" - classpath = sourceSets.main.runtimeClasspath -} \ No newline at end of file diff --git a/airline/client/saaj/pom.xml b/airline/client/saaj/pom.xml new file mode 100644 index 0000000..eb56b3a --- /dev/null +++ b/airline/client/saaj/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + + + org.springframework.ws + spring-ws-samples + 1.0.0.BUILD-SNAPSHOT + ../../../ + + + org.springframework.ws + airline-client-saaj + 0.0.1-SNAPSHOT + Spring Web Services Samples - Airline - Client - SAAJ + Demo project for Spring Web Services + + + 1.8 + 3.0 + + + + + + org.slf4j + slf4j-api + + + + com.sun.xml.wss + xws-security + ${xws.version} + + + javax.xml.crypto + xmldsig + + + javax.activation + activation + + + + + + + + + + + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + true + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + + + diff --git a/airline/client/saaj/src/main/java/org/springframework/ws/samples/airline/client/saaj/Driver.java b/airline/client/saaj/src/main/java/org/springframework/ws/samples/airline/client/saaj/SaajMain.java similarity index 55% rename from airline/client/saaj/src/main/java/org/springframework/ws/samples/airline/client/saaj/Driver.java rename to airline/client/saaj/src/main/java/org/springframework/ws/samples/airline/client/saaj/SaajMain.java index dc5459b..074d48f 100644 --- a/airline/client/saaj/src/main/java/org/springframework/ws/samples/airline/client/saaj/Driver.java +++ b/airline/client/saaj/src/main/java/org/springframework/ws/samples/airline/client/saaj/SaajMain.java @@ -16,23 +16,32 @@ package org.springframework.ws.samples.airline.client.saaj; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * @author Arjen Poutsma */ -public class Driver { +public class SaajMain { + + private static final Logger logger = LoggerFactory.getLogger(SaajMain.class); + + public static void main(String[] args) throws Exception { + + String url = "http://localhost:8080/airline-server/services"; + if (args.length > 0) { + url = args[0]; + } + + logger.info("Connecting to " + url + " for flight details..."); - public static void main(String[] args) throws Exception { - String url = "http://localhost:8080/airline-server/services"; - if (args.length > 0) { - url = args[0]; - } GetFlights getFlights = new GetFlights(url); - getFlights.getFlights(); + getFlights.getFlights(); - String username = "john"; - String password = "changeme"; - GetFrequentFlyerMileage getMileage = new GetFrequentFlyerMileage(url); - getMileage.getMileage(username, password); - } + String username = "john"; + String password = "changeme"; + GetFrequentFlyerMileage getMileage = new GetFrequentFlyerMileage(url); + getMileage.getMileage(username, password); + } } diff --git a/airline/client/saaj/src/main/resources/application.properties b/airline/client/saaj/src/main/resources/application.properties new file mode 100644 index 0000000..21c84be --- /dev/null +++ b/airline/client/saaj/src/main/resources/application.properties @@ -0,0 +1,4 @@ +logging.level.org.springframework.ws=TRACE +logging.level.javax.xml.soap=TRACE +logging.level.com.sun.xml=TRACE +logging.level.javax.security.auth=TRACE diff --git a/airline/client/saaj/src/main/resources/org/springframework/ws/samples/airline/client/saaj/securityPolicy.xml b/airline/client/saaj/src/main/resources/org/springframework/ws/samples/airline/client/saaj/securityPolicy.xml index 195eb98..8509073 100644 --- a/airline/client/saaj/src/main/resources/org/springframework/ws/samples/airline/client/saaj/securityPolicy.xml +++ b/airline/client/saaj/src/main/resources/org/springframework/ws/samples/airline/client/saaj/securityPolicy.xml @@ -1,3 +1,3 @@ - + diff --git a/airline/client/spring-ws/build.gradle b/airline/client/spring-ws/build.gradle deleted file mode 100644 index 8f86aa7..0000000 --- a/airline/client/spring-ws/build.gradle +++ /dev/null @@ -1,46 +0,0 @@ -configurations { - xmlbeans -} - -ext.springWsVersion = '2.1.4.RELEASE' - -task xmlbeans { - ext.schema = "${projectDir}/../../server/src/main/webapp/messages.xsd" - ext.classesDir = "${buildDir}/classes/xmlbeans" - - inputs.files schema - outputs.dir classesDir - - doLast() { - project.ant { - taskdef name: "xmlbeans", - classname: "org.apache.xmlbeans.impl.tool.XMLBean", - classpath: configurations.xmlbeans.asPath - - xmlbeans(classgendir: classesDir, schema: schema, - compiler: "modern", verbose: "false", - classpath: configurations.xmlbeans.asPath) - } - } -} - -dependencies { - compile(files(xmlbeans.classesDir).builtBy(xmlbeans)) - compile("org.apache.xmlbeans:xmlbeans:2.4.0") - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - runtime("org.springframework.ws:spring-ws-security:$springWsVersion") { - exclude group: 'com.sun.xml.wsit', module: 'wsit-rt' - exclude group: 'com.sun.xml.wsit', module: 'xws-security' - } - runtime("com.sun.xml.wss:xws-security:3.0") { - exclude group: 'javax.xml.crypto', module: 'xmldsig' - } - runtime("log4j:log4j:1.2.16") - testCompile("org.springframework.ws:spring-ws-test:$springWsVersion") - xmlbeans("org.apache.xmlbeans:xmlbeans:2.4.0") -} - -task runClient(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.airline.client.sws.Driver" - classpath = sourceSets.main.runtimeClasspath -} \ No newline at end of file diff --git a/airline/client/spring-ws/pom.xml b/airline/client/spring-ws/pom.xml new file mode 100644 index 0000000..eaeef37 --- /dev/null +++ b/airline/client/spring-ws/pom.xml @@ -0,0 +1,135 @@ + + + 4.0.0 + + + org.springframework.ws + spring-ws-samples + 1.0.0.BUILD-SNAPSHOT + ../../../ + + + org.springframework.ws + airline-client-spring-ws + 0.0.1-SNAPSHOT + Spring Web Services Samples - Airline - Client - Spring WS + Demo project for Spring Web Services + + + 1.8 + 2.1.7 + 1.2.16 + 2.4.0 + 3.0 + ${project.basedir}/target/generated-sources/xjc + ${project.basedir}/target/classes + ${project.basedir}/../../server/src/main/resources + ${project.basedir}/../airline.wsdl + + + + + + org.springframework.ws + spring-ws-core + + + + org.springframework.ws + spring-ws-security + + + com.sun.xml.wsit + wsit-rt + + + com.sun.xml.wsit + xws-security + + + + + + com.sun.xml.wss + xws-security + ${xws.version} + runtime + + + javax.xml.crypto + xmldsig + + + javax.activation + activation + + + + + + log4j + log4j + ${log4j.version} + runtime + + + + org.springframework.ws + spring-ws-test + test + + + + + + + + + + org.jvnet.jaxb2.maven2 + maven-jaxb2-plugin + 0.14.0 + + + + generate + + + + + WSDL + org.springframework.springWs.samples.airline.schemas + + + ${wsdl} + + + true + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.1 + + + add-source + process-sources + + add-source + + + + ${sourcesDir} + + + + + + + + + + diff --git a/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/Driver.java b/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/Driver.java deleted file mode 100644 index dc2d350..0000000 --- a/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/Driver.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2005-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. - */ - -package org.springframework.ws.samples.airline.client.sws; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * @author Arjen Poutsma - */ -public class Driver { - - public static void main(String[] args) { - ApplicationContext applicationContext = new ClassPathXmlApplicationContext( - "org/springframework/ws/samples/airline/client/sws/applicationContext.xml"); - GetFlights getFlights = applicationContext.getBean("getFlights", GetFlights.class); - getFlights.getFlights(); - - GetFrequentFlyerMileage getFrequentFlyerMileage = applicationContext - .getBean("getFrequentFlyerMileage", GetFrequentFlyerMileage.class); - getFrequentFlyerMileage.getFrequentFlyerMileage(); - - } - -} diff --git a/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/GetFlights.java b/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/GetFlights.java index a2d3ef5..e542e28 100644 --- a/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/GetFlights.java +++ b/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/GetFlights.java @@ -16,87 +16,87 @@ package org.springframework.ws.samples.airline.client.sws; -import java.text.SimpleDateFormat; -import java.util.Calendar; +import javax.xml.bind.JAXBElement; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeConstants; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; -import org.springframework.springWs.samples.airline.schemas.messages.BookFlightRequestDocument; -import org.springframework.springWs.samples.airline.schemas.messages.BookFlightResponseDocument; -import org.springframework.springWs.samples.airline.schemas.messages.GetFlightsRequestDocument; -import org.springframework.springWs.samples.airline.schemas.messages.GetFlightsResponseDocument; -import org.springframework.springWs.samples.airline.schemas.types.Flight; -import org.springframework.springWs.samples.airline.schemas.types.Name; -import org.springframework.springWs.samples.airline.schemas.types.Ticket; +import org.springframework.springWs.samples.airline.schemas.BookFlightRequest; +import org.springframework.springWs.samples.airline.schemas.Flight; +import org.springframework.springWs.samples.airline.schemas.GetFlightsRequest; +import org.springframework.springWs.samples.airline.schemas.GetFlightsResponse; +import org.springframework.springWs.samples.airline.schemas.Name; +import org.springframework.springWs.samples.airline.schemas.Ticket; +import org.springframework.stereotype.Service; import org.springframework.ws.WebServiceMessageFactory; import org.springframework.ws.client.core.support.WebServiceGatewaySupport; public class GetFlights extends WebServiceGatewaySupport { - public GetFlights(WebServiceMessageFactory messageFactory) { - super(messageFactory); - } + public GetFlights(WebServiceMessageFactory messageFactory) { + super(messageFactory); + } - public void getFlights() { - GetFlightsRequestDocument getFlightsRequestDocument = GetFlightsRequestDocument.Factory.newInstance(); - GetFlightsRequestDocument.GetFlightsRequest getFlightsRequest = - getFlightsRequestDocument.addNewGetFlightsRequest(); - getFlightsRequest.setFrom("AMS"); - getFlightsRequest.setTo("VCE"); - Calendar departureDate = Calendar.getInstance(); - departureDate.clear(); - departureDate.set(2006, Calendar.JANUARY, 31); - getFlightsRequest.setDepartureDate(departureDate); + public void getFlights() { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - System.out.println("Requesting flights on " + dateFormat.format(departureDate.getTime())); - GetFlightsResponseDocument getFlightsResponseDocument = - (GetFlightsResponseDocument) getWebServiceTemplate().marshalSendAndReceive(getFlightsRequestDocument); - GetFlightsResponseDocument.GetFlightsResponse response = getFlightsResponseDocument.getGetFlightsResponse(); - System.out.println("Got " + response.sizeOfFlightArray() + " results"); - if (response.sizeOfFlightArray() > 0) { - // Book the first flight using John Doe as a frequent flyer - BookFlightRequestDocument bookFlightRequestDocument = BookFlightRequestDocument.Factory.newInstance(); - BookFlightRequestDocument.BookFlightRequest bookFlightRequest = - bookFlightRequestDocument.addNewBookFlightRequest(); - bookFlightRequest.setFlightNumber(response.getFlightArray(0).getNumber()); - bookFlightRequest.setDepartureTime(response.getFlightArray(0).getDepartureTime()); - BookFlightRequestDocument.BookFlightRequest.Passengers passengers = bookFlightRequest.addNewPassengers(); - passengers.addUsername("john"); + GetFlightsRequest getFlightsRequest = new GetFlightsRequest(); + getFlightsRequest.setFrom("AMS"); + getFlightsRequest.setTo("VCE"); + XMLGregorianCalendar departureDate = null; + try { + departureDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(2006, 1, 31, + DatatypeConstants.FIELD_UNDEFINED); + } catch (DatatypeConfigurationException e) { + throw new RuntimeException(e); + } - BookFlightResponseDocument bookFlightResponseDocument = (BookFlightResponseDocument) getWebServiceTemplate() - .marshalSendAndReceive(bookFlightRequestDocument); - Ticket ticket = bookFlightResponseDocument.getBookFlightResponse(); - writeTicket(ticket); - } - } + getFlightsRequest.setDepartureDate(departureDate); - private void writeTicket(Ticket ticket) { - System.out.println("Ticket " + ticket.getId()); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - System.out.println("Ticket issue date:\t" + dateFormat.format(ticket.getIssueDate().getTime())); - for (int i = 0; i < ticket.getPassengers().sizeOfPassengerArray(); i++) { - writeName(ticket.getPassengers().getPassengerArray(i)); + System.out.println("Requesting flights on " + departureDate); + GetFlightsResponse response = (GetFlightsResponse) getWebServiceTemplate().marshalSendAndReceive(getFlightsRequest); + System.out.println("Got " + response.getFlight().size() + " results"); + if (response.getFlight().size() > 0) { + // Book the first flight using John Doe as a frequent flyer + BookFlightRequest bookFlightRequest = new BookFlightRequest(); + bookFlightRequest.setFlightNumber(response.getFlight().get(0).getNumber()); + bookFlightRequest.setDepartureTime(response.getFlight().get(0).getDepartureTime()); + BookFlightRequest.Passengers passengers = new BookFlightRequest.Passengers(); + passengers.getPassengerOrUsername().add("john"); + bookFlightRequest.setPassengers(passengers); - } - writeFlight(ticket.getFlight()); - } + JAXBElement ticket = (JAXBElement) getWebServiceTemplate() + .marshalSendAndReceive(bookFlightRequest); - private void writeName(Name name) { - System.out.println("Passenger Name:"); - System.out.println(name.getFirst() + " " + name.getLast()); - System.out.println("------------"); - } + writeTicket(ticket.getValue()); + } + } - private void writeFlight(Flight flight) { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - System.out.println(dateFormat.format(flight.getDepartureTime().getTime())); - System.out.println(flight.getNumber() + "\t" + flight.getServiceClass()); - System.out.println("------------"); - System.out.println("Depart:\t" + flight.getFrom().getCode() + "-" + flight.getFrom().getName() + "\t" + - dateFormat.format(flight.getDepartureTime().getTime())); - System.out.println("\t" + flight.getFrom().getCity()); - System.out.println("Arrive:\t" + flight.getTo().getCode() + "-" + flight.getTo().getName() + "\t" + - dateFormat.format(flight.getArrivalTime().getTime())); - System.out.println("\t" + flight.getTo().getCity()); - } + private void writeTicket(Ticket ticket) { + System.out.println("Ticket " + ticket.getId()); + System.out.println("Ticket issue date:\t" + ticket.getIssueDate()); + ticket.getPassengers().getPassenger().forEach(this::writeName); + writeFlight(ticket.getFlight()); + } + + private void writeName(Name name) { + + System.out.println("Passenger Name:"); + System.out.println(name.getFirst() + " " + name.getLast()); + System.out.println("------------"); + } + + private void writeFlight(Flight flight) { + + System.out.println(flight.getDepartureTime()); + System.out.println(flight.getNumber() + "\t" + flight.getServiceClass()); + System.out.println("------------"); + System.out.println( + "Depart:\t" + flight.getFrom().getCode() + "-" + flight.getFrom().getName() + "\t" + flight.getDepartureTime()); + System.out.println("\t" + flight.getFrom().getCity()); + System.out.println( + "Arrive:\t" + flight.getTo().getCode() + "-" + flight.getTo().getName() + "\t" + flight.getArrivalTime()); + System.out.println("\t" + flight.getTo().getCity()); + } } diff --git a/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/GetFrequentFlyerMileage.java b/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/GetFrequentFlyerMileage.java index 99021bc..be0aafe 100644 --- a/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/GetFrequentFlyerMileage.java +++ b/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/GetFrequentFlyerMileage.java @@ -25,16 +25,17 @@ import org.springframework.xml.transform.StringSource; public class GetFrequentFlyerMileage extends WebServiceGatewaySupport { - public GetFrequentFlyerMileage(WebServiceMessageFactory messageFactory) { - super(messageFactory); - } + public GetFrequentFlyerMileage(WebServiceMessageFactory messageFactory) { + super(messageFactory); + } - public void getFrequentFlyerMileage() { - Source source = new StringSource( - ""); + public void getFrequentFlyerMileage() { - getWebServiceTemplate().sendSourceAndReceiveToResult(source, new StreamResult(System.out)); + Source source = new StringSource( + ""); - } + getWebServiceTemplate().sendSourceAndReceiveToResult(source, new StreamResult(System.out)); + + } } diff --git a/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/SpringWsMain.java b/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/SpringWsMain.java new file mode 100644 index 0000000..6e91a54 --- /dev/null +++ b/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/SpringWsMain.java @@ -0,0 +1,36 @@ +/* + * Copyright 2005-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. + */ + +package org.springframework.ws.samples.airline.client.sws; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +/** + * @author Arjen Poutsma + */ +public class SpringWsMain { + + public static void main(String[] args) { + + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(WsConfiguration.class); + + GetFlights getFlights = ctx.getBean(GetFlights.class); + getFlights.getFlights(); + + GetFrequentFlyerMileage getFrequentFlyerMileage = ctx.getBean(GetFrequentFlyerMileage.class); + getFrequentFlyerMileage.getFrequentFlyerMileage(); + } +} diff --git a/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/WsConfiguration.java b/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/WsConfiguration.java new file mode 100644 index 0000000..de35db2 --- /dev/null +++ b/airline/client/spring-ws/src/main/java/org/springframework/ws/samples/airline/client/sws/WsConfiguration.java @@ -0,0 +1,56 @@ +package org.springframework.ws.samples.airline.client.sws; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import org.springframework.ws.soap.SoapMessageFactory; +import org.springframework.ws.soap.saaj.SaajSoapMessageFactory; +import org.springframework.ws.soap.security.wss4j2.Wss4jSecurityInterceptor; + +@Configuration(proxyBeanMethods = false) +public class WsConfiguration { + + @Bean + SoapMessageFactory messageFactory() { + return new SaajSoapMessageFactory(); + } + + @Bean + Jaxb2Marshaller marshaller() { + + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + marshaller.setPackagesToScan("org.springframework.springWs.samples.airline.schemas"); + return marshaller; + } + + @Bean + GetFlights getFlights(SoapMessageFactory messageFactory, Jaxb2Marshaller marshaller) { + + GetFlights getFlights = new GetFlights(messageFactory); + getFlights.setDefaultUri("http://localhost:8080/airline-server/services"); + getFlights.setMarshaller(marshaller); + getFlights.setUnmarshaller(marshaller); + return getFlights; + } + + @Bean + GetFrequentFlyerMileage getFrequentFlyerMileage(SoapMessageFactory messageFactory, + Wss4jSecurityInterceptor securityInterceptor) { + + GetFrequentFlyerMileage getFrequentFlyerMileage = new GetFrequentFlyerMileage(messageFactory); + getFrequentFlyerMileage.setDefaultUri("http://localhost:8080/airline-server/services"); + getFrequentFlyerMileage.setInterceptors(new Wss4jSecurityInterceptor[] { securityInterceptor }); + return getFrequentFlyerMileage; + } + + @Bean + Wss4jSecurityInterceptor securityInterceptor() { + + Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor(); + interceptor.setSecurementActions("UsernameToken"); + interceptor.setSecurementUsername("john"); + interceptor.setSecurementPassword("changeme"); + return interceptor; + } + +} diff --git a/airline/client/spring-ws/src/main/resources/org/springframework/ws/samples/airline/client/sws/applicationContext.xml b/airline/client/spring-ws/src/main/resources/org/springframework/ws/samples/airline/client/sws/applicationContext.xml deleted file mode 100644 index 21a31df..0000000 --- a/airline/client/spring-ws/src/main/resources/org/springframework/ws/samples/airline/client/sws/applicationContext.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/airline/client/spring-ws/src/test/java/org/springframework/ws/samples/airline/client/sws/GetFlightsTest.java b/airline/client/spring-ws/src/test/java/org/springframework/ws/samples/airline/client/sws/GetFlightsTest.java index 39eff19..d0cce92 100644 --- a/airline/client/spring-ws/src/test/java/org/springframework/ws/samples/airline/client/sws/GetFlightsTest.java +++ b/airline/client/spring-ws/src/test/java/org/springframework/ws/samples/airline/client/sws/GetFlightsTest.java @@ -16,85 +16,78 @@ package org.springframework.ws.samples.airline.client.sws; -import java.util.Collections; -import java.util.Map; -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 org.springframework.ws.test.client.MockWebServiceServer; import static org.springframework.ws.test.client.RequestMatchers.*; import static org.springframework.ws.test.client.ResponseCreators.*; +import java.util.Collections; +import java.util.Map; + +import javax.xml.transform.Source; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.ws.test.client.MockWebServiceServer; +import org.springframework.xml.transform.StringSource; /** * This test illustrates the use of the client-side testing API, introduced in Spring-WS 2.0. * * @author Arjen Poutsma */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("applicationContext.xml") +@ExtendWith(SpringExtension.class) +@Import(WsConfiguration.class) public class GetFlightsTest { - @Autowired - GetFlights getFlights; - - private MockWebServiceServer mockServer; + @Autowired GetFlights getFlights; - private static final String MESSAGES_NS = - "http://www.springframework.org/spring-ws/samples/airline/schemas/messages"; + private MockWebServiceServer mockServer; - private static final String TYPES_NS = "http://www.springframework.org/spring-ws/samples/airline/schemas/types"; + private static final String MESSAGES_NS = "http://www.springframework.org/spring-ws/samples/airline/schemas/messages"; - @Before - public void setUpMocks() throws Exception { - mockServer = MockWebServiceServer.createServer(getFlights); - } + private static final String TYPES_NS = "http://www.springframework.org/spring-ws/samples/airline/schemas/types"; - @Test - public void getFlights() throws Exception { - Source getFlightsRequest = new StringSource( - "" + "AMS" + "VCE" + - "2006-01-31" + ""); + @BeforeEach + public void setUpMocks() { + mockServer = MockWebServiceServer.createServer(getFlights); + } - String flightInfo = - "KL1653" + "2006-01-31T10:05:00.000+01:00" + - "AMSSchiphol AirportAmsterdam" + - "2006-01-31T12:25:00.000+01:00" + - "VCEMarco Polo AirportVenice" + - "economy"; + @Test + public void getFlights() { - Source getFlightsResponse = new StringSource( - "" + "" + - flightInfo + "" + ""); + Source getFlightsRequest = new StringSource("" + "AMS" + + "VCE" + "2006-01-31" + ""); - mockServer.expect(payload(getFlightsRequest)).andRespond(withPayload(getFlightsResponse)); + String flightInfo = "KL1653" + + "2006-01-31T10:05:00.000+01:00" + + "AMSSchiphol AirportAmsterdam" + + "2006-01-31T12:25:00.000+01:00" + + "VCEMarco Polo AirportVenice" + + "economy"; - Source bookFlightResponse = new StringSource( - "" + "4" + - "2010-07-28" + - "JohnDoe" + - "" + flightInfo + "" + ""); + Source getFlightsResponse = new StringSource("" + "" + flightInfo + "" + ""); - Map namespaces = Collections.singletonMap("m", MESSAGES_NS); + mockServer.expect(payload(getFlightsRequest)).andRespond(withPayload(getFlightsResponse)); - mockServer.expect(xpath("/m:BookFlightRequest/m:flightNumber", namespaces).exists()) - .andExpect(xpath("/m:BookFlightRequest/m:departureTime", namespaces).exists()) - .andExpect(xpath("/m:BookFlightRequest/m:passengers", namespaces).exists()) - .andRespond(withPayload(bookFlightResponse)); + Source bookFlightResponse = new StringSource("" + "4" + "2010-07-28" + + "JohnDoe" + + "" + flightInfo + "" + ""); - getFlights.getFlights(); + Map namespaces = Collections.singletonMap("m", MESSAGES_NS); - mockServer.verify(); + mockServer.expect(xpath("/m:BookFlightRequest/m:flightNumber", namespaces).exists()) + .andExpect(xpath("/m:BookFlightRequest/m:departureTime", namespaces).exists()) + .andExpect(xpath("/m:BookFlightRequest/m:passengers", namespaces).exists()) + .andRespond(withPayload(bookFlightResponse)); - } + getFlights.getFlights(); + mockServer.verify(); + } } diff --git a/airline/server/build.gradle b/airline/server/build.gradle deleted file mode 100644 index 7e6e0e0..0000000 --- a/airline/server/build.gradle +++ /dev/null @@ -1,147 +0,0 @@ -configurations { - jaxb - openjpa -} - -buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.9' - } -} - -ext.springVersion = '3.2.4.RELEASE' -ext.springWsVersion = '2.1.4.RELEASE' -ext.springSecVersion = '3.1.0.RELEASE' -ext.tomcatVersion = '7.0.42' - -apply plugin: 'war' -apply plugin: 'tomcat' - - -task genJaxb { - ext.sourcesDir = "${buildDir}/generated-sources/jaxb" - ext.classesDir = "${buildDir}/classes/jaxb" - ext.schema = "${projectDir}/src/main/webapp/messages.xsd" - - inputs.files schema - outputs.dir classesDir - - doLast() { - project.ant { - taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask", - classpath: configurations.jaxb.asPath - mkdir(dir: sourcesDir) - mkdir(dir: classesDir) - - xjc(destdir: sourcesDir, schema: schema, - package: "org.springframework.ws.samples.airline.schema") { - produces(dir: sourcesDir, includes: "**/*.java") - } - - javac(destdir: classesDir, source: 1.6, target: 1.6, debug: true, - debugLevel: "lines,vars,source", - classpath: configurations.jaxb.asPath) { - src(path: sourcesDir) - include(name: "**/*.java") - include(name: "*.java") - } - - copy(todir: classesDir) { - fileset(dir: sourcesDir, erroronmissingdir: false) { - exclude(name: "**/*.java") - } - } - } - } -} - -task enhance { - doLast { - ant.taskdef( name : 'openjpaenhancer', - classpath : project.runtimeClasspath.asPath, - classname : 'org.apache.openjpa.ant.PCEnhancerTask' - ) - - ant.openjpaenhancer( - classpath : project.runtimeClasspath.asPath) - ant.fileset(dir: "${projectDir}/src/main/java/") { - include(name: '**/domain/*.java') - exclude(name: 'ServiceClass.java') - } - } -} - -war { - it.dependsOn enhance -} - -test { - it.dependsOn enhance -} - -tomcatRun { - it.dependsOn enhance - contextPath = 'airline-server' -} - - - - -dependencies { - compile(files(genJaxb.classesDir).builtBy(genJaxb)) - - // Spring-WS - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - compile("org.springframework.ws:spring-ws-security:$springWsVersion") { - exclude group: 'com.sun.xml.wsit', module: 'wsit-rt' - exclude group: 'com.sun.xml.wsit', module: 'xws-security' - } - - runtime("org.springframework.ws:spring-ws-support:$springWsVersion") - - // Spring - runtime("org.springframework:spring-orm:$springVersion") - testCompile("org.springframework:spring-jdbc:$springVersion") - testCompile("org.springframework:spring-test:$springVersion") - - // Spring Security - runtime("org.springframework.security:spring-security-core:$springSecVersion") - runtime("org.springframework.security:spring-security-config:$springSecVersion") - runtime("org.springframework.security:spring-security-web:$springSecVersion") - - // JEE - runtime("javax.servlet:jstl:1.2") - - // ORM - compile("org.apache.openjpa:openjpa:1.2.3") - runtime("commons-dbcp:commons-dbcp:1.2.1") { - exclude group: 'xml-apis', module: 'xml-apis' - exclude group: 'xerces', module: 'xerces' - } - runtime("hsqldb:hsqldb:1.8.0.7") - - // Various - runtime("org.apache.activemq:activemq-core:4.1.2") - runtime("org.apache.derby:derby:10.3.1.4") - runtime("org.apache.ws.xmlschema:xmlschema-core:2.0.2") - runtime("com.sun.xml.wss:xws-security:3.0") { - exclude group: 'javax.xml.crypto', module: 'xmldsig' - } - runtime("joda-time:joda-time-jsptags:1.1.1") - - runtime("log4j:log4j:1.2.16") - - - jaxb "com.sun.xml.bind:jaxb-xjc:2.1.7" - openjpa "org.apache.openjpa:openjpa:1.2.3" - - tomcat("org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion", - "org.apache.tomcat.embed:tomcat-embed-logging-juli:$tomcatVersion") - tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:$tomcatVersion") { - exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj' - } -} \ No newline at end of file diff --git a/airline/server/pom.xml b/airline/server/pom.xml new file mode 100644 index 0000000..3e85dc1 --- /dev/null +++ b/airline/server/pom.xml @@ -0,0 +1,224 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.3.1.RELEASE + + + + org.springframework.ws + airline-server + 0.0.1-SNAPSHOT + Spring Web Services Samples - Airline - Server + Demo project for Spring Web Services + + + 1.8 + 2.10.6 + 1.2.16 + ${project.basedir}/target/generated-sources/axis + ${project.basedir}/target/classes + ${project.basedir}/../airline.wsdl + 2.0.2 + 3.0 + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-web-services + + + + org.springframework.ws + spring-ws-security + + + com.sun.xml.wsit + wsit-rt + + + com.sun.xml.wsit + xws-security + + + + + + com.sun.xml.wss + xws-security + ${xws-security.version} + + + javax.activation + activation + + + javax.xml.crypto + xmldsig + + + javax.xml.bind + jaxb-api + + + javax.xml.stream + stax-api + + + javax.xml.ws + jaxws-api + + + javax.mail + mail + + + + + + org.springframework.ws + spring-ws-support + + + + wsdl4j + wsdl4j + + + + org.springframework.boot + spring-boot-starter-security + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + runtime + + + + org.apache.ws.xmlschema + xmlschema-core + ${xmlschema.version} + runtime + + + + org.springframework.boot + spring-boot-starter-activemq + + + + org.apache.activemq + activemq-kahadb-store + runtime + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + joda-time + joda-time + ${joda-time.version} + + + + + + + + + + + org.springframework + spring-test + test + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.codehaus.mojo + jaxb2-maven-plugin + 2.5.0 + + + xjc + + xjc + + + + + ${project.basedir}/src/main/resources/messages.xsd + org.springframework.ws.samples.airline.schema + 2.1 + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.1 + + + add-source + process-sources + + add-source + + + + target/generated-sources/xjc + + + + + + + + + + + + diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/AirlineServerApplication.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/AirlineServerApplication.java new file mode 100644 index 0000000..1d52b3e --- /dev/null +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/AirlineServerApplication.java @@ -0,0 +1,13 @@ +package org.springframework.ws.samples.airline; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; + +@SpringBootApplication(exclude = SecurityAutoConfiguration.class) +public class AirlineServerApplication { + + public static void main(String[] args) { + SpringApplication.run(AirlineServerApplication.class, args); + } +} diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/AirportDao.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/AirportDao.java new file mode 100644 index 0000000..5730213 --- /dev/null +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/AirportDao.java @@ -0,0 +1,8 @@ +package org.springframework.ws.samples.airline.dao; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.ws.samples.airline.domain.Airport; + +public interface AirportDao extends CrudRepository { + +} diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/Databaseinit.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/Databaseinit.java new file mode 100644 index 0000000..b31db40 --- /dev/null +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/Databaseinit.java @@ -0,0 +1,50 @@ +package org.springframework.ws.samples.airline.dao; + +import org.joda.time.DateTime; +import org.springframework.boot.CommandLineRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.ws.samples.airline.domain.Airport; +import org.springframework.ws.samples.airline.domain.Flight; +import org.springframework.ws.samples.airline.domain.FrequentFlyer; +import org.springframework.ws.samples.airline.domain.ServiceClass; + +@Configuration +public class Databaseinit { + + @Bean + CommandLineRunner initializeDatabase(AirportDao airportDao, FlightDao flightDao, FrequentFlyerDao frequentFlyerDao) { + return args -> { + Airport amsterdam = airportDao.save(new Airport("AMS", "Schiphol Airport", "Amsterdam")); + Airport venice = airportDao.save(new Airport("VCE", "Marco Polo Airport", "Venice")); + Airport rotterdam = airportDao.save(new Airport("RTM", "Rotterdam Airport", "Rotterdam")); + Airport gardermoen = airportDao.save(new Airport("OSL", "Gardermoen", "Oslo")); + + Flight flight = new Flight(); + flight.setNumber("KL1653"); + flight.setDepartureTime(new DateTime(2006, 1, 31, 10, 5, 0, 0).toGregorianCalendar().toZonedDateTime()); + flight.setFrom(amsterdam); + flight.setArrivalTime(new DateTime(2006, 1, 31, 12, 25, 0, 0).toGregorianCalendar().toZonedDateTime()); + flight.setTo(venice); + flight.setServiceClass(ServiceClass.ECONOMY); + flight.setSeatsAvailable(5); + flight.setMiles(200); + + flightDao.save(flight); + + flight = new Flight(); + flight.setNumber("KL1654"); + flight.setDepartureTime(new DateTime(2006, 2, 5, 12, 40, 0, 0).toGregorianCalendar().toZonedDateTime()); + flight.setFrom(venice); + flight.setArrivalTime(new DateTime(2006, 2, 5, 14, 15, 0, 0).toGregorianCalendar().toZonedDateTime()); + flight.setTo(amsterdam); + flight.setServiceClass(ServiceClass.ECONOMY); + flight.setSeatsAvailable(5); + flight.setMiles(200); + + flightDao.save(flight); + + frequentFlyerDao.save(new FrequentFlyer("John", "Doe", "john", "changeme")); + }; + } +} diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/FlightDao.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/FlightDao.java index dc8c18c..0edecba 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/FlightDao.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/FlightDao.java @@ -15,22 +15,50 @@ */ package org.springframework.ws.samples.airline.dao; +import java.time.ZonedDateTime; import java.util.List; -import org.joda.time.DateTime; import org.joda.time.Interval; -import org.springframework.dao.DataAccessException; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; import org.springframework.ws.samples.airline.domain.Flight; import org.springframework.ws.samples.airline.domain.ServiceClass; -public interface FlightDao { +public interface FlightDao extends CrudRepository { - List findFlights(String fromAirportCode, String toAirportCode, Interval interval, ServiceClass serviceClass) - throws DataAccessException; + @Query("SELECT f FROM Flight f WHERE f.from.code = :fromAirportCode " + + "AND f.to.code = :toAirportCode AND f.departureTime >= :#{#interval.start.toGregorianCalendar().toZonedDateTime()} AND f.departureTime <= :#{#interval.end.toGregorianCalendar().toZonedDateTime()} AND " + + "f.serviceClass = :class") + List findFlights(@Param("fromAirportCode") String fromAirportCode, // + @Param("toAirportCode") String toAirportCode, // + @Param("interval") Interval interval, // + @Param("class") ServiceClass serviceClass); - Flight getFlight(Long id); + /** + * @deprecated Migrate to {@link #findById(Object)}. + */ + default Flight getFlight(Long id) { + return findById(id).get(); + } - Flight getFlight(String flightNumber, DateTime departureTime); + ; - Flight update(Flight flight); + /** + * @deprecated Migrate to {@link #findFlightByNumberAndDepartureTime(String, ZonedDateTime)}. + */ + @Deprecated + default Flight getFlight(String flightNumber, ZonedDateTime departureTime) { + return findFlightByNumberAndDepartureTime(flightNumber, departureTime); + } + + Flight findFlightByNumberAndDepartureTime(String flightNumber, ZonedDateTime departureTime); + + /** + * @deprecated Migrate to {@link #save(Object)}. + */ + @Deprecated + default Flight update(Flight flight) { + return save(flight); + } } diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/FrequentFlyerDao.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/FrequentFlyerDao.java index e889cc9..a2e9c7e 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/FrequentFlyerDao.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/FrequentFlyerDao.java @@ -17,10 +17,19 @@ package org.springframework.ws.samples.airline.dao; import org.springframework.dao.DataAccessException; +import org.springframework.data.repository.CrudRepository; import org.springframework.ws.samples.airline.domain.FrequentFlyer; -public interface FrequentFlyerDao { +public interface FrequentFlyerDao extends CrudRepository { - FrequentFlyer get(String username) throws DataAccessException; + /** + * @deprecated Migrate to {@link #findByUsername(String)}. + */ + @Deprecated + default FrequentFlyer get(String username) throws DataAccessException { + return findByUsername(username); + } + + FrequentFlyer findByUsername(String username); } diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/TicketDao.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/TicketDao.java index e3be0ac..afe0b21 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/TicketDao.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/TicketDao.java @@ -16,11 +16,9 @@ package org.springframework.ws.samples.airline.dao; -import org.springframework.dao.DataAccessException; +import org.springframework.data.repository.CrudRepository; import org.springframework.ws.samples.airline.domain.Ticket; -public interface TicketDao { - - void save(Ticket ticket) throws DataAccessException; +public interface TicketDao extends CrudRepository { } diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/jpa/DatabaseInitializer.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/jpa/DatabaseInitializer.java deleted file mode 100644 index a4a506a..0000000 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/jpa/DatabaseInitializer.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2005-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. - */ - -package org.springframework.ws.samples.airline.dao.jpa; - -import javax.annotation.PostConstruct; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallbackWithoutResult; -import org.springframework.transaction.support.TransactionTemplate; -import org.springframework.ws.samples.airline.domain.Airport; -import org.springframework.ws.samples.airline.domain.Flight; -import org.springframework.ws.samples.airline.domain.FrequentFlyer; -import org.springframework.ws.samples.airline.domain.ServiceClass; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.joda.time.DateTime; - -/** - * A simple class that uses JPA to initialize the database. - * - * @author Arjen Poutsma - * @since 1.5.0 - */ -@Component -public class DatabaseInitializer { - - private static final Log logger = LogFactory.getLog(DatabaseInitializer.class); - - private final TransactionTemplate transactionTemplate; - - @PersistenceContext - private EntityManager entityManager; - - private Airport amsterdam; - - private Airport venice; - - @Autowired - public DatabaseInitializer(PlatformTransactionManager transactionManager) { - this.transactionTemplate = new TransactionTemplate(transactionManager); - } - - @PostConstruct - public void initDatabase() { - transactionTemplate.execute(new TransactionCallbackWithoutResult() { - protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { - logger.info("Initializing Database"); - createAirports(); - createFlights(); - createFrequentFlyers(); - } - }); - } - - private void createAirports() { - amsterdam = new Airport("AMS", "Schiphol Airport", "Amsterdam"); - entityManager.persist(amsterdam); - venice = new Airport("VCE", "Marco Polo Airport", "Venice"); - entityManager.persist(venice); - } - - private void createFlights() { - Flight flight = new Flight(); - flight.setNumber("KL1653"); - flight.setDepartureTime(new DateTime(2006, 1, 31, 10, 5, 0, 0)); - flight.setFrom(amsterdam); - flight.setArrivalTime(new DateTime(2006, 1, 31, 12, 25, 0, 0)); - flight.setTo(venice); - flight.setServiceClass(ServiceClass.ECONOMY); - flight.setSeatsAvailable(5); - flight.setMiles(200); - entityManager.persist(flight); - flight = new Flight(); - flight.setNumber("KL1654"); - flight.setDepartureTime(new DateTime(2006, 2, 5, 12, 40, 0, 0)); - flight.setFrom(venice); - flight.setArrivalTime(new DateTime(2006, 2, 5, 14, 15, 0, 0)); - flight.setTo(amsterdam); - flight.setServiceClass(ServiceClass.ECONOMY); - flight.setSeatsAvailable(5); - flight.setMiles(200); - entityManager.persist(flight); - } - - private void createFrequentFlyers() { - entityManager.persist(new FrequentFlyer("John", "Doe", "john", "changeme")); - } -} diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/jpa/JpaFlightDao.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/jpa/JpaFlightDao.java deleted file mode 100644 index 72ca105..0000000 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/jpa/JpaFlightDao.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2007 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. - */ - -package org.springframework.ws.samples.airline.dao.jpa; - -import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.NoResultException; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; - -import org.joda.time.DateTime; -import org.joda.time.Interval; -import org.springframework.dao.DataAccessException; -import org.springframework.stereotype.Repository; -import org.springframework.ws.samples.airline.dao.FlightDao; -import org.springframework.ws.samples.airline.domain.Flight; -import org.springframework.ws.samples.airline.domain.ServiceClass; - -@Repository -public class JpaFlightDao implements FlightDao { - - @PersistenceContext - private EntityManager entityManager; - - public List findFlights(String fromAirportCode, - String toAirportCode, - Interval interval, - ServiceClass serviceClass) throws DataAccessException { - Query query = entityManager.createQuery("SELECT f FROM Flight f WHERE f.from.code = :fromParam " + - "AND f.to.code = :toParam AND f.departureTime >= :start AND f.departureTime <= :end AND " + - "f.serviceClass = :class"); - query.setParameter("fromParam", fromAirportCode); - query.setParameter("toParam", toAirportCode); - query.setParameter("start", interval.getStart()); - query.setParameter("end", interval.getEnd()); - query.setParameter("class", serviceClass); - return query.getResultList(); - } - - public Flight getFlight(Long id) { - return entityManager.find(Flight.class, id); - } - - public Flight getFlight(String flightNumber, DateTime departureTime) { - Query query = entityManager - .createQuery("SELECT f FROM Flight f WHERE f.number = :number AND f.departureTime = :departureTime"); - query.setParameter("number", flightNumber); - query.setParameter("departureTime", departureTime); - try { - return (Flight) query.getSingleResult(); - } - catch (NoResultException e) { - return null; - } - } - - public Flight update(Flight flight) { - return entityManager.merge(flight); - } -} diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/jpa/JpaFrequentFlyerDao.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/jpa/JpaFrequentFlyerDao.java deleted file mode 100644 index b7cb58d..0000000 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/jpa/JpaFrequentFlyerDao.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2007 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. - */ - -package org.springframework.ws.samples.airline.dao.jpa; - -import javax.persistence.EntityManager; -import javax.persistence.NoResultException; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; - -import org.springframework.dao.DataAccessException; -import org.springframework.stereotype.Repository; -import org.springframework.ws.samples.airline.dao.FrequentFlyerDao; -import org.springframework.ws.samples.airline.domain.FrequentFlyer; - -@Repository -public class JpaFrequentFlyerDao implements FrequentFlyerDao { - - @PersistenceContext - private EntityManager entityManager; - - public FrequentFlyer get(String username) throws DataAccessException { - Query query = entityManager.createQuery("SELECT f FROM FrequentFlyer f WHERE f.username = :username"); - query.setParameter("username", username); - try { - return (FrequentFlyer) query.getSingleResult(); - } - catch (NoResultException e) { - return null; - } - } - -} diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/jpa/JpaTicketDao.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/jpa/JpaTicketDao.java deleted file mode 100644 index ba11a44..0000000 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/dao/jpa/JpaTicketDao.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2007 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. - */ - -package org.springframework.ws.samples.airline.dao.jpa; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - -import org.springframework.dao.DataAccessException; -import org.springframework.stereotype.Repository; -import org.springframework.ws.samples.airline.dao.TicketDao; -import org.springframework.ws.samples.airline.domain.Ticket; - -@Repository -public class JpaTicketDao implements TicketDao { - - @PersistenceContext - private EntityManager entityManager; - - public void save(Ticket ticket) throws DataAccessException { - entityManager.persist(ticket); - } -} diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Airport.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Airport.java index d9951a0..ce55810 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Airport.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Airport.java @@ -17,6 +17,7 @@ package org.springframework.ws.samples.airline.domain; import java.io.Serializable; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Flight.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Flight.java index 102859f..32d7d17 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Flight.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Flight.java @@ -16,6 +16,8 @@ package org.springframework.ws.samples.airline.domain; import java.io.Serializable; +import java.time.ZonedDateTime; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; @@ -27,153 +29,131 @@ import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; -import org.apache.openjpa.persistence.Persistent; -import org.joda.time.DateTime; +import org.springframework.data.annotation.Persistent; @Entity @Table(name = "FLIGHT") public class Flight implements Serializable { - @Id - @Column(name = "ID") - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @Id @Column(name = "ID") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @Column(name = "NUMBER") - private String number; + @Column(name = "NUMBER") private String number; - @Column(name = "DEPARTURE_TIME") - @Persistent - private DateTime departureTime; + @Column(name = "DEPARTURE_TIME") @Persistent private ZonedDateTime departureTime; - @ManyToOne - @JoinColumn(name = "FROM_AIRPORT_CODE", nullable = false) - private Airport from; + @ManyToOne @JoinColumn(name = "FROM_AIRPORT_CODE", nullable = false) private Airport from; - @Column(name = "ARRIVAL_TIME") - @Persistent - private DateTime arrivalTime; + @Column(name = "ARRIVAL_TIME") @Persistent private ZonedDateTime arrivalTime; - @ManyToOne - @JoinColumn(name = "TO_AIRPORT_CODE", nullable = false) - private Airport to; + @ManyToOne @JoinColumn(name = "TO_AIRPORT_CODE", nullable = false) private Airport to; - @Column(name = "SERVICE_CLASS") - @Enumerated(EnumType.STRING) - private ServiceClass serviceClass; + @Column(name = "SERVICE_CLASS") @Enumerated(EnumType.STRING) private ServiceClass serviceClass; - @Column(name = "SEATS_AVAILABLE") - private int seatsAvailable; + @Column(name = "SEATS_AVAILABLE") private int seatsAvailable; - @Column(name = "MILES") - private int miles; + @Column(name = "MILES") private int miles; - public Flight() { - } + public Flight() {} - public Flight(Long id) { - this.id = id; - } + public Flight(Long id) { + this.id = id; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public DateTime getArrivalTime() { - return arrivalTime; - } + public ZonedDateTime getArrivalTime() { + return arrivalTime; + } - public void setArrivalTime(DateTime arrivalTime) { - this.arrivalTime = arrivalTime; - } + public void setArrivalTime(ZonedDateTime arrivalTime) { + this.arrivalTime = arrivalTime; + } - public DateTime getDepartureTime() { - return departureTime; - } + public ZonedDateTime getDepartureTime() { + return departureTime; + } - public void setDepartureTime(DateTime departureTime) { - this.departureTime = departureTime; - } + public void setDepartureTime(ZonedDateTime departureTime) { + this.departureTime = departureTime; + } - public Airport getFrom() { - return from; - } + public Airport getFrom() { + return from; + } - public void setFrom(Airport from) { - this.from = from; - } + public void setFrom(Airport from) { + this.from = from; + } - public int getMiles() { - return miles; - } + public int getMiles() { + return miles; + } - public void setMiles(int miles) { - this.miles = miles; - } + public void setMiles(int miles) { + this.miles = miles; + } - public String getNumber() { - return number; - } + public String getNumber() { + return number; + } - public void setNumber(String number) { - this.number = number; - } + public void setNumber(String number) { + this.number = number; + } - public int getSeatsAvailable() { - return seatsAvailable; - } + public int getSeatsAvailable() { + return seatsAvailable; + } - public void setSeatsAvailable(int seatsAvailable) { - this.seatsAvailable = seatsAvailable; - } + public void setSeatsAvailable(int seatsAvailable) { + this.seatsAvailable = seatsAvailable; + } - public ServiceClass getServiceClass() { - return serviceClass; - } + public ServiceClass getServiceClass() { + return serviceClass; + } - public void setServiceClass(ServiceClass serviceClass) { - this.serviceClass = serviceClass; - } + public void setServiceClass(ServiceClass serviceClass) { + this.serviceClass = serviceClass; + } - public Airport getTo() { - return to; - } + public Airport getTo() { + return to; + } - public void setTo(Airport to) { - this.to = to; - } + public void setTo(Airport to) { + this.to = to; + } - public void substractSeats(int count) { - seatsAvailable -= count; - } + public void substractSeats(int count) { + seatsAvailable -= count; + } - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } - final Flight flight = (Flight) o; + final Flight flight = (Flight) o; - if (!departureTime.equals(flight.departureTime)) { - return false; - } - return number.equals(flight.number); - } + if (!departureTime.equals(flight.departureTime)) { + return false; + } + return number.equals(flight.number); + } - public int hashCode() { - int result = number.hashCode(); - result = 29 * result + departureTime.hashCode(); - return result; - } + public int hashCode() { + int result = number.hashCode(); + result = 29 * result + departureTime.hashCode(); + return result; + } - public String toString() { - StringBuffer buffer = new StringBuffer(); - buffer.append(getNumber()); - buffer.append(' '); - buffer.append(getDepartureTime().toString()); - return buffer.toString(); - } + public String toString() { + return getNumber() + " " + getDepartureTime(); + } } diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/FrequentFlyer.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/FrequentFlyer.java index 7e428ea..a1ea89e 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/FrequentFlyer.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/FrequentFlyer.java @@ -26,72 +26,70 @@ import javax.persistence.Table; @PrimaryKeyJoinColumn(name = "PASSENGER_ID") public class FrequentFlyer extends Passenger { - @Column(name = "USERNAME") - private String username; + @Column(name = "USERNAME") private String username; - @Column(name = "PASSWORD") - private String password; + @Column(name = "PASSWORD") private String password; - @Column(name = "MILES") - private int miles; + @Column(name = "MILES") private int miles; - public FrequentFlyer() { - } + public FrequentFlyer() {} - public FrequentFlyer(String username) { - this.username = username; - } + public FrequentFlyer(String username) { + this.username = username; + } - public FrequentFlyer(String firstName, String lastName, String username, String password) { - super(firstName, lastName); - this.username = username; - this.password = password; - } + public FrequentFlyer(String firstName, String lastName, String username, String password) { - public int getMiles() { - return miles; - } + super(firstName, lastName); + this.username = username; + this.password = password; + } - public void setMiles(int miles) { - this.miles = miles; - } + public int getMiles() { + return miles; + } - public String getPassword() { - return password; - } + public void setMiles(int miles) { + this.miles = miles; + } - public void setPassword(String password) { - this.password = password; - } + public String getPassword() { + return password; + } - public String getUsername() { - return username; - } + public void setPassword(String password) { + this.password = password; + } - public void setUsername(String username) { - this.username = username; - } + public String getUsername() { + return username; + } - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof FrequentFlyer)) { - return false; - } - final FrequentFlyer that = (FrequentFlyer) other; - return username.equals(that.username); - } + public void setUsername(String username) { + this.username = username; + } - public int hashCode() { - return username.hashCode(); - } + public boolean equals(Object other) { - public String toString() { - return username; - } + if (this == other) { + return true; + } + if (!(other instanceof FrequentFlyer)) { + return false; + } + final FrequentFlyer that = (FrequentFlyer) other; + return username.equals(that.username); + } - public void addMiles(int miles) { - this.miles += miles; - } + public int hashCode() { + return username.hashCode(); + } + + public String toString() { + return username; + } + + public void addMiles(int miles) { + this.miles += miles; + } } diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Passenger.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Passenger.java index 3aeb628..462b167 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Passenger.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Passenger.java @@ -16,6 +16,7 @@ package org.springframework.ws.samples.airline.domain; import java.io.Serializable; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Ticket.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Ticket.java index da3593f..3e5abe2 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Ticket.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/Ticket.java @@ -19,6 +19,7 @@ package org.springframework.ws.samples.airline.domain; import java.io.Serializable; import java.util.HashSet; import java.util.Set; + import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; @@ -31,67 +32,67 @@ import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; -import org.apache.openjpa.persistence.Persistent; import org.joda.time.LocalDate; +import org.springframework.data.annotation.Persistent; @Entity @Table(name = "TICKET") public class Ticket implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; - @Column(name = "ISSUE_DATE") - @Persistent - private LocalDate issueDate; + @Column(name = "ISSUE_DATE") + @Persistent + private LocalDate issueDate; - @ManyToOne - @JoinColumn(name = "FLIGHT_ID", nullable = false) - private Flight flight; + @ManyToOne + @JoinColumn(name = "FLIGHT_ID", nullable = false) + private Flight flight; - @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) - @JoinTable(name = "PASSENGER_TICKET", - joinColumns = @JoinColumn(name = "TICKET_ID"), - inverseJoinColumns = @JoinColumn(name = "PASSENGER_ID")) - private Set passengers = new HashSet(); + @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) + @JoinTable(name = "PASSENGER_TICKET", + joinColumns = @JoinColumn(name = "TICKET_ID"), + inverseJoinColumns = @JoinColumn(name = "PASSENGER_ID")) + private Set passengers = new HashSet(); - public Ticket() { - } + public Ticket() { + } - public Ticket(Long id) { - this.id = id; - } + public Ticket(Long id) { + this.id = id; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public Flight getFlight() { - return flight; - } + public Flight getFlight() { + return flight; + } - public void setFlight(Flight flight) { - this.flight = flight; - } + public void setFlight(Flight flight) { + this.flight = flight; + } - public LocalDate getIssueDate() { - return issueDate; - } + public LocalDate getIssueDate() { + return issueDate; + } - public void setIssueDate(LocalDate issueDate) { - this.issueDate = issueDate; - } + public void setIssueDate(LocalDate issueDate) { + this.issueDate = issueDate; + } - public Set getPassengers() { - return passengers; - } + public Set getPassengers() { + return passengers; + } - public void setPassengers(Set passengers) { - this.passengers = passengers; - } + public void setPassengers(Set passengers) { + this.passengers = passengers; + } - public void addPassenger(Passenger passenger) { - passengers.add(passenger); - } + public void addPassenger(Passenger passenger) { + passengers.add(passenger); + } } diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/openjpa/DateTimeValueHandler.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/openjpa/DateTimeValueHandler.java deleted file mode 100644 index e3d4842..0000000 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/openjpa/DateTimeValueHandler.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2007 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. - */ - -package org.springframework.ws.samples.airline.domain.openjpa; - -import java.sql.Timestamp; - -import org.apache.openjpa.jdbc.kernel.JDBCStore; -import org.apache.openjpa.jdbc.meta.JavaSQLTypes; -import org.apache.openjpa.jdbc.meta.ValueMapping; -import org.apache.openjpa.jdbc.meta.strats.AbstractValueHandler; -import org.apache.openjpa.jdbc.schema.Column; -import org.apache.openjpa.jdbc.schema.ColumnIO; -import org.joda.time.DateTime; - -/** - * @author Arjen Poutsma - * @since 1.1.0 - */ -public class DateTimeValueHandler extends AbstractValueHandler { - - private static final DateTimeValueHandler instance = new DateTimeValueHandler(); - - public static DateTimeValueHandler getInstance() { - return instance; - } - - public Column[] map(ValueMapping vm, String name, ColumnIO io, boolean adapt) { - Column col = new Column(); - col.setName(name); - col.setJavaType(JavaSQLTypes.TIMESTAMP); - return new Column[]{col}; - } - - @Override - public Object toDataStoreValue(ValueMapping valueMapping, Object val, JDBCStore jdbcStore) { - return val == null ? null : new Timestamp(((DateTime) val).getMillis()); - } - - @Override - public Object toObjectValue(ValueMapping valueMapping, Object val) { - return val == null ? null : new DateTime(val); - } -} diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/openjpa/LocalDateValueHandler.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/openjpa/LocalDateValueHandler.java deleted file mode 100644 index b05a46b..0000000 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/domain/openjpa/LocalDateValueHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2007 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. - */ - -package org.springframework.ws.samples.airline.domain.openjpa; - -import java.sql.Date; - -import org.apache.openjpa.jdbc.kernel.JDBCStore; -import org.apache.openjpa.jdbc.meta.JavaSQLTypes; -import org.apache.openjpa.jdbc.meta.ValueMapping; -import org.apache.openjpa.jdbc.meta.strats.AbstractValueHandler; -import org.apache.openjpa.jdbc.schema.Column; -import org.apache.openjpa.jdbc.schema.ColumnIO; -import org.joda.time.LocalDate; - -/** - * @author Arjen Poutsma - * @since 1.1.0 - */ -public class LocalDateValueHandler extends AbstractValueHandler { - - public Column[] map(ValueMapping vm, String name, ColumnIO io, boolean adapt) { - Column col = new Column(); - col.setName(name); - col.setJavaType(JavaSQLTypes.DATE); - return new Column[]{col}; - } - - @Override - public Object toDataStoreValue(ValueMapping valueMapping, Object val, JDBCStore jdbcStore) { - return val == null ? null : new Date(((LocalDate) val).toDateMidnight().getMillis()); - } - - @Override - public Object toObjectValue(ValueMapping valueMapping, Object val) { - return val == null ? null : new LocalDate(val); - } -} diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/jms/JmsConfiguration.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/jms/JmsConfiguration.java new file mode 100644 index 0000000..b6f30af --- /dev/null +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/jms/JmsConfiguration.java @@ -0,0 +1,52 @@ +package org.springframework.ws.samples.airline.jms; + +import javax.jms.ConnectionFactory; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.activemq.broker.BrokerFactory; +import org.apache.activemq.broker.BrokerService; +import org.apache.activemq.command.ActiveMQQueue; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jms.listener.DefaultMessageListenerContainer; +import org.springframework.ws.WebServiceMessageFactory; +import org.springframework.ws.transport.WebServiceMessageReceiver; +import org.springframework.ws.transport.jms.WebServiceMessageListener; + +@Configuration +public class JmsConfiguration { + + @Bean(initMethod = "start") + BrokerService broker() throws Exception { + return BrokerFactory.createBroker("broker:tcp://localhost:61616?persistent=false"); + } + + @Bean + ActiveMQConnectionFactory connectionFactory() { + + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); + connectionFactory.setBrokerURL("tcp://localhost:61616"); + return connectionFactory; + } + + @Bean + DefaultMessageListenerContainer containerFactory(ConnectionFactory connectionFactory, + WebServiceMessageListener messageListener) { + + DefaultMessageListenerContainer container = new DefaultMessageListenerContainer(); + container.setConnectionFactory(connectionFactory); + container.setDestination(new ActiveMQQueue("RequestQueue")); + container.setMessageListener(messageListener); + return container; + } + + @Bean + WebServiceMessageListener messageListener(WebServiceMessageFactory messageFactory, + WebServiceMessageReceiver messageReceiver) { + + WebServiceMessageListener messageListener = new WebServiceMessageListener(); + messageListener.setMessageFactory(messageFactory); + messageListener.setMessageReceiver(messageReceiver); + return messageListener; + } +} diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/schema/support/SchemaConversionUtils.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/schema/support/SchemaConversionUtils.java index 4335524..4f10522 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/schema/support/SchemaConversionUtils.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/schema/support/SchemaConversionUtils.java @@ -16,15 +16,16 @@ package org.springframework.ws.samples.airline.schema.support; -import java.util.ArrayList; +import java.time.ZonedDateTime; +import java.util.GregorianCalendar; import java.util.List; +import java.util.stream.Collectors; + import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.springframework.ws.samples.airline.domain.Passenger; import org.springframework.ws.samples.airline.schema.Airport; @@ -36,112 +37,119 @@ import org.springframework.ws.samples.airline.schema.Ticket; /** @author Arjen Poutsma */ public abstract class SchemaConversionUtils { - private SchemaConversionUtils() { - } + private SchemaConversionUtils() {} - public static Flight toSchemaType(org.springframework.ws.samples.airline.domain.Flight domainFlight) - throws DatatypeConfigurationException { - Flight schemaFlight = new Flight(); - schemaFlight.setNumber(domainFlight.getNumber()); - schemaFlight.setDepartureTime(toXMLGregorianCalendar(domainFlight.getDepartureTime())); - schemaFlight.setFrom(toSchemaType(domainFlight.getFrom())); - schemaFlight.setArrivalTime(toXMLGregorianCalendar(domainFlight.getArrivalTime())); - schemaFlight.setTo(toSchemaType(domainFlight.getTo())); - schemaFlight.setServiceClass(toSchemaType(domainFlight.getServiceClass())); - return schemaFlight; - } + public static Flight toSchemaType(org.springframework.ws.samples.airline.domain.Flight domainFlight) + throws DatatypeConfigurationException { - public static List toSchemaType(List domainFlights) - throws DatatypeConfigurationException { - List schemaFlights = new ArrayList(domainFlights.size()); - for (org.springframework.ws.samples.airline.domain.Flight domainFlight : domainFlights) { - schemaFlights.add(toSchemaType(domainFlight)); - } - return schemaFlights; - } + Flight schemaFlight = new Flight(); + schemaFlight.setNumber(domainFlight.getNumber()); + schemaFlight.setDepartureTime(toXMLGregorianCalendar(domainFlight.getDepartureTime())); + schemaFlight.setFrom(toSchemaType(domainFlight.getFrom())); + schemaFlight.setArrivalTime(toXMLGregorianCalendar(domainFlight.getArrivalTime())); + schemaFlight.setTo(toSchemaType(domainFlight.getTo())); + schemaFlight.setServiceClass(toSchemaType(domainFlight.getServiceClass())); + return schemaFlight; + } - public static XMLGregorianCalendar toXMLGregorianCalendar(DateTime dateTime) throws DatatypeConfigurationException { - DatatypeFactory factory = DatatypeFactory.newInstance(); - return factory.newXMLGregorianCalendar(dateTime.toGregorianCalendar()); - } + public static List toSchemaType(List domainFlights) { - public static DateTime toDateTime(XMLGregorianCalendar calendar) { - int timeZoneMinutes = calendar.getTimezone(); - DateTimeZone timeZone = DateTimeZone.forOffsetHoursMinutes(timeZoneMinutes / 60, timeZoneMinutes % 60); - return new DateTime(calendar.getYear(), calendar.getMonth(), calendar.getDay(), calendar.getHour(), - calendar.getMinute(), calendar.getSecond(), calendar.getMillisecond(), timeZone); - } + return domainFlights.stream() // + .map(flight -> { + try { + return toSchemaType(flight); + } catch (DatatypeConfigurationException e) { + throw new RuntimeException(e); + } + }) // + .collect(Collectors.toList()); + } - public static XMLGregorianCalendar toXMLGregorianCalendar(LocalDate localDate) - throws DatatypeConfigurationException { - DatatypeFactory factory = DatatypeFactory.newInstance(); - return factory.newXMLGregorianCalendarDate(localDate.getYear(), localDate.getMonthOfYear(), - localDate.getDayOfMonth(), DatatypeConstants.FIELD_UNDEFINED); - } + public static XMLGregorianCalendar toXMLGregorianCalendar(ZonedDateTime dateTime) + throws DatatypeConfigurationException { - public static LocalDate toLocalDate(XMLGregorianCalendar calendar) { - return new LocalDate(calendar.getYear(), calendar.getMonth(), calendar.getDay()); - } + DatatypeFactory factory = DatatypeFactory.newInstance(); + return factory.newXMLGregorianCalendar(GregorianCalendar.from(dateTime)); + } - public static Airport toSchemaType(org.springframework.ws.samples.airline.domain.Airport domainAirport) { - if (domainAirport == null) { - return null; - } - Airport schemaAirport = new Airport(); - schemaAirport.setCode(domainAirport.getCode()); - schemaAirport.setName(domainAirport.getName()); - schemaAirport.setCity(domainAirport.getCity()); - return schemaAirport; - } + public static ZonedDateTime toDateTime(XMLGregorianCalendar calendar) { + return calendar.toGregorianCalendar().toZonedDateTime(); + } - public static ServiceClass toSchemaType(org.springframework.ws.samples.airline.domain.ServiceClass domainServiceClass) { - switch (domainServiceClass) { - case BUSINESS: - return ServiceClass.BUSINESS; - case ECONOMY: - return ServiceClass.ECONOMY; - case FIRST: - return ServiceClass.FIRST; - default: - throw new IllegalArgumentException("Invalid domain service class: [" + domainServiceClass + "]"); - } - } + public static XMLGregorianCalendar toXMLGregorianCalendar(LocalDate localDate) throws DatatypeConfigurationException { - public static org.springframework.ws.samples.airline.domain.ServiceClass toDomainType(ServiceClass schemaServiceClass) { - if (schemaServiceClass == null) { - return null; - } - switch (schemaServiceClass) { - case BUSINESS: - return org.springframework.ws.samples.airline.domain.ServiceClass.BUSINESS; - case ECONOMY: - return org.springframework.ws.samples.airline.domain.ServiceClass.ECONOMY; - case FIRST: - return org.springframework.ws.samples.airline.domain.ServiceClass.FIRST; - default: - throw new IllegalArgumentException("Invalid schema service class: [" + schemaServiceClass + "]"); - } - } + DatatypeFactory factory = DatatypeFactory.newInstance(); + return factory.newXMLGregorianCalendarDate(localDate.getYear(), localDate.getMonthOfYear(), + localDate.getDayOfMonth(), DatatypeConstants.FIELD_UNDEFINED); + } - public static Name toSchemaType(org.springframework.ws.samples.airline.domain.Passenger passenger) { - Name name = new Name(); - name.setFirst(passenger.getFirstName()); - name.setLast(passenger.getLastName()); - return name; - } + public static LocalDate toLocalDate(XMLGregorianCalendar calendar) { + return new LocalDate(calendar.getYear(), calendar.getMonth(), calendar.getDay()); + } - public static Ticket toSchemaType(org.springframework.ws.samples.airline.domain.Ticket domainTicket) - throws DatatypeConfigurationException { - Ticket schemaTicket = new Ticket(); - schemaTicket.setId(domainTicket.getId()); - schemaTicket.setFlight(toSchemaType(domainTicket.getFlight())); - schemaTicket.setIssueDate(toXMLGregorianCalendar(domainTicket.getIssueDate())); - if (!domainTicket.getPassengers().isEmpty()) { - schemaTicket.setPassengers(new Ticket.Passengers()); - } - for (Passenger passenger : domainTicket.getPassengers()) { - schemaTicket.getPassengers().getPassenger().add(toSchemaType(passenger)); - } - return schemaTicket; - } + public static Airport toSchemaType(org.springframework.ws.samples.airline.domain.Airport domainAirport) { + + if (domainAirport == null) { + return null; + } + + Airport schemaAirport = new Airport(); + schemaAirport.setCode(domainAirport.getCode()); + schemaAirport.setName(domainAirport.getName()); + schemaAirport.setCity(domainAirport.getCity()); + return schemaAirport; + } + + public static ServiceClass toSchemaType( + org.springframework.ws.samples.airline.domain.ServiceClass domainServiceClass) { + switch (domainServiceClass) { + case BUSINESS: + return ServiceClass.BUSINESS; + case ECONOMY: + return ServiceClass.ECONOMY; + case FIRST: + return ServiceClass.FIRST; + default: + throw new IllegalArgumentException("Invalid domain service class: [" + domainServiceClass + "]"); + } + } + + public static org.springframework.ws.samples.airline.domain.ServiceClass toDomainType( + ServiceClass schemaServiceClass) { + if (schemaServiceClass == null) { + return null; + } + switch (schemaServiceClass) { + case BUSINESS: + return org.springframework.ws.samples.airline.domain.ServiceClass.BUSINESS; + case ECONOMY: + return org.springframework.ws.samples.airline.domain.ServiceClass.ECONOMY; + case FIRST: + return org.springframework.ws.samples.airline.domain.ServiceClass.FIRST; + default: + throw new IllegalArgumentException("Invalid schema service class: [" + schemaServiceClass + "]"); + } + } + + public static Name toSchemaType(Passenger passenger) { + Name name = new Name(); + name.setFirst(passenger.getFirstName()); + name.setLast(passenger.getLastName()); + return name; + } + + public static Ticket toSchemaType(org.springframework.ws.samples.airline.domain.Ticket domainTicket) + throws DatatypeConfigurationException { + Ticket schemaTicket = new Ticket(); + schemaTicket.setId(domainTicket.getId()); + schemaTicket.setFlight(toSchemaType(domainTicket.getFlight())); + schemaTicket.setIssueDate(toXMLGregorianCalendar(domainTicket.getIssueDate())); + if (!domainTicket.getPassengers().isEmpty()) { + schemaTicket.setPassengers(new Ticket.Passengers()); + } + for (Passenger passenger : domainTicket.getPassengers()) { + schemaTicket.getPassengers().getPassenger().add(toSchemaType(passenger)); + } + return schemaTicket; + } } diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/security/FrequentFlyerDetails.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/security/FrequentFlyerDetails.java index 6bda1d7..82ca823 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/security/FrequentFlyerDetails.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/security/FrequentFlyerDetails.java @@ -20,7 +20,7 @@ import java.util.ArrayList; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.GrantedAuthorityImpl; +import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.ws.samples.airline.domain.FrequentFlyer; @@ -37,7 +37,7 @@ public class FrequentFlyerDetails implements UserDetails { public static final Collection GRANTED_AUTHORITIES = new ArrayList(); { - GRANTED_AUTHORITIES.add(new GrantedAuthorityImpl("ROLE_FREQUENT_FLYER")); + GRANTED_AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_FREQUENT_FLYER")); }; public FrequentFlyerDetails(FrequentFlyer frequentFlyer) { diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/security/SecurityConfiguration.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/security/SecurityConfiguration.java new file mode 100644 index 0000000..63272b0 --- /dev/null +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/security/SecurityConfiguration.java @@ -0,0 +1,37 @@ +package org.springframework.ws.samples.airline.security; + +import java.util.HashMap; +import java.util.Map; + +import net.bytebuddy.build.Plugin; +import org.springframework.context.annotation.Bean; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.crypto.password.DelegatingPasswordEncoder; +import org.springframework.security.crypto.password.NoOpPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.ws.samples.airline.dao.FrequentFlyerDao; + +@EnableGlobalMethodSecurity(securedEnabled = true) +public class SecurityConfiguration /*extends WebSecurityConfigurerAdapter*/ { + + @Bean + SpringFrequentFlyerSecurityService securityService(FrequentFlyerDao frequentFlyerDao) { + return new SpringFrequentFlyerSecurityService(frequentFlyerDao); + } + + @Bean + AuthenticationManager authenticationManager(SpringFrequentFlyerSecurityService securityService) { + + DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); + authenticationProvider.setUserDetailsService(securityService); + return new ProviderManager(authenticationProvider); + } + + @Bean + PasswordEncoder passwordEncoder() { + return NoOpPasswordEncoder.getInstance(); + } +} diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/security/SpringFrequentFlyerSecurityService.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/security/SpringFrequentFlyerSecurityService.java index 355d2a7..c709a84 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/security/SpringFrequentFlyerSecurityService.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/security/SpringFrequentFlyerSecurityService.java @@ -16,7 +16,6 @@ package org.springframework.ws.samples.airline.security; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; @@ -36,51 +35,48 @@ import org.springframework.ws.samples.airline.service.NoSuchFrequentFlyerExcepti */ public class SpringFrequentFlyerSecurityService implements FrequentFlyerSecurityService, UserDetailsService { - private FrequentFlyerDao frequentFlyerDao; + private FrequentFlyerDao frequentFlyerDao; - @Autowired - public SpringFrequentFlyerSecurityService(FrequentFlyerDao frequentFlyerDao) { - this.frequentFlyerDao = frequentFlyerDao; - } + public SpringFrequentFlyerSecurityService(FrequentFlyerDao frequentFlyerDao) { + this.frequentFlyerDao = frequentFlyerDao; + } - @Transactional - public FrequentFlyer getCurrentlyAuthenticatedFrequentFlyer() { - SecurityContext context = SecurityContextHolder.getContext(); - Authentication authentication = context.getAuthentication(); - if (authentication != null) { - if (authentication.getPrincipal() instanceof FrequentFlyerDetails) { - FrequentFlyerDetails details = (FrequentFlyerDetails) authentication.getPrincipal(); - return details.getFrequentFlyer(); - } - else { - return (FrequentFlyer) authentication.getPrincipal(); - } - } - else { - return null; - } - } + @Transactional + public FrequentFlyer getCurrentlyAuthenticatedFrequentFlyer() { - @Transactional - public FrequentFlyer getFrequentFlyer(String username) throws NoSuchFrequentFlyerException { - FrequentFlyer frequentFlyer = frequentFlyerDao.get(username); - if (frequentFlyer != null) { - return frequentFlyer; - } - else { - throw new NoSuchFrequentFlyerException(username); - } - } + SecurityContext context = SecurityContextHolder.getContext(); + Authentication authentication = context.getAuthentication(); + if (authentication != null) { + if (authentication.getPrincipal() instanceof FrequentFlyerDetails) { + FrequentFlyerDetails details = (FrequentFlyerDetails) authentication.getPrincipal(); + return details.getFrequentFlyer(); + } else { + return (FrequentFlyer) authentication.getPrincipal(); + } + } else { + return null; + } + } - @Transactional - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { - FrequentFlyer frequentFlyer = frequentFlyerDao.get(username); - if (frequentFlyer != null) { - return new FrequentFlyerDetails(frequentFlyer); - } - else { - throw new UsernameNotFoundException("Frequent flyer '" + username + "' not found"); - } - } + @Transactional + public FrequentFlyer getFrequentFlyer(String username) throws NoSuchFrequentFlyerException { + FrequentFlyer frequentFlyer = frequentFlyerDao.get(username); + if (frequentFlyer != null) { + return frequentFlyer; + } else { + throw new NoSuchFrequentFlyerException(username); + } + } + + @Transactional + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { + + FrequentFlyer frequentFlyer = frequentFlyerDao.get(username); + if (frequentFlyer != null) { + return new FrequentFlyerDetails(frequentFlyer); + } else { + throw new UsernameNotFoundException("Frequent flyer '" + username + "' not found"); + } + } } diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/service/AirlineService.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/service/AirlineService.java index 851a5a4..5835b99 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/service/AirlineService.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/service/AirlineService.java @@ -15,11 +15,10 @@ */ package org.springframework.ws.samples.airline.service; +import java.time.ZonedDateTime; import java.util.List; -import org.joda.time.DateTime; import org.joda.time.LocalDate; - import org.springframework.ws.samples.airline.domain.Flight; import org.springframework.ws.samples.airline.domain.FrequentFlyer; import org.springframework.ws.samples.airline.domain.Passenger; @@ -52,9 +51,9 @@ public interface AirlineService { * @return a list of flights */ List getFlights(String fromAirportCode, - String toAirportCode, - LocalDate departureDate, - ServiceClass serviceClass); + String toAirportCode, + LocalDate departureDate, + ServiceClass serviceClass); /** * Books a single flight for a number of passengers. Passengers can be either specified by name or by frequent flyer @@ -69,10 +68,10 @@ public interface AirlineService { * exist * @throws NoSeatAvailableException if not enough seats are available for the flight * @throws NoSuchFrequentFlyerException if a specified {@link FrequentFlyer} cannot be found - * @see org.springframework.ws.samples.airline.domain.Passenger - * @see org.springframework.ws.samples.airline.domain.FrequentFlyer + * @see Passenger + * @see FrequentFlyer */ - Ticket bookFlight(String flightNumber, DateTime departureTime, List passengers) + Ticket bookFlight(String flightNumber, ZonedDateTime departureTime, List passengers) throws NoSuchFlightException, NoSeatAvailableException, NoSuchFrequentFlyerException; /** diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/service/NoSuchFlightException.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/service/NoSuchFlightException.java index b79db40..e6681ca 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/service/NoSuchFlightException.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/service/NoSuchFlightException.java @@ -16,7 +16,8 @@ package org.springframework.ws.samples.airline.service; -import org.joda.time.DateTime; +import java.time.ZonedDateTime; + import org.springframework.ws.soap.server.endpoint.annotation.FaultCode; import org.springframework.ws.soap.server.endpoint.annotation.SoapFault; @@ -30,9 +31,9 @@ public class NoSuchFlightException extends Exception { private String flightNumber; - private DateTime departureTime; + private ZonedDateTime departureTime; - public NoSuchFlightException(String flightNumber, DateTime departureTime) { + public NoSuchFlightException(String flightNumber, ZonedDateTime departureTime) { super("No flight with number [" + flightNumber + "] and departure time [" + departureTime + "]"); this.flightNumber = flightNumber; this.departureTime = departureTime; @@ -46,7 +47,7 @@ public class NoSuchFlightException extends Exception { return flightNumber; } - public DateTime getDepartureTime() { + public ZonedDateTime getDepartureTime() { return departureTime; } } diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/service/impl/AirlineServiceImpl.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/service/impl/AirlineServiceImpl.java index c9cfec1..9680689 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/service/impl/AirlineServiceImpl.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/service/impl/AirlineServiceImpl.java @@ -15,8 +15,12 @@ */ package org.springframework.ws.samples.airline.service.impl; +import java.time.ZonedDateTime; import java.util.List; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.joda.time.LocalDate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Service; @@ -36,11 +40,6 @@ import org.springframework.ws.samples.airline.service.NoSeatAvailableException; import org.springframework.ws.samples.airline.service.NoSuchFlightException; import org.springframework.ws.samples.airline.service.NoSuchFrequentFlyerException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; - /** * Default implementation of the AirlineService interface. * @@ -50,97 +49,96 @@ import org.joda.time.LocalDate; @Transactional(readOnly = true) public class AirlineServiceImpl implements AirlineService { - private static final Log logger = LogFactory.getLog(AirlineServiceImpl.class); + private static final Log logger = LogFactory.getLog(AirlineServiceImpl.class); - private FlightDao flightDao; + private FlightDao flightDao; - private TicketDao ticketDao; + private TicketDao ticketDao; - private FrequentFlyerSecurityService frequentFlyerSecurityService = new StubFrequentFlyerSecurityService(); + private FrequentFlyerSecurityService frequentFlyerSecurityService = new StubFrequentFlyerSecurityService(); - @Autowired - public AirlineServiceImpl(FlightDao flightDao, TicketDao ticketDao) { - this.flightDao = flightDao; - this.ticketDao = ticketDao; - } + @Autowired + public AirlineServiceImpl(FlightDao flightDao, TicketDao ticketDao) { - @Autowired(required = false) - public void setFrequentFlyerSecurityService(FrequentFlyerSecurityService frequentFlyerSecurityService) { - this.frequentFlyerSecurityService = frequentFlyerSecurityService; - } + this.flightDao = flightDao; + this.ticketDao = ticketDao; + } - @Transactional(readOnly = false, - rollbackFor = {NoSuchFlightException.class, NoSeatAvailableException.class, NoSuchFrequentFlyerException.class}) - public Ticket bookFlight(String flightNumber, DateTime departureTime, List passengers) - throws NoSuchFlightException, NoSeatAvailableException, NoSuchFrequentFlyerException { - Assert.notEmpty(passengers, "No passengers given"); - if (logger.isDebugEnabled()) { - logger.debug("Booking flight '" + flightNumber + "' on '" + departureTime + "' for " + passengers); - } - Flight flight = flightDao.getFlight(flightNumber, departureTime); - if (flight == null) { - throw new NoSuchFlightException(flightNumber, departureTime); - } - else if (flight.getSeatsAvailable() < passengers.size()) { - throw new NoSeatAvailableException(flight); - } - Ticket ticket = new Ticket(); - ticket.setIssueDate(new LocalDate()); - ticket.setFlight(flight); - for (Passenger passenger : passengers) { - // frequent flyer service is not required - if (passenger instanceof FrequentFlyer && frequentFlyerSecurityService != null) { - String username = ((FrequentFlyer) passenger).getUsername(); - Assert.hasLength(username, "No username specified"); - FrequentFlyer frequentFlyer = frequentFlyerSecurityService.getFrequentFlyer(username); - frequentFlyer.addMiles(flight.getMiles()); - ticket.addPassenger(frequentFlyer); - } - else { - ticket.addPassenger(passenger); - } - } - flight.substractSeats(passengers.size()); - flightDao.update(flight); - ticketDao.save(ticket); - return ticket; - } + @Autowired(required = false) + public void setFrequentFlyerSecurityService(FrequentFlyerSecurityService frequentFlyerSecurityService) { + this.frequentFlyerSecurityService = frequentFlyerSecurityService; + } - public Flight getFlight(Long id) throws NoSuchFlightException { - Flight flight = flightDao.getFlight(id); - if (flight != null) { - return flight; - } - else { - throw new NoSuchFlightException(id); - } - } + @Transactional(readOnly = false, + rollbackFor = { NoSuchFlightException.class, NoSeatAvailableException.class, NoSuchFrequentFlyerException.class }) + public Ticket bookFlight(String flightNumber, ZonedDateTime departureTime, List passengers) + throws NoSuchFlightException, NoSeatAvailableException, NoSuchFrequentFlyerException { - public List getFlights(String fromAirportCode, - String toAirportCode, - LocalDate departureDate, - ServiceClass serviceClass) { - if (serviceClass == null) { - serviceClass = ServiceClass.ECONOMY; - } - if (logger.isDebugEnabled()) { - logger.debug( - "Getting flights from '" + fromAirportCode + "' to '" + toAirportCode + "' on " + departureDate); - } - List flights = - flightDao.findFlights(fromAirportCode, toAirportCode, departureDate.toInterval(), serviceClass); - if (logger.isDebugEnabled()) { - logger.debug("Returning " + flights.size() + " flights"); - } - return flights; - } + Assert.notEmpty(passengers, "No passengers given"); + if (logger.isDebugEnabled()) { + logger.debug("Booking flight '" + flightNumber + "' on '" + departureTime + "' for " + passengers); + } + Flight flight = flightDao.getFlight(flightNumber, departureTime); + if (flight == null) { + throw new NoSuchFlightException(flightNumber, departureTime); + } else if (flight.getSeatsAvailable() < passengers.size()) { + throw new NoSeatAvailableException(flight); + } + Ticket ticket = new Ticket(); + ticket.setIssueDate(new LocalDate()); + ticket.setFlight(flight); + for (Passenger passenger : passengers) { + // frequent flyer service is not required + if (passenger instanceof FrequentFlyer && frequentFlyerSecurityService != null) { + String username = ((FrequentFlyer) passenger).getUsername(); + Assert.hasLength(username, "No username specified"); + FrequentFlyer frequentFlyer = frequentFlyerSecurityService.getFrequentFlyer(username); + frequentFlyer.addMiles(flight.getMiles()); + ticket.addPassenger(frequentFlyer); + } else { + ticket.addPassenger(passenger); + } + } + flight.substractSeats(passengers.size()); + flightDao.update(flight); + ticketDao.save(ticket); + return ticket; + } - @Secured({"ROLE_FREQUENT_FLYER"}) - public int getFrequentFlyerMileage() { - if (logger.isDebugEnabled()) { - logger.debug("Using " + frequentFlyerSecurityService + " for security"); - } - FrequentFlyer frequentFlyer = frequentFlyerSecurityService.getCurrentlyAuthenticatedFrequentFlyer(); - return frequentFlyer != null ? frequentFlyer.getMiles() : 0; - } + public Flight getFlight(Long id) throws NoSuchFlightException { + + Flight flight = flightDao.getFlight(id); + if (flight != null) { + return flight; + } else { + throw new NoSuchFlightException(id); + } + } + + public List getFlights(String fromAirportCode, String toAirportCode, LocalDate departureDate, + ServiceClass serviceClass) { + + if (serviceClass == null) { + serviceClass = ServiceClass.ECONOMY; + } + if (logger.isDebugEnabled()) { + logger.debug("Getting flights from '" + fromAirportCode + "' to '" + toAirportCode + "' on " + departureDate); + } + List flights = flightDao.findFlights(fromAirportCode, toAirportCode, departureDate.toInterval(), + serviceClass); + if (logger.isDebugEnabled()) { + logger.debug("Returning " + flights.size() + " flights"); + } + return flights; + } + + @Secured({ "ROLE_FREQUENT_FLYER" }) + public int getFrequentFlyerMileage() { + + if (logger.isDebugEnabled()) { + logger.debug("Using " + frequentFlyerSecurityService + " for security"); + } + FrequentFlyer frequentFlyer = frequentFlyerSecurityService.getCurrentlyAuthenticatedFrequentFlyer(); + return frequentFlyer != null ? frequentFlyer.getMiles() : 0; + } } diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/web/FlightsController.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/web/FlightsController.java index 19e8525..0518fd7 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/web/FlightsController.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/web/FlightsController.java @@ -16,65 +16,63 @@ package org.springframework.ws.samples.airline.web; -import org.springframework.beans.factory.annotation.Autowired; +import org.joda.time.LocalDate; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.Assert; import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.ws.samples.airline.domain.Flight; import org.springframework.ws.samples.airline.domain.ServiceClass; import org.springframework.ws.samples.airline.service.AirlineService; import org.springframework.ws.samples.airline.service.NoSuchFlightException; -import org.joda.time.LocalDate; - /** @author Arjen Poutsma */ @Controller @RequestMapping("/flights") public class FlightsController { - private AirlineService airlineService; + private AirlineService airlineService; - @Autowired - public FlightsController(AirlineService airlineService) { - Assert.notNull(airlineService, "'airlineService' must not be null"); - this.airlineService = airlineService; - } + public FlightsController(AirlineService airlineService) { - @RequestMapping - public String flightList(@RequestParam(value = "from", required = false)String fromAirportCode, - @RequestParam(value = "to", required = false)String toAirportCode, - @RequestParam(value = "departureDate", required = false)String departureDateString, - @RequestParam(value = "serviceClass", required = false)String serviceClassString, - ModelMap model) { - if (!StringUtils.hasLength(departureDateString)) { - departureDateString = new LocalDate().toString(); - } - if (!StringUtils.hasLength(serviceClassString)) { - serviceClassString = "ECONOMY"; - } - ServiceClass serviceClass = ServiceClass.valueOf(serviceClassString); - LocalDate departureDate = new LocalDate(departureDateString); + Assert.notNull(airlineService, "'airlineService' must not be null"); + this.airlineService = airlineService; + } - if (StringUtils.hasLength(fromAirportCode) && StringUtils.hasLength(toAirportCode)) { - model.addAttribute("from", fromAirportCode); - model.addAttribute("to", toAirportCode); - model.addAttribute("departureDate", departureDateString); - model.addAttribute("serviceClass", serviceClassString); - model.addAttribute("flights", - airlineService.getFlights(fromAirportCode, toAirportCode, departureDate, serviceClass)); - } - return "flights"; - } + @GetMapping + public String flightList(@RequestParam(value = "from", required = false) String fromAirportCode, + @RequestParam(value = "to", required = false) String toAirportCode, + @RequestParam(value = "departureDate", required = false) String departureDateString, + @RequestParam(value = "serviceClass", required = false) String serviceClassString, ModelMap model) { - @RequestMapping(value = "{id}") - public String singleFlight(@PathVariable("id") long id, ModelMap model) throws NoSuchFlightException { - Flight flight = airlineService.getFlight(id); - model.addAttribute(flight); - return "flight"; - } + if (StringUtils.isEmpty(departureDateString)) { + departureDateString = new LocalDate().toString(); + } + if (StringUtils.isEmpty(serviceClassString)) { + serviceClassString = "ECONOMY"; + } + ServiceClass serviceClass = ServiceClass.valueOf(serviceClassString); + LocalDate departureDate = new LocalDate(departureDateString); + + if (StringUtils.hasLength(fromAirportCode) && StringUtils.hasLength(toAirportCode)) { + model.addAttribute("from", fromAirportCode); + model.addAttribute("to", toAirportCode); + model.addAttribute("departureDate", departureDateString); + model.addAttribute("serviceClass", serviceClassString); + model.addAttribute("flights", + airlineService.getFlights(fromAirportCode, toAirportCode, departureDate, serviceClass)); + } + return "flights"; + } + + @GetMapping(value = "{id}") + public String singleFlight(@PathVariable("id") long id, ModelMap model) throws NoSuchFlightException { + + model.addAttribute(airlineService.getFlight(id)); + return "flight"; + } } diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/ws/AirlineEndpoint.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/ws/AirlineEndpoint.java index e0c9f8d..203d539 100644 --- a/airline/server/src/main/java/org/springframework/ws/samples/airline/ws/AirlineEndpoint.java +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/ws/AirlineEndpoint.java @@ -16,15 +16,22 @@ package org.springframework.ws.samples.airline.ws; +import static org.springframework.ws.samples.airline.ws.AirlineWebServiceConstants.*; + +import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Iterator; import java.util.List; + import javax.xml.bind.JAXBElement; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.joda.time.LocalDate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.ws.samples.airline.domain.FrequentFlyer; @@ -46,16 +53,9 @@ import org.springframework.ws.server.endpoint.annotation.PayloadRoot; import org.springframework.ws.server.endpoint.annotation.RequestPayload; import org.springframework.ws.server.endpoint.annotation.ResponsePayload; import org.springframework.ws.server.endpoint.annotation.XPathParam; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; import org.w3c.dom.Document; import org.w3c.dom.Element; -import static org.springframework.ws.samples.airline.ws.AirlineWebServiceConstants.*; - /** * Endpoint that handles the Airline Web Service messages using a combination of JAXB2 marshalling and XPath * expressions. @@ -65,115 +65,122 @@ import static org.springframework.ws.samples.airline.ws.AirlineWebServiceConstan @Endpoint public class AirlineEndpoint { - private static final Log logger = LogFactory.getLog(AirlineEndpoint.class); + private static final Log logger = LogFactory.getLog(AirlineEndpoint.class); - private final ObjectFactory objectFactory = new ObjectFactory(); + private final ObjectFactory objectFactory = new ObjectFactory(); - private final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + private final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - private final AirlineService airlineService; + private final AirlineService airlineService; - @Autowired - public AirlineEndpoint(AirlineService airlineService) { - this.airlineService = airlineService; - } + @Autowired + public AirlineEndpoint(AirlineService airlineService) { + this.airlineService = airlineService; + } - /** - * This endpoint method uses a combination of XPath expressions and marshalling to handle message with a - * <GetFlightsRequest> payload. - * - * @param from the from airport - * @param to the to airport - * @param departureDateString the string representation of the departure date - * @param serviceClassString the string representation of the service class - * @return the JAXB2 representation of a <GetFlightsResponse> - */ - @PayloadRoot(localPart = GET_FLIGHTS_REQUEST, namespace = MESSAGES_NAMESPACE) - @Namespace(prefix = "m", uri = MESSAGES_NAMESPACE) - @ResponsePayload - public GetFlightsResponse getFlights(@XPathParam("//m:from") String from, - @XPathParam("//m:to") String to, - @XPathParam("//m:departureDate") String departureDateString, - @XPathParam("//m:serviceClass") String serviceClassString) - throws DatatypeConfigurationException { - if (logger.isDebugEnabled()) { - logger.debug("Received GetFlightsRequest '" + from + "' to '" + to + "' on " + departureDateString); - } - LocalDate departureDate = new LocalDate(departureDateString); - ServiceClass serviceClass = null; - if (StringUtils.hasLength(serviceClassString)) { - serviceClass = ServiceClass.valueOf(serviceClassString.toUpperCase()); - } - List flights = - airlineService.getFlights(from, to, departureDate, serviceClass); + /** + * This endpoint method uses a combination of XPath expressions and marshalling to handle message with a + * <GetFlightsRequest> payload. + * + * @param from the from airport + * @param to the to airport + * @param departureDateString the string representation of the departure date + * @param serviceClassString the string representation of the service class + * @return the JAXB2 representation of a <GetFlightsResponse> + */ + @PayloadRoot(localPart = GET_FLIGHTS_REQUEST, namespace = MESSAGES_NAMESPACE) + @Namespace(prefix = "m", uri = MESSAGES_NAMESPACE) + @ResponsePayload + public GetFlightsResponse getFlights(@XPathParam("//m:from") String from, @XPathParam("//m:to") String to, + @XPathParam("//m:departureDate") String departureDateString, + @XPathParam("//m:serviceClass") String serviceClassString) throws DatatypeConfigurationException { - GetFlightsResponse response = objectFactory.createGetFlightsResponse(); - for (org.springframework.ws.samples.airline.domain.Flight domainFlight : flights) { - response.getFlight().add(SchemaConversionUtils.toSchemaType(domainFlight)); - } - return response; - } + if (logger.isDebugEnabled()) { + logger.debug("Received GetFlightsRequest '" + from + "' to '" + to + "' on " + departureDateString); + } - /** - * This endpoint method uses marshalling to handle message with a <BookFlightRequest> payload. - * - * @param request the JAXB2 representation of a <BookFlightRequest> - * @return the JAXB2 representation of a <BookFlightResponse> - */ - @PayloadRoot(localPart = BOOK_FLIGHT_REQUEST, namespace = MESSAGES_NAMESPACE) - @ResponsePayload - public JAXBElement bookFlight(@RequestPayload BookFlightRequest request) - throws NoSeatAvailableException, DatatypeConfigurationException, NoSuchFlightException, - NoSuchFrequentFlyerException { - if (logger.isDebugEnabled()) { - logger.debug("Received BookingFlightRequest '" + request.getFlightNumber() + "' on '" + - request.getDepartureTime() + "' for " + request.getPassengers().getPassengerOrUsername()); - } - Ticket ticket = bookSchemaFlight(request.getFlightNumber(), request.getDepartureTime(), - request.getPassengers().getPassengerOrUsername()); - return objectFactory.createBookFlightResponse(ticket); - } + LocalDate departureDate = new LocalDate(departureDateString); + ServiceClass serviceClass = null; - /** - * Converts between the domain and schema types. - */ - private Ticket bookSchemaFlight(String flightNumber, - XMLGregorianCalendar xmlDepartureTime, - List passengerOrUsernameList) - throws NoSeatAvailableException, NoSuchFlightException, NoSuchFrequentFlyerException, - DatatypeConfigurationException { - DateTime departureTime = SchemaConversionUtils.toDateTime(xmlDepartureTime); - List passengers = new ArrayList(passengerOrUsernameList.size()); - for (Iterator iterator = passengerOrUsernameList.iterator(); iterator.hasNext();) { - Object passengerOrUsername = iterator.next(); - if (passengerOrUsername instanceof Name) { - Name passengerName = (Name) passengerOrUsername; - Passenger passenger = new Passenger(passengerName.getFirst(), passengerName.getLast()); - passengers.add(passenger); - } - else if (passengerOrUsername instanceof String) { - String frequentFlyerUsername = (String) passengerOrUsername; - FrequentFlyer frequentFlyer = new FrequentFlyer(frequentFlyerUsername); - passengers.add(frequentFlyer); - } - } - org.springframework.ws.samples.airline.domain.Ticket domainTicket = - airlineService.bookFlight(flightNumber, departureTime, passengers); - return SchemaConversionUtils.toSchemaType(domainTicket); - } + if (StringUtils.hasLength(serviceClassString)) { + serviceClass = ServiceClass.valueOf(serviceClassString.toUpperCase()); + } + List flights = airlineService.getFlights(from, to, + departureDate, serviceClass); - @PayloadRoot(localPart = GET_FREQUENT_FLYER_MILEAGE_REQUEST, namespace = MESSAGES_NAMESPACE) - @ResponsePayload - public Element getFrequentFlyerMileage() throws Exception { - if (logger.isDebugEnabled()) { - logger.debug("Received GetFrequentFlyerMileageRequest"); - } - int mileage = airlineService.getFrequentFlyerMileage(); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); - Element response = document.createElementNS(MESSAGES_NAMESPACE, GET_FREQUENT_FLYER_MILEAGE_RESPONSE); - response.setTextContent(Integer.toString(mileage)); - return response; - } + GetFlightsResponse response = objectFactory.createGetFlightsResponse(); + for (org.springframework.ws.samples.airline.domain.Flight domainFlight : flights) { + response.getFlight().add(SchemaConversionUtils.toSchemaType(domainFlight)); + } + + return response; + } + + /** + * This endpoint method uses marshalling to handle message with a <BookFlightRequest> payload. + * + * @param request the JAXB2 representation of a <BookFlightRequest> + * @return the JAXB2 representation of a <BookFlightResponse> + */ + @PayloadRoot(localPart = BOOK_FLIGHT_REQUEST, namespace = MESSAGES_NAMESPACE) + @ResponsePayload + public JAXBElement bookFlight(@RequestPayload BookFlightRequest request) throws NoSeatAvailableException, + DatatypeConfigurationException, NoSuchFlightException, NoSuchFrequentFlyerException { + + if (logger.isDebugEnabled()) { + logger.debug("Received BookingFlightRequest '" + request.getFlightNumber() + "' on '" + request.getDepartureTime() + + "' for " + request.getPassengers().getPassengerOrUsername()); + } + + Ticket ticket = bookSchemaFlight(request.getFlightNumber(), request.getDepartureTime(), + request.getPassengers().getPassengerOrUsername()); + + return objectFactory.createBookFlightResponse(ticket); + } + + /** + * Converts between the domain and schema types. + */ + private Ticket bookSchemaFlight(String flightNumber, XMLGregorianCalendar xmlDepartureTime, + List passengerOrUsernameList) throws NoSeatAvailableException, NoSuchFlightException, + NoSuchFrequentFlyerException, DatatypeConfigurationException { + + ZonedDateTime departureTime = SchemaConversionUtils.toDateTime(xmlDepartureTime); + List passengers = new ArrayList(passengerOrUsernameList.size()); + + for (Iterator iterator = passengerOrUsernameList.iterator(); iterator.hasNext();) { + Object passengerOrUsername = iterator.next(); + if (passengerOrUsername instanceof Name) { + Name passengerName = (Name) passengerOrUsername; + Passenger passenger = new Passenger(passengerName.getFirst(), passengerName.getLast()); + passengers.add(passenger); + } else if (passengerOrUsername instanceof String) { + String frequentFlyerUsername = (String) passengerOrUsername; + FrequentFlyer frequentFlyer = new FrequentFlyer(frequentFlyerUsername); + passengers.add(frequentFlyer); + } + } + org.springframework.ws.samples.airline.domain.Ticket domainTicket = airlineService.bookFlight(flightNumber, + departureTime, passengers); + + return SchemaConversionUtils.toSchemaType(domainTicket); + } + + @PayloadRoot(localPart = GET_FREQUENT_FLYER_MILEAGE_REQUEST, namespace = MESSAGES_NAMESPACE) + @ResponsePayload + public Element getFrequentFlyerMileage() throws Exception { + + if (logger.isDebugEnabled()) { + logger.debug("Received GetFrequentFlyerMileageRequest"); + } + + int mileage = airlineService.getFrequentFlyerMileage(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.newDocument(); + Element response = document.createElementNS(MESSAGES_NAMESPACE, GET_FREQUENT_FLYER_MILEAGE_RESPONSE); + response.setTextContent(Integer.toString(mileage)); + + return response; + } } diff --git a/airline/server/src/main/java/org/springframework/ws/samples/airline/ws/WebServicesConfiguration.java b/airline/server/src/main/java/org/springframework/ws/samples/airline/ws/WebServicesConfiguration.java new file mode 100644 index 0000000..e2daf54 --- /dev/null +++ b/airline/server/src/main/java/org/springframework/ws/samples/airline/ws/WebServicesConfiguration.java @@ -0,0 +1,121 @@ +package org.springframework.ws.samples.airline.ws; + +import org.springframework.boot.web.server.MimeMappings; +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.util.MimeTypeUtils; +import org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor; +import org.springframework.ws.soap.saaj.SaajSoapMessageFactory; +import org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor; +import org.springframework.ws.soap.security.xwss.callback.SpringDigestPasswordValidationCallbackHandler; +import org.springframework.ws.soap.server.SoapMessageDispatcher; +import org.springframework.ws.soap.server.endpoint.interceptor.PayloadRootSmartSoapEndpointInterceptor; +import org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor; +import org.springframework.ws.transport.http.MessageDispatcherServlet; +import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition; +import org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection; + +@Configuration +public class WebServicesConfiguration { + + @Bean + WebServerFactoryCustomizer wsMimeMappings() { + + return factory -> { + MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT); + mappings.add("xsd", MimeTypeUtils.TEXT_XML_VALUE); + factory.setMimeMappings(mappings); + }; + } + + @Bean + ServletRegistrationBean webServicesRegistration(ApplicationContext ctx) { + + MessageDispatcherServlet messageDispatcherServlet = new MessageDispatcherServlet(); + messageDispatcherServlet.setApplicationContext(ctx); + messageDispatcherServlet.setTransformWsdlLocations(true); + + return new ServletRegistrationBean<>(messageDispatcherServlet, "/airline-server/*", "*.wsdl"); + } + + @Bean + PayloadLoggingInterceptor payloadLoggingInterceptor() { + return new PayloadLoggingInterceptor(); + } + + @Bean + PayloadValidatingInterceptor payloadValidatingInterceptor(CommonsXsdSchemaCollection xsdSchemaCollection) { + + PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor(); + payloadValidatingInterceptor.setXsdSchemaCollection(xsdSchemaCollection); + payloadValidatingInterceptor.setValidateRequest(true); + payloadValidatingInterceptor.setValidateResponse(true); + + return payloadValidatingInterceptor; + } + + @Bean + XwsSecurityInterceptor securityInterceptor(UserDetailsService securityService) { + + XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor(); + securityInterceptor.setSecureResponse(false); + securityInterceptor.setPolicyConfiguration( + new ClassPathResource("org/springframework/ws/samples/airline/security/securityPolicy.xml")); + securityInterceptor.setCallbackHandler(springDigestPasswordValidationCallbackHandler(securityService)); + + return securityInterceptor; + } + + @Bean + PayloadRootSmartSoapEndpointInterceptor smartSoapEndpointInterceptor(XwsSecurityInterceptor securityInterceptor) { + + return new PayloadRootSmartSoapEndpointInterceptor(securityInterceptor, + "http://www.springframework.org/spring-ws/samples/airline/schemas/messages", "GetFrequentFlyerMileageRequest"); + } + + @Bean + SpringDigestPasswordValidationCallbackHandler springDigestPasswordValidationCallbackHandler( + UserDetailsService securityService) { + + SpringDigestPasswordValidationCallbackHandler handler = new SpringDigestPasswordValidationCallbackHandler(); + handler.setUserDetailsService(securityService); + return handler; + } + + @Bean + SaajSoapMessageFactory messageFactory() { + return new SaajSoapMessageFactory(); + } + + @Bean + SoapMessageDispatcher dispatcher() { + return new SoapMessageDispatcher(); + } + + @Bean + CommonsXsdSchemaCollection commonsXsdSchemaCollection() { + + CommonsXsdSchemaCollection commonsXsdSchemaCollection = new CommonsXsdSchemaCollection(); + commonsXsdSchemaCollection.setXsds(new ClassPathResource("messages.xsd")); + commonsXsdSchemaCollection.setInline(true); + return commonsXsdSchemaCollection; + } + + @Bean("services") + DefaultWsdl11Definition airline(CommonsXsdSchemaCollection schemaCollection) { + + DefaultWsdl11Definition definition = new DefaultWsdl11Definition(); + definition.setSchemaCollection(schemaCollection); + definition.setPortTypeName("Airline"); + definition.setLocationUri("http://localhost:8080/airline-server/services"); + definition.setTargetNamespace("http://www.springframework.org/spring-ws/samples/airline/definitions"); + return definition; + } + +} diff --git a/airline/server/src/main/resources/META-INF/persistence.xml b/airline/server/src/main/resources/META-INF/persistence.xml deleted file mode 100644 index 0834a67..0000000 --- a/airline/server/src/main/resources/META-INF/persistence.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - org.apache.openjpa.persistence.PersistenceProviderImpl - org.springframework.ws.samples.airline.domain.Airport - org.springframework.ws.samples.airline.domain.Flight - org.springframework.ws.samples.airline.domain.FrequentFlyer - org.springframework.ws.samples.airline.domain.Passenger - org.springframework.ws.samples.airline.domain.Ticket - - - diff --git a/airline/server/src/main/resources/application.properties b/airline/server/src/main/resources/application.properties new file mode 100644 index 0000000..0f447a3 --- /dev/null +++ b/airline/server/src/main/resources/application.properties @@ -0,0 +1,3 @@ +logging.level.org.springframework.data=DEBUG +logging.level.org.springframework.ws=DEBUG +logging.level.org.springframework.web=DEBUG diff --git a/airline/server/src/main/resources/log4j.properties b/airline/server/src/main/resources/log4j.properties deleted file mode 100644 index c44d7a4..0000000 --- a/airline/server/src/main/resources/log4j.properties +++ /dev/null @@ -1,8 +0,0 @@ -log4j.rootLogger=WARN, stdout -log4j.logger.org.springframework.ws=DEBUG -log4j.logger.org.springframework.xml=DEBUG -log4j.logger.openjpa=INFO - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n \ No newline at end of file diff --git a/airline/server/src/main/webapp/messages.xsd b/airline/server/src/main/resources/messages.xsd similarity index 100% rename from airline/server/src/main/webapp/messages.xsd rename to airline/server/src/main/resources/messages.xsd diff --git a/airline/server/src/main/resources/org/springframework/ws/samples/airline/dao/jpa/applicationContext-jpa.xml b/airline/server/src/main/resources/org/springframework/ws/samples/airline/dao/jpa/applicationContext-jpa.xml deleted file mode 100644 index 20062a7..0000000 --- a/airline/server/src/main/resources/org/springframework/ws/samples/airline/dao/jpa/applicationContext-jpa.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - commons - buildSchema - - FieldStrategies='org.joda.time.DateTime=org.springframework.ws.samples.airline.domain.openjpa.DateTimeValueHandler, - org.joda.time.LocalDate=org.springframework.ws.samples.airline.domain.openjpa.LocalDateValueHandler' - - org.apache.openjpa.jdbc.sql.HSQLDictionary - - - - - - - - - - - - - - - - diff --git a/airline/server/src/main/resources/org/springframework/ws/samples/airline/jms/applicationContext-jms.xml b/airline/server/src/main/resources/org/springframework/ws/samples/airline/jms/applicationContext-jms.xml deleted file mode 100644 index 1fa957e..0000000 --- a/airline/server/src/main/resources/org/springframework/ws/samples/airline/jms/applicationContext-jms.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/airline/server/src/main/resources/org/springframework/ws/samples/airline/security/applicationContext-security.xml b/airline/server/src/main/resources/org/springframework/ws/samples/airline/security/applicationContext-security.xml deleted file mode 100644 index c51aee7..0000000 --- a/airline/server/src/main/resources/org/springframework/ws/samples/airline/security/applicationContext-security.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - This application context contains the WS-Security and Spring Security beans. - - - - - - - - - - - A security service used to obtain Frequent Flyer information. - - - - - \ No newline at end of file diff --git a/airline/server/src/main/resources/org/springframework/ws/samples/airline/security/securityPolicy.xml b/airline/server/src/main/resources/org/springframework/ws/samples/airline/security/securityPolicy.xml index 0d7140f..b6d644b 100644 --- a/airline/server/src/main/resources/org/springframework/ws/samples/airline/security/securityPolicy.xml +++ b/airline/server/src/main/resources/org/springframework/ws/samples/airline/security/securityPolicy.xml @@ -1,3 +1,3 @@ - + diff --git a/airline/server/src/main/resources/org/springframework/ws/samples/airline/service/applicationContext.xml b/airline/server/src/main/resources/org/springframework/ws/samples/airline/service/applicationContext.xml deleted file mode 100644 index 6cefe32..0000000 --- a/airline/server/src/main/resources/org/springframework/ws/samples/airline/service/applicationContext.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/airline/server/src/main/resources/org/springframework/ws/samples/airline/ws/applicationContext-ws.xml b/airline/server/src/main/resources/org/springframework/ws/samples/airline/ws/applicationContext-ws.xml deleted file mode 100644 index fd44eb4..0000000 --- a/airline/server/src/main/resources/org/springframework/ws/samples/airline/ws/applicationContext-ws.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This bean wrap the messages.xsd (which imports types.xsd), and inlines them as a one. - - - - - - diff --git a/airline/server/src/main/resources/templates/flight.html b/airline/server/src/main/resources/templates/flight.html new file mode 100644 index 0000000..feb65e1 --- /dev/null +++ b/airline/server/src/main/resources/templates/flight.html @@ -0,0 +1,41 @@ + + +Flights + + + + + + + + + + + + + + + + + + + + + + +
Number: + +
From: + + () +
Departure: + +
To: + + () +
Departure: + +
+Flights + + \ No newline at end of file diff --git a/airline/server/src/main/resources/templates/flights.html b/airline/server/src/main/resources/templates/flights.html new file mode 100644 index 0000000..84d2792 --- /dev/null +++ b/airline/server/src/main/resources/templates/flights.html @@ -0,0 +1,62 @@ + + +Flights + +
+ + + + + + + + + + + + + + + + + + + + +
From:
To:
Departure Date:
Service Class: + +
+ +
+
+ + + + + + + + + + + + +
NumberDepartsArrives
+ + + + () + + + + () + +
+
+
+ + \ No newline at end of file diff --git a/airline/server/src/main/resources/templates/noSuchFlight.html b/airline/server/src/main/resources/templates/noSuchFlight.html new file mode 100644 index 0000000..598a823 --- /dev/null +++ b/airline/server/src/main/resources/templates/noSuchFlight.html @@ -0,0 +1,12 @@ + + +No Such Flight + + +

+ +

No such flight:

+Flights + + + \ No newline at end of file diff --git a/airline/server/src/main/webapp/types.xsd b/airline/server/src/main/resources/types.xsd similarity index 100% rename from airline/server/src/main/webapp/types.xsd rename to airline/server/src/main/resources/types.xsd diff --git a/airline/server/src/main/webapp/WEB-INF/jsp/error.jsp b/airline/server/src/main/webapp/WEB-INF/jsp/error.jsp deleted file mode 100644 index d7654d9..0000000 --- a/airline/server/src/main/webapp/WEB-INF/jsp/error.jsp +++ /dev/null @@ -1,13 +0,0 @@ -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> - -<% - Exception ex = (Exception) request.getAttribute("exception"); -%> -<%= ex.getMessage() %> - - -

<%= ex.getMessage() %> -

-Flights - - \ No newline at end of file diff --git a/airline/server/src/main/webapp/WEB-INF/jsp/flight.jsp b/airline/server/src/main/webapp/WEB-INF/jsp/flight.jsp deleted file mode 100644 index 7c76fc0..0000000 --- a/airline/server/src/main/webapp/WEB-INF/jsp/flight.jsp +++ /dev/null @@ -1,47 +0,0 @@ -<%@ page contentType="text/html;charset=UTF-8" language="java" %> -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="joda" uri="http://www.joda.org/joda/time/tags" %> - -Flights - - - - - - - - - - - - - - - - - - - - - - -
Number: - -
From: - - ( - - ) -
Departure: - -
To: - - ( - - ) -
Departure: - -
-Flights - - \ No newline at end of file diff --git a/airline/server/src/main/webapp/WEB-INF/jsp/flights.jsp b/airline/server/src/main/webapp/WEB-INF/jsp/flights.jsp deleted file mode 100644 index 441c92e..0000000 --- a/airline/server/src/main/webapp/WEB-INF/jsp/flights.jsp +++ /dev/null @@ -1,73 +0,0 @@ -<%@ page contentType="text/html;charset=UTF-8" language="java" %> -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> -<%@ taglib prefix="joda" uri="http://www.joda.org/joda/time/tags" %> - -Flights - -
- - - - - - - - - - - - - - - - - - - - -
From:
To:"/>
Departure Date:"/>
Service Class: - -
- -
- - - - - - - - - - - - - - -
NumberDepartsArrives
- - - - - - - ( - - ) - - - - ( - - ) - -
-
-
- - \ No newline at end of file diff --git a/airline/server/src/main/webapp/WEB-INF/jsp/noSuchFlight.jsp b/airline/server/src/main/webapp/WEB-INF/jsp/noSuchFlight.jsp deleted file mode 100644 index 2a6ede9..0000000 --- a/airline/server/src/main/webapp/WEB-INF/jsp/noSuchFlight.jsp +++ /dev/null @@ -1,13 +0,0 @@ -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> - -No Such Flight - -<% - Exception ex = (Exception) request.getAttribute("exception"); -%> -

No such flight: <%= ex.getMessage() %> -

-Flights - - - \ No newline at end of file diff --git a/airline/server/src/main/webapp/WEB-INF/mvc-servlet.xml b/airline/server/src/main/webapp/WEB-INF/mvc-servlet.xml deleted file mode 100644 index 9a71074..0000000 --- a/airline/server/src/main/webapp/WEB-INF/mvc-servlet.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - This web application context contains a simple Spring Web MVC web application that shows flights - - - - - - - - - - - - - - - - - - noSuchFlight - - - - - - \ No newline at end of file diff --git a/airline/server/src/main/webapp/WEB-INF/web.xml b/airline/server/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 12586dc..0000000 --- a/airline/server/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - Spring-WS Airline Sample - - contextConfigLocation - - classpath:org/springframework/ws/samples/airline/dao/jpa/applicationContext-jpa.xml - classpath:org/springframework/ws/samples/airline/service/applicationContext.xml - classpath:org/springframework/ws/samples/airline/security/applicationContext-security.xml - classpath:org/springframework/ws/samples/airline/ws/applicationContext-ws.xml - classpath:org/springframework/ws/samples/airline/jms/applicationContext-jms.xml - - - - org.springframework.web.context.ContextLoaderListener - - - ws - org.springframework.ws.transport.http.MessageDispatcherServlet - - - ws - /services - - - ws - *.wsdl - - - mvc - org.springframework.web.servlet.DispatcherServlet - - - mvc - *.html - - - xsd - text/xml - - - index.jsp - - \ No newline at end of file diff --git a/airline/server/src/main/webapp/WEB-INF/ws-servlet.xml b/airline/server/src/main/webapp/WEB-INF/ws-servlet.xml deleted file mode 100644 index eda6c0c..0000000 --- a/airline/server/src/main/webapp/WEB-INF/ws-servlet.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - Builds a WSDL from the airline.xsd.This bean definition represents the airline.wsdl file found - in the root of the web application. - - - - - - - - \ No newline at end of file diff --git a/airline/server/src/main/webapp/index.jsp b/airline/server/src/main/webapp/index.jsp deleted file mode 100644 index 0937555..0000000 --- a/airline/server/src/main/webapp/index.jsp +++ /dev/null @@ -1,3 +0,0 @@ -<%@ page contentType="text/html;charset=UTF-8" language="java" %> -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> - \ No newline at end of file diff --git a/airline/server/src/test/java/org/springframework/ws/samples/airline/dao/jpa/JpaFlightDaoTest.java b/airline/server/src/test/java/org/springframework/ws/samples/airline/dao/jpa/JpaFlightDaoTest.java deleted file mode 100644 index 3637cdf..0000000 --- a/airline/server/src/test/java/org/springframework/ws/samples/airline/dao/jpa/JpaFlightDaoTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2005-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. - */ - -package org.springframework.ws.samples.airline.dao.jpa; - -import java.util.List; -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.transaction.BeforeTransaction; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.ws.samples.airline.dao.FlightDao; -import org.springframework.ws.samples.airline.domain.Airport; -import org.springframework.ws.samples.airline.domain.Flight; -import org.springframework.ws.samples.airline.domain.ServiceClass; - -import org.joda.time.DateTime; -import org.joda.time.Interval; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.*; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("applicationContext-jpa.xml") -@Transactional -public class JpaFlightDaoTest { - - private DateTime departureTime; - - private DateTime arrivalTime; - - private Interval interval; - - private Airport fromAirport; - - private Airport toAirport; - - @Autowired - private FlightDao flightDao; - - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(DataSource dataSource) { - jdbcTemplate = new JdbcTemplate(dataSource); - } - - @BeforeTransaction - public void createTestData() { - departureTime = new DateTime(2006, 1, 31, 10, 5, 0, 0); - arrivalTime = new DateTime(2006, 1, 31, 12, 25, 0, 0); - interval = departureTime.toLocalDate().toInterval(); - fromAirport = new Airport("RTM", "Rotterdam Airport", "Rotterdam"); - toAirport = new Airport("OSL", "Gardermoen", "Oslo"); - } - - @Before - public void insertTestData() { - jdbcTemplate.update("INSERT INTO AIRPORT(CODE, NAME, CITY) VALUES('RTM', 'Rotterdam Airport', 'Rotterdam')"); - jdbcTemplate.update("INSERT INTO AIRPORT(CODE, NAME, CITY) VALUES('OSL', 'Gardermoen', 'Oslo')"); - } - - @Test - public void getFlightsInPeriod() throws Exception { - jdbcTemplate - .update("INSERT INTO FLIGHT(NUMBER, DEPARTURE_TIME, FROM_AIRPORT_CODE, ARRIVAL_TIME, TO_AIRPORT_CODE, SERVICE_CLASS, SEATS_AVAILABLE, MILES) " + - "VALUES ('KL020','2006-01-31 10:05:00', 'RTM', '2006-01-31 12:25:00', 'OSL', 'BUSINESS', 90, 10)"); - List flights = flightDao.findFlights("RTM", "OSL", interval, ServiceClass.BUSINESS); - assertNotNull("Invalid result", flights); - assertEquals("Invalid amount of flights", 1, flights.size()); - } - - @Test - public void getFlightsOutOfPeriod() throws Exception { - jdbcTemplate - .update("INSERT INTO FLIGHT(NUMBER, DEPARTURE_TIME, FROM_AIRPORT_CODE, ARRIVAL_TIME, TO_AIRPORT_CODE, SERVICE_CLASS, SEATS_AVAILABLE, MILES) " + - "VALUES ('KL020','2006-01-31 10:05:00', 'RTM', '2006-01-31 12:25:00', 'OSL', 'BUSINESS', 90, 10)"); - DateTime dateTime = new DateTime(2006, 6, 1, 0, 0, 0, 0); - List flights = flightDao.findFlights("RTM", "OSL", new Interval(dateTime, dateTime), ServiceClass.BUSINESS); - assertNotNull("Invalid result", flights); - assertEquals("Invalid amount of flights", 0, flights.size()); - } - - @Test - public void getFlightByNumberDepartureTime() throws Exception { - jdbcTemplate - .update("INSERT INTO FLIGHT(NUMBER, DEPARTURE_TIME, FROM_AIRPORT_CODE, ARRIVAL_TIME, TO_AIRPORT_CODE, SERVICE_CLASS, SEATS_AVAILABLE, MILES) " + - "VALUES ('KL020','2006-01-31 10:05:00', 'RTM', '2006-01-31 12:25:00', 'OSL', 'BUSINESS', 90, 10)"); - Flight flight = flightDao.getFlight("KL020", departureTime); - assertNotNull("No flight returned", flight); - assertNotNull("Invalid flight id", flight.getId()); - assertEquals("Invalid flight number", "KL020", flight.getNumber()); - assertEquals("Invalid flight departure time", departureTime, flight.getDepartureTime()); - assertEquals("Invalid flight arrival time", arrivalTime, flight.getArrivalTime()); - assertEquals("Invalid flight from airport", fromAirport, flight.getFrom()); - assertEquals("Invalid flight to airport", toAirport, flight.getTo()); - assertEquals("Invalid flight service class", ServiceClass.BUSINESS, flight.getServiceClass()); - } - - @Test - public void noSuchFlight() { - Flight flight = flightDao.getFlight("INVALID", departureTime); - assertNull("Flight returned", flight); - } - -} \ No newline at end of file diff --git a/airline/server/src/test/java/org/springframework/ws/samples/airline/dao/jpa/JpaFrequentFlyerDaoTest.java b/airline/server/src/test/java/org/springframework/ws/samples/airline/dao/jpa/JpaFrequentFlyerDaoTest.java deleted file mode 100644 index b6e20c5..0000000 --- a/airline/server/src/test/java/org/springframework/ws/samples/airline/dao/jpa/JpaFrequentFlyerDaoTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2005-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. - */ - -package org.springframework.ws.samples.airline.dao.jpa; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.ws.samples.airline.domain.FrequentFlyer; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.*; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("applicationContext-jpa.xml") -@Transactional -public class JpaFrequentFlyerDaoTest { - - @Autowired - private JpaFrequentFlyerDao frequentFlyerDao; - - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(DataSource dataSource) { - jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Before - public void insertTestData() { - jdbcTemplate - .update("INSERT INTO PASSENGER(ID, FIRST_NAME, LAST_NAME) " + "VALUES (42, 'Arjen', 'Poutsma')"); - jdbcTemplate - .update("INSERT INTO FREQUENT_FLYER(PASSENGER_ID, USERNAME, PASSWORD, MILES) " + - "VALUES (42, 'arjen', 'changeme', 0)"); - } - - @Test - public void getByUsername() throws Exception { - FrequentFlyer flyer = frequentFlyerDao.get("arjen"); - assertNotNull("No frequent flyer returned", flyer); - assertEquals("Invalid username", "arjen", flyer.getUsername()); - assertEquals("Invalid password", "changeme", flyer.getPassword()); - assertEquals("Invalid first name", "Arjen", flyer.getFirstName()); - assertEquals("Invalid last name", "Poutsma", flyer.getLastName()); - } - - @Test - public void noSuchUsername() { - FrequentFlyer flyer = frequentFlyerDao.get("invalid"); - assertNull("FrequentFlyer returned", flyer); - } -} \ No newline at end of file diff --git a/airline/server/src/test/java/org/springframework/ws/samples/airline/dao/jpa/JpaTicketDaoTest.java b/airline/server/src/test/java/org/springframework/ws/samples/airline/dao/jpa/JpaTicketDaoTest.java deleted file mode 100644 index 2e4a5f7..0000000 --- a/airline/server/src/test/java/org/springframework/ws/samples/airline/dao/jpa/JpaTicketDaoTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2005-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. - */ - -package org.springframework.ws.samples.airline.dao.jpa; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.ws.samples.airline.domain.Flight; -import org.springframework.ws.samples.airline.domain.Passenger; -import org.springframework.ws.samples.airline.domain.Ticket; - -import org.joda.time.LocalDate; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("applicationContext-jpa.xml") -@Transactional -public class JpaTicketDaoTest { - - @Autowired - private JpaTicketDao ticketDao; - - @Autowired - private JpaFlightDao flightDao; - - private JdbcTemplate jdbcTemplate; - - @Autowired - public void setDataSource(DataSource dataSource) { - jdbcTemplate = new JdbcTemplate(dataSource); - } - - @Before - public void insertTestData() { - jdbcTemplate.update("INSERT INTO AIRPORT(CODE, NAME, CITY) VALUES('RTM', 'Rotterdam Airport', 'Rotterdam')"); - jdbcTemplate.update("INSERT INTO AIRPORT(CODE, NAME, CITY) VALUES('OSL', 'Gardermoen', 'Oslo')"); - jdbcTemplate - .update("INSERT INTO FLIGHT(ID, NUMBER, DEPARTURE_TIME, FROM_AIRPORT_CODE, ARRIVAL_TIME, TO_AIRPORT_CODE, SERVICE_CLASS, SEATS_AVAILABLE, MILES) " + - "VALUES (42, 'KL020','2006-01-31 10:05:00', 'RTM', '2006-01-31 12:25:00', 'OSL', 'BUSINESS', 90, 10)"); - } - - @Test - public void save() throws Exception { - Passenger passenger = new Passenger("Arjen", "Poutsma"); - Flight flight = flightDao.getFlight(42L); - Ticket ticket = new Ticket(); - ticket.addPassenger(passenger); - ticket.setFlight(flight); - ticket.setIssueDate(new LocalDate()); - int startTicketCount = jdbcTemplate.queryForInt("SELECT COUNT(0) FROM TICKET"); - int startPassengerCount = jdbcTemplate.queryForInt("SELECT COUNT(0) FROM PASSENGER"); - ticketDao.save(ticket); - assertNotNull("No Id generated", ticket.getId()); - int endTicketCount = jdbcTemplate.queryForInt("SELECT COUNT(0) FROM TICKET"); - int endPassengerCount = jdbcTemplate.queryForInt("SELECT COUNT(0) FROM PASSENGER"); - assertEquals("Flight not inserted", 1, endTicketCount - startTicketCount); - assertEquals("Passenger not inserted", 1, endPassengerCount - startPassengerCount); - } - -} \ No newline at end of file diff --git a/airline/server/src/test/java/org/springframework/ws/samples/airline/security/SpringFrequentFlyerSecurityServiceTest.java b/airline/server/src/test/java/org/springframework/ws/samples/airline/security/SpringFrequentFlyerSecurityServiceTest.java deleted file mode 100644 index 6cbf555..0000000 --- a/airline/server/src/test/java/org/springframework/ws/samples/airline/security/SpringFrequentFlyerSecurityServiceTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2005-2012 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. - */ - -package org.springframework.ws.samples.airline.security; - -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.context.SecurityContextImpl; -import org.springframework.ws.samples.airline.dao.FrequentFlyerDao; -import org.springframework.ws.samples.airline.domain.FrequentFlyer; - -import junit.framework.TestCase; - -import static org.easymock.EasyMock.*; - -public class SpringFrequentFlyerSecurityServiceTest extends TestCase { - - private SpringFrequentFlyerSecurityService securityService; - - private FrequentFlyerDao flyerDaoMock; - - @Override - protected void setUp() throws Exception { - flyerDaoMock = createMock(FrequentFlyerDao.class); - securityService = new SpringFrequentFlyerSecurityService(flyerDaoMock); - } - - public void testGetCurrentlyAuthenticatedFrequentFlyer() throws Exception { - FrequentFlyer frequentFlyer = new FrequentFlyer("john"); - FrequentFlyerDetails detail = new FrequentFlyerDetails(frequentFlyer); - TestingAuthenticationToken token = new TestingAuthenticationToken(detail, null); - SecurityContext context = new SecurityContextImpl(); - context.setAuthentication(token); - SecurityContextHolder.setContext(context); - replay(flyerDaoMock); - FrequentFlyer result = securityService.getCurrentlyAuthenticatedFrequentFlyer(); - assertEquals("Invalid result", frequentFlyer, result); - verify(flyerDaoMock); - } - - public void testGetFrequentFlyer() throws Exception { - FrequentFlyer frequentFlyer = new FrequentFlyer("john"); - expect(flyerDaoMock.get("john")).andReturn(frequentFlyer); - replay(flyerDaoMock); - FrequentFlyer result = securityService.getFrequentFlyer("john"); - assertEquals("Invalid result", frequentFlyer, result); - verify(flyerDaoMock); - } -} diff --git a/airline/server/src/test/java/org/springframework/ws/samples/airline/service/impl/AirlineServiceImplTest.java b/airline/server/src/test/java/org/springframework/ws/samples/airline/service/impl/AirlineServiceImplTest.java deleted file mode 100644 index db5cb71..0000000 --- a/airline/server/src/test/java/org/springframework/ws/samples/airline/service/impl/AirlineServiceImplTest.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright 2005-2010 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. - */ - -package org.springframework.ws.samples.airline.service.impl; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import junit.framework.TestCase; -import static org.easymock.EasyMock.*; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.springframework.ws.samples.airline.dao.FlightDao; -import org.springframework.ws.samples.airline.dao.TicketDao; -import org.springframework.ws.samples.airline.domain.Flight; -import org.springframework.ws.samples.airline.domain.FrequentFlyer; -import org.springframework.ws.samples.airline.domain.Passenger; -import org.springframework.ws.samples.airline.domain.ServiceClass; -import org.springframework.ws.samples.airline.domain.Ticket; -import org.springframework.ws.samples.airline.security.FrequentFlyerSecurityService; -import org.springframework.ws.samples.airline.service.NoSeatAvailableException; -import org.springframework.ws.samples.airline.service.NoSuchFlightException; - -public class AirlineServiceImplTest extends TestCase { - - private AirlineServiceImpl airlineService; - - private FlightDao flightDaoMock; - - private TicketDao ticketDaoMock; - - private FrequentFlyerSecurityService securityServiceMock; - - private String flightNumber; - - @Override - protected void setUp() throws Exception { - flightDaoMock = createMock(FlightDao.class); - ticketDaoMock = createMock(TicketDao.class); - airlineService = new AirlineServiceImpl(flightDaoMock, ticketDaoMock); - securityServiceMock = createMock(FrequentFlyerSecurityService.class); - airlineService.setFrequentFlyerSecurityService(securityServiceMock); - flightNumber = "AB1234"; - } - - public void testBookFlight() throws Exception { - DateTime departureTime = new DateTime(); - Passenger passenger = new Passenger("John", "Doe"); - List passengers = new ArrayList(); - passengers.add(passenger); - Flight flight = new Flight(); - flight.setNumber(flightNumber); - flight.setSeatsAvailable(10); - expect(flightDaoMock.getFlight(flightNumber, departureTime)).andReturn(flight); - expect(flightDaoMock.update(flight)).andReturn(flight); - Ticket ticket = new Ticket(); - ticket.setFlight(flight); - ticketDaoMock.save(isA(Ticket.class)); - - replay(flightDaoMock, ticketDaoMock, securityServiceMock); - - ticket = airlineService.bookFlight(flightNumber, departureTime, passengers); - assertNotNull("Invalid ticket", ticket); - assertEquals("Invalid flight", flight, ticket.getFlight()); - assertEquals("Invalid seats available", 9, flight.getSeatsAvailable()); - assertEquals("Invalid passengers count", 1, ticket.getPassengers().size()); - - verify(flightDaoMock, ticketDaoMock, securityServiceMock); - } - - public void testBookFlightFrequentFlyer() throws Exception { - DateTime departureTime = new DateTime(); - FrequentFlyer frequentFlyer = new FrequentFlyer("John", "Doe", "john", "changeme"); - List passengers = new ArrayList(); - passengers.add(frequentFlyer); - Flight flight = new Flight(); - flight.setNumber(flightNumber); - flight.setSeatsAvailable(1); - flight.setMiles(10); - expect(securityServiceMock.getFrequentFlyer("john")).andReturn(frequentFlyer); - expect(flightDaoMock.getFlight(flightNumber, departureTime)).andReturn(flight); - expect(flightDaoMock.update(flight)).andReturn(flight); - ticketDaoMock.save(isA(Ticket.class)); - - replay(flightDaoMock, ticketDaoMock, securityServiceMock); - - Ticket ticket = airlineService.bookFlight(flightNumber, departureTime, passengers); - assertNotNull("Invalid ticket", ticket); - assertEquals("Invalid flight", flight, ticket.getFlight()); - assertEquals("Invalid amount of miles", 10, frequentFlyer.getMiles()); - - verify(flightDaoMock, ticketDaoMock, securityServiceMock); - } - - public void testBookFlightNoSeatAvailable() throws Exception { - DateTime departureTime = new DateTime(); - List passengers = Collections.singletonList(new Passenger()); - Flight flight = new Flight(); - flight.setNumber("AB1234"); - flight.setDepartureTime(new DateTime()); - expect(flightDaoMock.getFlight(flightNumber, departureTime)).andReturn(flight); - - replay(flightDaoMock, ticketDaoMock, securityServiceMock); - - try { - airlineService.bookFlight(flightNumber, departureTime, passengers); - fail("Should have thrown an NoSeatAvailableException"); - } - catch (NoSeatAvailableException ex) { - } - - verify(flightDaoMock, ticketDaoMock, securityServiceMock); - } - - public void testBookFlightNoSuchFlight() throws Exception { - String flightNumber = "AB1234"; - DateTime departureTime = new DateTime(); - List passengers = Collections.singletonList(new Passenger()); - expect(flightDaoMock.getFlight(flightNumber, departureTime)).andReturn(null); - - replay(flightDaoMock, ticketDaoMock, securityServiceMock); - try { - airlineService.bookFlight(flightNumber, departureTime, passengers); - fail("Should have thrown an NoSuchFlightException"); - } - catch (NoSuchFlightException ex) { - } - - verify(flightDaoMock, ticketDaoMock, securityServiceMock); - } - - public void testGetFlights() throws Exception { - LocalDate departureDate = new LocalDate(2006, 1, 31); - Flight flight = new Flight(); - List flights = new ArrayList(); - flights.add(flight); - String toCode = "to"; - String fromCode = "from"; - - expect(flightDaoMock.findFlights(fromCode, toCode, departureDate.toInterval(), ServiceClass.ECONOMY)) - .andReturn(flights); - - replay(flightDaoMock, ticketDaoMock, securityServiceMock); - - List result = airlineService.getFlights(fromCode, toCode, departureDate, ServiceClass.ECONOMY); - assertEquals("Invalid result", flights, result); - - verify(flightDaoMock, ticketDaoMock, securityServiceMock); - } - - public void testGetFlightsDefaultServiceClass() throws Exception { - LocalDate departureDate = new LocalDate(2006, 1, 31); - Flight flight = new Flight(); - List flights = new ArrayList(); - flights.add(flight); - String toCode = "to"; - String fromCode = "from"; - - expect(flightDaoMock.findFlights(fromCode, toCode, departureDate.toInterval(), ServiceClass.ECONOMY)) - .andReturn(flights); - - replay(flightDaoMock, ticketDaoMock, securityServiceMock); - - List result = airlineService.getFlights(fromCode, toCode, departureDate, null); - assertEquals("Invalid result", flights, result); - - verify(flightDaoMock, ticketDaoMock, securityServiceMock); - - } -} diff --git a/airline/server/src/test/java/org/springframework/ws/samples/airline/web/FlightsControllerTest.java b/airline/server/src/test/java/org/springframework/ws/samples/airline/web/FlightsControllerTest.java deleted file mode 100644 index b527afd..0000000 --- a/airline/server/src/test/java/org/springframework/ws/samples/airline/web/FlightsControllerTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2005-2010 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. - */ - -package org.springframework.ws.samples.airline.web; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; -import static org.easymock.EasyMock.*; -import org.joda.time.LocalDate; - -import org.springframework.ui.ModelMap; -import org.springframework.ws.samples.airline.domain.Flight; -import org.springframework.ws.samples.airline.domain.ServiceClass; -import org.springframework.ws.samples.airline.service.AirlineService; - -public class FlightsControllerTest extends TestCase { - - private FlightsController flightsController; - - private AirlineService airlineServiceMock; - - @Override - protected void setUp() throws Exception { - airlineServiceMock = createMock(AirlineService.class); - flightsController = new FlightsController(airlineServiceMock); - } - - public void testFlightList() throws Exception { - String from = "AMS"; - String to = "VCE"; - LocalDate departureDate = new LocalDate(); - ServiceClass serviceClass = ServiceClass.FIRST; - List flights = new ArrayList(); - flights.add(new Flight()); - expect(airlineServiceMock.getFlights(from, to, departureDate, serviceClass)).andReturn(flights); - - replay(airlineServiceMock); - - ModelMap model = new ModelMap(); - String view = flightsController - .flightList(from, to, departureDate.toString(), serviceClass.toString(), model); - assertNotNull("No view returned", view); - assertEquals("Invalid view name", "flights", view); - assertTrue("No flights in ModelAndView", model.containsAttribute("flights")); - verify(airlineServiceMock); - } -} \ No newline at end of file diff --git a/airline/server/src/test/java/org/springframework/ws/samples/airline/ws/AirlineEndpointTest.java b/airline/server/src/test/java/org/springframework/ws/samples/airline/ws/AirlineEndpointTest.java deleted file mode 100644 index 870c443..0000000 --- a/airline/server/src/test/java/org/springframework/ws/samples/airline/ws/AirlineEndpointTest.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright 2005-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. - */ - -package org.springframework.ws.samples.airline.ws; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import javax.xml.bind.JAXBElement; -import javax.xml.datatype.DatatypeConstants; -import javax.xml.datatype.DatatypeFactory; - -import org.springframework.ws.samples.airline.domain.Airport; -import org.springframework.ws.samples.airline.domain.FrequentFlyer; -import org.springframework.ws.samples.airline.domain.Passenger; -import org.springframework.ws.samples.airline.schema.BookFlightRequest; -import org.springframework.ws.samples.airline.schema.Flight; -import org.springframework.ws.samples.airline.schema.GetFlightsResponse; -import org.springframework.ws.samples.airline.schema.Name; -import org.springframework.ws.samples.airline.schema.ObjectFactory; -import org.springframework.ws.samples.airline.schema.ServiceClass; -import org.springframework.ws.samples.airline.schema.Ticket; -import org.springframework.ws.samples.airline.service.AirlineService; - -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.joda.time.LocalDate; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.w3c.dom.Element; - -import static org.easymock.EasyMock.*; -import static org.junit.Assert.assertNotNull; - -public class AirlineEndpointTest { - - private AirlineEndpoint endpoint; - - private AirlineService airlineServiceMock; - - private DatatypeFactory datatypeFactory; - - private ObjectFactory objectFactory; - - @Before - public void setUp() throws Exception { - airlineServiceMock = createMock(AirlineService.class); - endpoint = new AirlineEndpoint(airlineServiceMock); - datatypeFactory = DatatypeFactory.newInstance(); - objectFactory = new ObjectFactory(); - } - - @Test - public void testGetFlights() throws Exception { - org.springframework.ws.samples.airline.domain.Flight domainFlight = createDomainFlight(); - - expect(airlineServiceMock.getFlights("ABC", "DEF", new LocalDate(2007, 6, 13), - org.springframework.ws.samples.airline.domain.ServiceClass.FIRST)) - .andReturn(Collections.singletonList(domainFlight)); - - replay(airlineServiceMock); - - GetFlightsResponse response = endpoint.getFlights("ABC", "DEF", "2007-06-13", "first"); - Assert.assertEquals("Invalid amount of flights received", 1, response.getFlight().size()); - Flight schemaFlight = response.getFlight().get(0); - verifySchemaFlight(schemaFlight); - - verify(airlineServiceMock); - } - - private void verifySchemaFlight(Flight schemaFlight) { - Assert.assertEquals("Invalid number", "ABC1234", schemaFlight.getNumber()); - Assert.assertEquals("Invalid departure time", - datatypeFactory.newXMLGregorianCalendar(2007, 6, 13, 12, 0, 0, 0, 0), schemaFlight.getDepartureTime()); - Assert.assertEquals("Invalid from code", "ABC", schemaFlight.getFrom().getCode()); - Assert.assertEquals("Invalid from name", "ABC Airport", schemaFlight.getFrom().getName()); - Assert.assertEquals("Invalid from city", "ABC City", schemaFlight.getFrom().getCity()); - Assert.assertEquals("Invalid arrival time", - datatypeFactory.newXMLGregorianCalendar(2007, 6, 13, 14, 0, 0, 0, 0), schemaFlight.getArrivalTime()); - Assert.assertEquals("Invalid to code", "DEF", schemaFlight.getTo().getCode()); - Assert.assertEquals("Invalid to name", "DEF Airport", schemaFlight.getTo().getName()); - Assert.assertEquals("Invalid to city", "DEF City", schemaFlight.getTo().getCity()); - Assert.assertEquals("Invalid service class", ServiceClass.FIRST, schemaFlight.getServiceClass()); - } - - private org.springframework.ws.samples.airline.domain.Flight createDomainFlight() { - org.springframework.ws.samples.airline.domain.Flight domainFlight = - new org.springframework.ws.samples.airline.domain.Flight(); - domainFlight.setNumber("ABC1234"); - domainFlight.setDepartureTime(new DateTime(2007, 6, 13, 12, 0, 0, 0, DateTimeZone.UTC)); - domainFlight.setFrom(new Airport("ABC", "ABC Airport", "ABC City")); - domainFlight.setArrivalTime(new DateTime(2007, 6, 13, 14, 0, 0, 0, DateTimeZone.UTC)); - domainFlight.setTo(new Airport("DEF", "DEF Airport", "DEF City")); - domainFlight.setServiceClass(org.springframework.ws.samples.airline.domain.ServiceClass.FIRST); - return domainFlight; - } - - @Test - public void bookFlightPassenger() throws Exception { - BookFlightRequest request = objectFactory.createBookFlightRequest(); - request.setDepartureTime(datatypeFactory.newXMLGregorianCalendar(2007, 6, 13, 12, 0, 0, 0, 0)); - request.setFlightNumber("ABC1234"); - Name passengerName = new Name(); - passengerName.setFirst("John"); - passengerName.setLast("Doe"); - BookFlightRequest.Passengers passengers = new BookFlightRequest.Passengers(); - passengers.getPassengerOrUsername().add(passengerName); - request.setPassengers(passengers); - - Passenger domainPassenger = new Passenger("John", "Doe"); - - org.springframework.ws.samples.airline.domain.Ticket domainTicket = - new org.springframework.ws.samples.airline.domain.Ticket(42L); - domainTicket.setFlight(createDomainFlight()); - domainTicket.setIssueDate(new LocalDate(2007, 6, 13)); - domainTicket.setPassengers(Collections.singleton(domainPassenger)); - - expect(airlineServiceMock.bookFlight("ABC1234", new DateTime(2007, 6, 13, 12, 0, 0, 0, DateTimeZone.UTC), - Collections.singletonList(domainPassenger))).andReturn(domainTicket); - - replay(airlineServiceMock); - - JAXBElement response = endpoint.bookFlight(request); - Ticket schemaTicket = response.getValue(); - Assert.assertEquals("Invalid id", 42L, schemaTicket.getId()); - Assert.assertEquals("Invalid issue date", - datatypeFactory.newXMLGregorianCalendarDate(2007, 6, 13, DatatypeConstants.FIELD_UNDEFINED), - schemaTicket.getIssueDate()); - Assert.assertEquals("Invalid amount of passengers", 1, schemaTicket.getPassengers().getPassenger().size()); - Name schemaPassenger = schemaTicket.getPassengers().getPassenger().get(0); - Assert.assertEquals("Invalid passenger first name", "John", schemaPassenger.getFirst()); - Assert.assertEquals("Invalid passenger first name", "Doe", schemaPassenger.getLast()); - verifySchemaFlight(schemaTicket.getFlight()); - - verify(airlineServiceMock); - } - - @Test - public void testBookFlightFrequentFlyer() throws Exception { - BookFlightRequest request = objectFactory.createBookFlightRequest(); - request.setDepartureTime(datatypeFactory.newXMLGregorianCalendar(2007, 6, 13, 12, 0, 0, 0, 0)); - request.setFlightNumber("ABC1234"); - BookFlightRequest.Passengers passengers = new BookFlightRequest.Passengers(); - passengers.getPassengerOrUsername().add("john"); - request.setPassengers(passengers); - - FrequentFlyer domainFrequentFlyer = new FrequentFlyer("John", "Doe", "john", "changeme"); - Set domainPassengers = new HashSet(); - domainPassengers.add(domainFrequentFlyer); - - org.springframework.ws.samples.airline.domain.Ticket domainTicket = - new org.springframework.ws.samples.airline.domain.Ticket(42L); - domainTicket.setFlight(createDomainFlight()); - domainTicket.setIssueDate(new LocalDate(2007, 6, 13)); - domainTicket.setPassengers(domainPassengers); - - List domainPassengerList = new ArrayList(domainPassengers); - expect(airlineServiceMock - .bookFlight("ABC1234", new DateTime(2007, 6, 13, 12, 0, 0, 0, DateTimeZone.UTC), domainPassengerList)) - .andReturn(domainTicket); - - replay(airlineServiceMock); - - JAXBElement response = endpoint.bookFlight(request); - Ticket schemaTicket = response.getValue(); - Assert.assertEquals("Invalid id", 42L, schemaTicket.getId()); - Assert.assertEquals("Invalid issue date", - datatypeFactory.newXMLGregorianCalendarDate(2007, 6, 13, DatatypeConstants.FIELD_UNDEFINED), - schemaTicket.getIssueDate()); - Assert.assertEquals("Invalid amount of passengers", 1, schemaTicket.getPassengers().getPassenger().size()); - Name schemaPassenger = schemaTicket.getPassengers().getPassenger().get(0); - Assert.assertEquals("Invalid passenger first name", "John", schemaPassenger.getFirst()); - Assert.assertEquals("Invalid passenger first name", "Doe", schemaPassenger.getLast()); - verifySchemaFlight(schemaTicket.getFlight()); - - verify(airlineServiceMock); - } - - @Test - public void testGetFrequentFlyerMileage() throws Exception { - expect(airlineServiceMock.getFrequentFlyerMileage()).andReturn(42); - - replay(airlineServiceMock); - - Element response = endpoint.getFrequentFlyerMileage(); - assertNotNull("Invalid response", response); - - verify(airlineServiceMock); - } - -} \ No newline at end of file diff --git a/airline/settings.gradle b/airline/settings.gradle deleted file mode 100644 index aaeb3fd..0000000 --- a/airline/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ - -include "server", "client:axis1", "client:jax-ws", "client:jms", "client:saaj", "client:spring-ws" diff --git a/echo/build.gradle b/echo/build.gradle deleted file mode 100644 index c90a772..0000000 --- a/echo/build.gradle +++ /dev/null @@ -1,17 +0,0 @@ -ext.springWsVersion = '2.2.0.RELEASE' - -subprojects { - apply plugin: 'java' - apply plugin: 'eclipse' - apply plugin: 'idea' - - repositories { - maven { url 'https://repo.spring.io/libs-release' } - } - - dependencies { - testCompile("junit:junit:4.10") - testCompile("org.easymock:easymock:3.1") - } - -} diff --git a/echo/client/saaj/build.gradle b/echo/client/saaj/build.gradle deleted file mode 100644 index 5987bbd..0000000 --- a/echo/client/saaj/build.gradle +++ /dev/null @@ -1,4 +0,0 @@ -task runClient(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.echo.client.saaj.EchoClient" - classpath = sourceSets.main.runtimeClasspath -} \ No newline at end of file diff --git a/echo/client/saaj/pom.xml b/echo/client/saaj/pom.xml new file mode 100644 index 0000000..7a4fcea --- /dev/null +++ b/echo/client/saaj/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + + org.springframework.ws + spring-ws-samples + 1.0.0.BUILD-SNAPSHOT + ../../../ + + + echo-client-saaj + 0.0.1-SNAPSHOT + Spring Web Services Samples - Echo - Client - SAAJ + Demo project for Spring Web Services + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web-services + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/echo/client/saaj/src/main/java/org/springframework/ws/samples/echo/client/saaj/EchoClient.java b/echo/client/saaj/src/main/java/org/springframework/ws/samples/echo/client/saaj/EchoClient.java index a8ee4f2..2d77eb0 100644 --- a/echo/client/saaj/src/main/java/org/springframework/ws/samples/echo/client/saaj/EchoClient.java +++ b/echo/client/saaj/src/main/java/org/springframework/ws/samples/echo/client/saaj/EchoClient.java @@ -16,7 +16,6 @@ package org.springframework.ws.samples.echo.client.saaj; -import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; @@ -29,8 +28,9 @@ import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPFault; import javax.xml.soap.SOAPMessage; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * A client for the Echo Web Service that uses SAAJ. @@ -40,64 +40,57 @@ import javax.xml.transform.TransformerFactory; */ public class EchoClient { - public static final String NAMESPACE_URI = "http://www.springframework.org/spring-ws/samples/echo"; + public static final String NAMESPACE_URI = "http://www.springframework.org/spring-ws/samples/echo"; - public static final String PREFIX = "tns"; + public static final String PREFIX = "tns"; - private SOAPConnectionFactory connectionFactory; + private static final Logger logger = LoggerFactory.getLogger(EchoClient.class); - private MessageFactory messageFactory; + private SOAPConnectionFactory connectionFactory; - private URL url; + private MessageFactory messageFactory; - public EchoClient(String url) throws SOAPException, MalformedURLException { - connectionFactory = SOAPConnectionFactory.newInstance(); - messageFactory = MessageFactory.newInstance(); - this.url = new URL(url); - } + private URL url; - private SOAPMessage createEchoRequest() throws SOAPException { - SOAPMessage message = messageFactory.createMessage(); - SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); - Name echoRequestName = envelope.createName("echoRequest", PREFIX, NAMESPACE_URI); - SOAPBodyElement echoRequestElement = message.getSOAPBody() - .addBodyElement(echoRequestName); - echoRequestElement.setValue("Hello"); - return message; - } + public EchoClient(String url) throws SOAPException, MalformedURLException { - public void callWebService() throws SOAPException, IOException { - SOAPMessage request = createEchoRequest(); - SOAPConnection connection = connectionFactory.createConnection(); - SOAPMessage response = connection.call(request, url); - if (!response.getSOAPBody().hasFault()) { - writeEchoResponse(response); - } - else { - SOAPFault fault = response.getSOAPBody().getFault(); - System.err.println("Received SOAP Fault"); - System.err.println("SOAP Fault Code :" + fault.getFaultCode()); - System.err.println("SOAP Fault String :" + fault.getFaultString()); - } - } + connectionFactory = SOAPConnectionFactory.newInstance(); + messageFactory = MessageFactory.newInstance(); + this.url = new URL(url); + } - private void writeEchoResponse(SOAPMessage message) throws SOAPException { - SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); - Name echoResponseName = envelope.createName("echoResponse", PREFIX, NAMESPACE_URI); - SOAPBodyElement echoResponseElement = (SOAPBodyElement) message - .getSOAPBody().getChildElements(echoResponseName).next(); - String echoValue = echoResponseElement.getTextContent(); - System.out.println(); - System.out.println("Echo Response [" + echoValue + "]"); - System.out.println(); - } + private SOAPMessage createEchoRequest() throws SOAPException { - public static void main(String[] args) throws Exception { - String url = "http://localhost:8080/echo-server/services"; - if (args.length > 0) { - url = args[0]; - } - EchoClient echoClient = new EchoClient(url); - echoClient.callWebService(); - } -} \ No newline at end of file + SOAPMessage message = messageFactory.createMessage(); + SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); + Name echoRequestName = envelope.createName("echoRequest", PREFIX, NAMESPACE_URI); + SOAPBodyElement echoRequestElement = message.getSOAPBody().addBodyElement(echoRequestName); + echoRequestElement.setValue("Hello"); + return message; + } + + public void callWebService() throws SOAPException { + + SOAPMessage request = createEchoRequest(); + SOAPConnection connection = connectionFactory.createConnection(); + SOAPMessage response = connection.call(request, url); + if (!response.getSOAPBody().hasFault()) { + writeEchoResponse(response); + } else { + SOAPFault fault = response.getSOAPBody().getFault(); + logger.error("Received SOAP Fault"); + logger.error("SOAP Fault Code :" + fault.getFaultCode()); + logger.error("SOAP Fault String :" + fault.getFaultString()); + } + } + + private void writeEchoResponse(SOAPMessage message) throws SOAPException { + + SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); + Name echoResponseName = envelope.createName("echoResponse", PREFIX, NAMESPACE_URI); + SOAPBodyElement echoResponseElement = (SOAPBodyElement) message.getSOAPBody().getChildElements(echoResponseName) + .next(); + String echoValue = echoResponseElement.getTextContent(); + logger.info("Echo Response [" + echoValue + "]"); + } +} diff --git a/echo/client/saaj/src/main/java/org/springframework/ws/samples/echo/client/saaj/SaajEchoClient.java b/echo/client/saaj/src/main/java/org/springframework/ws/samples/echo/client/saaj/SaajEchoClient.java new file mode 100644 index 0000000..96cdb99 --- /dev/null +++ b/echo/client/saaj/src/main/java/org/springframework/ws/samples/echo/client/saaj/SaajEchoClient.java @@ -0,0 +1,24 @@ +package org.springframework.ws.samples.echo.client.saaj; + +import java.net.MalformedURLException; + +import javax.xml.soap.SOAPException; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SaajEchoClient { + + public static void main(String[] args) throws MalformedURLException, SOAPException { + SpringApplication.run(SaajEchoClient.class); + + String url = "http://localhost:8080/echo-server/services"; + if (args.length > 0) { + url = args[0]; + } + + EchoClient echoClient = new EchoClient(url); + echoClient.callWebService(); + } +} diff --git a/echo/client/spring-ws/build.gradle b/echo/client/spring-ws/build.gradle deleted file mode 100644 index 688d104..0000000 --- a/echo/client/spring-ws/build.gradle +++ /dev/null @@ -1,9 +0,0 @@ -dependencies { - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - runtime("log4j:log4j:1.2.16") -} - -task runClient(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.echo.client.sws.EchoClient" - classpath = sourceSets.main.runtimeClasspath -} diff --git a/echo/client/spring-ws/pom.xml b/echo/client/spring-ws/pom.xml new file mode 100644 index 0000000..4d56172 --- /dev/null +++ b/echo/client/spring-ws/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + + org.springframework.ws + spring-ws-samples + 1.0.0.BUILD-SNAPSHOT + ../../../ + + + org.springframework.ws + echo-client-spring-ws + 0.0.1-SNAPSHOT + Spring Web Services Samples - Echo - Client - Spring WS + Demo project for Spring Web Services + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web-services + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/echo/client/spring-ws/src/main/java/org/springframework/ws/samples/echo/client/sws/EchoClient.java b/echo/client/spring-ws/src/main/java/org/springframework/ws/samples/echo/client/sws/EchoClient.java index 764e21f..40e5f94 100644 --- a/echo/client/spring-ws/src/main/java/org/springframework/ws/samples/echo/client/sws/EchoClient.java +++ b/echo/client/spring-ws/src/main/java/org/springframework/ws/samples/echo/client/sws/EchoClient.java @@ -17,40 +17,34 @@ package org.springframework.ws.samples.echo.client.sws; import java.io.IOException; + import javax.xml.transform.Source; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.core.io.ClassPathResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; +import org.springframework.stereotype.Service; import org.springframework.ws.client.core.support.WebServiceGatewaySupport; import org.springframework.xml.transform.ResourceSource; import org.springframework.xml.transform.StringResult; +@Service public class EchoClient extends WebServiceGatewaySupport { - private Resource request; + private static final Logger logger = LoggerFactory.getLogger(EchoClient.class); - public void setRequest(Resource request) { - this.request = request; - } + private Resource request; - public void echo() throws IOException { - Source requestSource = new ResourceSource(request); - StringResult result = new StringResult(); - getWebServiceTemplate().sendSourceAndReceiveToResult(requestSource, result); - System.out.println(); - System.out.println(result); - System.out.println(); - } + public void setRequest(Resource request) { + this.request = request; + } - public static void main(String[] args) throws IOException { - EchoClient echoClient = new EchoClient(); - echoClient.setDefaultUri("http://localhost:8080/echo-server/services"); - echoClient.setRequest(new ClassPathResource( - "org/springframework/ws/samples/echo/client/sws/echoRequest.xml")); + public void echo() throws IOException { - echoClient.echo(); - } + Source requestSource = new ResourceSource(request); + StringResult result = new StringResult(); + getWebServiceTemplate().sendSourceAndReceiveToResult(requestSource, result); + logger.info(result.toString()); + } } diff --git a/echo/client/spring-ws/src/main/java/org/springframework/ws/samples/echo/client/sws/SpringWsEchoClient.java b/echo/client/spring-ws/src/main/java/org/springframework/ws/samples/echo/client/sws/SpringWsEchoClient.java new file mode 100644 index 0000000..6507859 --- /dev/null +++ b/echo/client/spring-ws/src/main/java/org/springframework/ws/samples/echo/client/sws/SpringWsEchoClient.java @@ -0,0 +1,41 @@ +/* + * Copyright 2007 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. + */ + +package org.springframework.ws.samples.echo.client.sws; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.core.io.ClassPathResource; + +@SpringBootApplication +public class SpringWsEchoClient { + + public static void main(String[] args) { + SpringApplication.run(SpringWsEchoClient.class, args); + } + + @Bean + CommandLineRunner invoke(EchoClient echoClient) { + + return args -> { + echoClient.setDefaultUri("http://localhost:8080/echo-server/services"); + echoClient.setRequest(new ClassPathResource("echoRequest.xml")); + echoClient.echo(); + }; + } +} diff --git a/echo/client/spring-ws/src/main/resources/application.yml b/echo/client/spring-ws/src/main/resources/application.yml new file mode 100644 index 0000000..cf866a4 --- /dev/null +++ b/echo/client/spring-ws/src/main/resources/application.yml @@ -0,0 +1,6 @@ +logging: + level: + org.springframework: + ws: TRACE + web: TRACE + xml: DEBUG \ No newline at end of file diff --git a/echo/client/spring-ws/src/main/resources/org/springframework/ws/samples/echo/client/sws/echoRequest.xml b/echo/client/spring-ws/src/main/resources/echoRequest.xml similarity index 100% rename from echo/client/spring-ws/src/main/resources/org/springframework/ws/samples/echo/client/sws/echoRequest.xml rename to echo/client/spring-ws/src/main/resources/echoRequest.xml diff --git a/echo/client/spring-ws/src/main/resources/log4j.properties b/echo/client/spring-ws/src/main/resources/log4j.properties deleted file mode 100644 index 0f73a75..0000000 --- a/echo/client/spring-ws/src/main/resources/log4j.properties +++ /dev/null @@ -1,7 +0,0 @@ -log4j.rootLogger=WARN, stdout -log4j.logger.org.springframework.ws=DEBUG -log4j.logger.org.springframework.xml=DEBUG - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n \ No newline at end of file diff --git a/echo/server/build.gradle b/echo/server/build.gradle deleted file mode 100644 index 43f6e53..0000000 --- a/echo/server/build.gradle +++ /dev/null @@ -1,38 +0,0 @@ -buildscript { - repositories { - maven { url 'https://repo.springsource.org/plugins-release' } - } - - dependencies { - classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.9' - } -} - -ext.springVersion = '4.0.2.RELEASE' -ext.tomcatVersion = '7.0.42' - -apply plugin: 'war' -apply plugin: 'maven' -apply plugin: 'tomcat' - -tomcatRun { - contextPath = 'echo-server' -} -repositories { - mavenLocal() -} - -dependencies { - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - compile("org.springframework:spring-context:$springVersion") - runtime("log4j:log4j:1.2.16") - - providedCompile("javax.servlet:javax.servlet-api:3.0.1") - runtime("wsdl4j:wsdl4j:1.6.1") - - tomcat("org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion", - "org.apache.tomcat.embed:tomcat-embed-logging-juli:$tomcatVersion") - tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:$tomcatVersion") { - exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj' - } -} diff --git a/echo/server/pom.xml b/echo/server/pom.xml new file mode 100644 index 0000000..e35301b --- /dev/null +++ b/echo/server/pom.xml @@ -0,0 +1,121 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.3.1.RELEASE + + + + org.springframework.ws + echo-server + 0.0.1-SNAPSHOT + Spring Web Services Samples - Echo - Server + Demo project for Spring Web Services + + + 1.8 + 2.10.6 + 1.2.16 + ${project.basedir}/target/generated-sources/axis + ${project.basedir}/target/classes + ${project.basedir}/../airline.wsdl + 2.0.2 + + + + + + org.springframework.boot + spring-boot-starter-web-services + + + + wsdl4j + wsdl4j + + + + org.apache.ws.xmlschema + xmlschema-core + ${xmlschema.version} + runtime + + + + org.springframework + spring-test + test + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.codehaus.mojo + jaxb2-maven-plugin + 2.5.0 + + + xjc + + xjc + + + + + ${project.basedir}/src/main/resources/echo.xsd + org.springframework.ws.samples.airline.schema + 2.1 + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.1 + + + add-source + process-sources + + add-source + + + + target/generated-sources/xjc + + + + + + + + + + + + diff --git a/echo/server/src/main/java/org/springframework/ws/samples/echo/EchoApplication.java b/echo/server/src/main/java/org/springframework/ws/samples/echo/EchoApplication.java new file mode 100644 index 0000000..775d859 --- /dev/null +++ b/echo/server/src/main/java/org/springframework/ws/samples/echo/EchoApplication.java @@ -0,0 +1,12 @@ +package org.springframework.ws.samples.echo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class EchoApplication { + + public static void main(String[] args) { + SpringApplication.run(EchoApplication.class, args); + } +} diff --git a/echo/server/src/main/java/org/springframework/ws/samples/echo/config/EchoConfig.java b/echo/server/src/main/java/org/springframework/ws/samples/echo/config/EchoConfig.java index 068cd2e..5f77ffa 100644 --- a/echo/server/src/main/java/org/springframework/ws/samples/echo/config/EchoConfig.java +++ b/echo/server/src/main/java/org/springframework/ws/samples/echo/config/EchoConfig.java @@ -19,10 +19,8 @@ package org.springframework.ws.samples.echo.config; import java.util.List; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; -import org.springframework.ws.config.annotation.EnableWs; import org.springframework.ws.config.annotation.WsConfigurerAdapter; import org.springframework.ws.server.EndpointInterceptor; import org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor; @@ -35,9 +33,7 @@ import org.springframework.xml.xsd.SimpleXsdSchema; * * @author Arjen Poutsma */ -@EnableWs @Configuration -@ComponentScan("org.springframework.ws.samples.echo") public class EchoConfig extends WsConfigurerAdapter { @Bean @@ -47,7 +43,9 @@ public class EchoConfig extends WsConfigurerAdapter { @Override public void addInterceptors(List interceptors) { + PayloadValidatingInterceptor validatingInterceptor = new PayloadValidatingInterceptor(); + validatingInterceptor.setXsdSchema(echoXsd()); validatingInterceptor.setValidateRequest(true); validatingInterceptor.setValidateResponse(true); @@ -56,12 +54,13 @@ public class EchoConfig extends WsConfigurerAdapter { interceptors.add(new PayloadLoggingInterceptor()); } - @Bean - public DefaultWsdl11Definition echo() { + @Bean("echo-server") + public DefaultWsdl11Definition echo(SimpleXsdSchema echoXsd) { + DefaultWsdl11Definition definition = new DefaultWsdl11Definition(); definition.setPortTypeName("Echo"); - definition.setLocationUri("http://localhost:8080/echo/services"); - definition.setSchema(echoXsd()); + definition.setLocationUri("http://localhost:8080/echo-server/services"); + definition.setSchema(echoXsd); return definition; } diff --git a/echo/server/src/main/java/org/springframework/ws/samples/echo/config/EchoServletInitializer.java b/echo/server/src/main/java/org/springframework/ws/samples/echo/config/EchoServletInitializer.java deleted file mode 100644 index 30469bc..0000000 --- a/echo/server/src/main/java/org/springframework/ws/samples/echo/config/EchoServletInitializer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2005-2014 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. - */ - -package org.springframework.ws.samples.echo.config; - -import org.springframework.web.WebApplicationInitializer; -import org.springframework.ws.transport.http.support.AbstractAnnotationConfigMessageDispatcherServletInitializer; - -/** - * {@link WebApplicationInitializer} for the echo sample. - * @author Arjen Poutsma - */ -public class EchoServletInitializer - extends AbstractAnnotationConfigMessageDispatcherServletInitializer { - - @Override - protected Class[] getRootConfigClasses() { - return null; - } - - @Override - protected Class[] getServletConfigClasses() { - return new Class[]{EchoConfig.class}; - } - - @Override - public boolean isTransformWsdlLocations() { - return true; - } -} diff --git a/echo/server/src/main/java/org/springframework/ws/samples/echo/service/EchoService.java b/echo/server/src/main/java/org/springframework/ws/samples/echo/service/EchoService.java index 602adee..a4de3bd 100644 --- a/echo/server/src/main/java/org/springframework/ws/samples/echo/service/EchoService.java +++ b/echo/server/src/main/java/org/springframework/ws/samples/echo/service/EchoService.java @@ -24,10 +24,10 @@ package org.springframework.ws.samples.echo.service; */ public interface EchoService { - /** - * Returns the given string. - * - * @return s - */ - String echo(String s); + /** + * Returns the given string. + * + * @return message + */ + String echo(String message); } diff --git a/echo/server/src/main/java/org/springframework/ws/samples/echo/service/impl/EchoServiceImpl.java b/echo/server/src/main/java/org/springframework/ws/samples/echo/service/impl/EchoServiceImpl.java index 7be65d2..266681f 100755 --- a/echo/server/src/main/java/org/springframework/ws/samples/echo/service/impl/EchoServiceImpl.java +++ b/echo/server/src/main/java/org/springframework/ws/samples/echo/service/impl/EchoServiceImpl.java @@ -28,7 +28,7 @@ import org.springframework.ws.samples.echo.service.EchoService; @Service public class EchoServiceImpl implements EchoService { - public String echo(String s) { - return s; - } + public String echo(String message) { + return message; + } } diff --git a/echo/server/src/main/java/org/springframework/ws/samples/echo/ws/EchoEndpoint.java b/echo/server/src/main/java/org/springframework/ws/samples/echo/ws/EchoEndpoint.java index f1e7327..b0b6136 100755 --- a/echo/server/src/main/java/org/springframework/ws/samples/echo/ws/EchoEndpoint.java +++ b/echo/server/src/main/java/org/springframework/ws/samples/echo/ws/EchoEndpoint.java @@ -20,14 +20,12 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import org.springframework.ws.samples.echo.service.EchoService; 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 org.springframework.ws.server.endpoint.annotation.ResponsePayload; - import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -43,62 +41,64 @@ import org.w3c.dom.Text; @Endpoint public class EchoEndpoint { - /** - * Namespace of both request and response. - */ - public static final String NAMESPACE_URI = "http://www.springframework.org/spring-ws/samples/echo"; + /** + * Namespace of both request and response. + */ + public static final String NAMESPACE_URI = "http://www.springframework.org/spring-ws/samples/echo"; - /** - * The local name of the expected request. - */ - public static final String ECHO_REQUEST_LOCAL_NAME = "echoRequest"; + /** + * The local name of the expected request. + */ + public static final String ECHO_REQUEST_LOCAL_NAME = "echoRequest"; - /** - * The local name of the created response. - */ - public static final String ECHO_RESPONSE_LOCAL_NAME = "echoResponse"; + /** + * The local name of the created response. + */ + public static final String ECHO_RESPONSE_LOCAL_NAME = "echoResponse"; - private final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + private final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - private final EchoService echoService; + private final EchoService echoService; - @Autowired - public EchoEndpoint(EchoService echoService) { - this.echoService = echoService; - } + public EchoEndpoint(EchoService echoService) { + this.echoService = echoService; + } + /** + * Reads the given requestElement, and sends a the response back. + * + * @param requestElement the contents of the SOAP message as DOM elements + * @return the response element + */ + @PayloadRoot(localPart = ECHO_REQUEST_LOCAL_NAME, namespace = NAMESPACE_URI) + @ResponsePayload + public Element handleEchoRequest(@RequestPayload Element requestElement) throws ParserConfigurationException { - /** - * Reads the given requestElement, and sends a the response back. - * - * @param requestElement the contents of the SOAP message as DOM elements - * @return the response element - */ - @PayloadRoot(localPart = ECHO_REQUEST_LOCAL_NAME, namespace = NAMESPACE_URI) - @ResponsePayload - public Element handleEchoRequest(@RequestPayload Element requestElement) throws ParserConfigurationException { - Assert.isTrue(NAMESPACE_URI.equals(requestElement.getNamespaceURI()), "Invalid namespace"); - Assert.isTrue(ECHO_REQUEST_LOCAL_NAME.equals(requestElement.getLocalName()), "Invalid local name"); + Assert.isTrue(NAMESPACE_URI.equals(requestElement.getNamespaceURI()), "Invalid namespace"); + Assert.isTrue(ECHO_REQUEST_LOCAL_NAME.equals(requestElement.getLocalName()), "Invalid local name"); - NodeList children = requestElement.getChildNodes(); - Text requestText = null; - for (int i = 0; i < children.getLength(); i++) { - if (children.item(i).getNodeType() == Node.TEXT_NODE) { - requestText = (Text) children.item(i); - break; - } - } - if (requestText == null) { - throw new IllegalArgumentException("Could not find request text node"); - } + NodeList children = requestElement.getChildNodes(); + Text requestText = null; - String echo = echoService.echo(requestText.getNodeValue()); + for (int i = 0; i < children.getLength(); i++) { + if (children.item(i).getNodeType() == Node.TEXT_NODE) { + requestText = (Text) children.item(i); + break; + } + } - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document document = documentBuilder.newDocument(); - Element responseElement = document.createElementNS(NAMESPACE_URI, ECHO_RESPONSE_LOCAL_NAME); - Text responseText = document.createTextNode(echo); - responseElement.appendChild(responseText); - return responseElement; - } + if (requestText == null) { + throw new IllegalArgumentException("Could not find request text node"); + } + + String echo = echoService.echo(requestText.getNodeValue()); + + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.newDocument(); + Element responseElement = document.createElementNS(NAMESPACE_URI, ECHO_RESPONSE_LOCAL_NAME); + Text responseText = document.createTextNode(echo); + responseElement.appendChild(responseText); + + return responseElement; + } } diff --git a/echo/server/src/main/resources/application.yml b/echo/server/src/main/resources/application.yml new file mode 100644 index 0000000..2f47459 --- /dev/null +++ b/echo/server/src/main/resources/application.yml @@ -0,0 +1,9 @@ +logging: + level: + org.springframework: + ws: TRACE + web: TRACE + xml: DEBUG +spring: + webservices: + path: /echo-server \ No newline at end of file diff --git a/echo/server/src/main/resources/log4j.properties b/echo/server/src/main/resources/log4j.properties deleted file mode 100644 index 0f73a75..0000000 --- a/echo/server/src/main/resources/log4j.properties +++ /dev/null @@ -1,7 +0,0 @@ -log4j.rootLogger=WARN, stdout -log4j.logger.org.springframework.ws=DEBUG -log4j.logger.org.springframework.xml=DEBUG - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n \ No newline at end of file diff --git a/echo/server/src/test/java/org/springframework/ws/samples/echo/ws/EchoEndpointTest.java b/echo/server/src/test/java/org/springframework/ws/samples/echo/ws/EchoEndpointTest.java index 6ce3af3..d5dab28 100644 --- a/echo/server/src/test/java/org/springframework/ws/samples/echo/ws/EchoEndpointTest.java +++ b/echo/server/src/test/java/org/springframework/ws/samples/echo/ws/EchoEndpointTest.java @@ -16,60 +16,56 @@ package org.springframework.ws.samples.echo.ws; +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; + import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.ws.samples.echo.service.EchoService; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; -import static org.easymock.EasyMock.*; - public class EchoEndpointTest { - private EchoEndpoint endpoint; + private EchoEndpoint endpoint; - private Document requestDocument; + private Document requestDocument; - private Document responseDocument; + private Document responseDocument; - private EchoService mock; + private EchoService echoServiceMock; - @Before - public void setUp() throws Exception { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - requestDocument = documentBuilder.newDocument(); - responseDocument = documentBuilder.newDocument(); - mock = createMock(EchoService.class); - endpoint = new EchoEndpoint(mock); - } + @BeforeEach + public void setUp() throws Exception { - @Test - public void testInvokeInternal() throws Exception { - Element echoRequest = - requestDocument.createElementNS(EchoEndpoint.NAMESPACE_URI, EchoEndpoint.ECHO_REQUEST_LOCAL_NAME); - String content = "ABC"; - Text requestText = requestDocument.createTextNode(content); - echoRequest.appendChild(requestText); - String result = "DEF"; - expect(mock.echo(content)).andReturn(result); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + requestDocument = documentBuilder.newDocument(); + responseDocument = documentBuilder.newDocument(); + echoServiceMock = mock(EchoService.class); + endpoint = new EchoEndpoint(echoServiceMock); + } - replay(mock); + @Test + public void testInvokeInternal() throws Exception { - Element echoResponse = endpoint.handleEchoRequest(echoRequest); - Assert.assertEquals("Invalid namespace", EchoEndpoint.NAMESPACE_URI, echoResponse.getNamespaceURI()); - Assert.assertEquals("Invalid namespace", EchoEndpoint.ECHO_RESPONSE_LOCAL_NAME, echoResponse.getLocalName()); - Text responseText = (Text) echoResponse.getChildNodes().item(0); - Assert.assertEquals("Invalid content", result, responseText.getNodeValue()); + Element echoRequest = requestDocument.createElementNS(EchoEndpoint.NAMESPACE_URI, + EchoEndpoint.ECHO_REQUEST_LOCAL_NAME); + Text requestText = requestDocument.createTextNode("ABC"); + echoRequest.appendChild(requestText); + when(echoServiceMock.echo("ABC")).thenReturn("DEF"); - verify(mock); - } + Element echoResponse = endpoint.handleEchoRequest(echoRequest); -} \ No newline at end of file + assertThat(echoResponse.getNamespaceURI()).isEqualTo(EchoEndpoint.NAMESPACE_URI); + assertThat(echoResponse.getLocalName()).isEqualTo(EchoEndpoint.ECHO_RESPONSE_LOCAL_NAME); + assertThat(echoResponse.getChildNodes().item(0).getNodeValue()).isEqualTo("DEF"); + + verify(echoServiceMock); + } +} diff --git a/echo/settings.gradle b/echo/settings.gradle deleted file mode 100644 index 72c6a98..0000000 --- a/echo/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ - -include "server", "client:saaj", "client:spring-ws" diff --git a/mtom/build.gradle b/mtom/build.gradle deleted file mode 100644 index 37c9698..0000000 --- a/mtom/build.gradle +++ /dev/null @@ -1,23 +0,0 @@ -ext.springWsVersion = '2.2.0.RELEASE' -ext.springVersion = '4.0.5.RELEASE' - - -subprojects { - apply plugin: 'java' - apply plugin: 'eclipse' - apply plugin: 'idea' - - repositories { - maven { url 'https://repo.spring.io/libs-release' } - } - - dependencies { - testCompile("junit:junit:4.10") - testCompile("org.easymock:easymock:3.1") - } - -} - -task wrapper(type: Wrapper) { - gradleVersion = '1.8' -} diff --git a/mtom/client/jax-ws/build.gradle b/mtom/client/jax-ws/build.gradle deleted file mode 100644 index 5d7bf51..0000000 --- a/mtom/client/jax-ws/build.gradle +++ /dev/null @@ -1,39 +0,0 @@ -configurations { - wsimport -} - -ext.springWsVersion = '2.1.4.RELEASE' - -task wsImport { - ext.outputDir = "${buildDir}/classes/wsimport" - ext.wsdl = "${projectDir}/mtom.wsdl" - - inputs.files wsdl - outputs.dir outputDir - - doLast() { - project.ant { - taskdef name: "wsimport", classname: "com.sun.tools.ws.ant.WsImport", - classpath: configurations.wsimport.asPath - mkdir(dir: outputDir) - - wsimport(destdir: outputDir, wsdl: wsdl, - package: "org.springframework.ws.samples.mtom.client.jaxws") { - produces(dir: outputDir, includes: "**/*.class") - } - } - } -} - -dependencies { - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - compile(files(wsImport.outputDir).builtBy(wsImport)) - runtime("log4j:log4j:1.2.16") - wsimport "com.sun.xml.ws:jaxws-tools:2.1.7" -} - -task runClient(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.mtom.client.jaxws.Main" - classpath = sourceSets.main.runtimeClasspath - systemProperty("java.awt.headless", "true") -} \ No newline at end of file diff --git a/mtom/client/jax-ws/mtom.wsdl b/mtom/client/jax-ws/mtom.wsdl deleted file mode 100644 index 86a2b42..0000000 --- a/mtom/client/jax-ws/mtom.wsdl +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/mtom/client/jax-ws/src/main/java/org/springframework/ws/samples/mtom/client/jaxws/Main.java b/mtom/client/jax-ws/src/main/java/org/springframework/ws/samples/mtom/client/jaxws/Main.java deleted file mode 100644 index 85ebca1..0000000 --- a/mtom/client/jax-ws/src/main/java/org/springframework/ws/samples/mtom/client/jaxws/Main.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2006 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. - */ - -package org.springframework.ws.samples.mtom.client.jaxws; - -import java.io.File; -import java.io.IOException; -import java.awt.image.RenderedImage; -import java.awt.Toolkit; -import javax.activation.DataHandler; -import javax.xml.ws.BindingProvider; -import javax.xml.ws.soap.SOAPBinding; -import javax.xml.ws.soap.SOAPFaultException; - -import org.springframework.util.StopWatch; - -/** - * Simple client that calls the GetFlights and BookFlight operations using JAX-WS. - * - * @author Arjen Poutsma - */ -public class Main { - - public static void main(String[] args) throws IOException { - try { - - String fileName = "../spring-ws-logo.png"; - if (args.length > 0) { - fileName = args[0]; - } - - ImageRepositoryService service = new ImageRepositoryService(); - ImageRepository imageRepository = service.getImageRepositorySoap11(); - SOAPBinding binding = (SOAPBinding) ((BindingProvider) imageRepository).getBinding(); - binding.setMTOMEnabled(true); - - Image request = new Image(); - File file = new File(fileName); - if (!file.exists()) { - System.err.println("File [" + fileName + "] does not exist"); - System.exit(-1); - } - request.setName(file.getName()); - request.setImage(Toolkit.getDefaultToolkit().getImage(file.getAbsolutePath())); - StopWatch stopWatch = new StopWatch(); - stopWatch.start("store"); - imageRepository.storeImage(request); - stopWatch.stop(); - - stopWatch.start("load"); - Image response = imageRepository.loadImage(file.getName()); - stopWatch.stop(); - System.out.println(stopWatch.prettyPrint()); - } - catch (SOAPFaultException ex) { - System.err.format("SOAP Fault Code %1s%n", ex.getFault().getFaultCodeAsQName()); - System.err.format("SOAP Fault String: %1s%n", ex.getFault().getFaultString()); - } - - } - - -} diff --git a/mtom/client/spring-ws/build.gradle b/mtom/client/spring-ws/build.gradle deleted file mode 100644 index 6947de7..0000000 --- a/mtom/client/spring-ws/build.gradle +++ /dev/null @@ -1,58 +0,0 @@ -configurations { - jaxb -} - -task genJaxb { - ext.sourcesDir = "${buildDir}/generated-sources/jaxb" - ext.classesDir = "${buildDir}/classes/jaxb" - ext.schema = "${projectDir}/../../server/src/main/resources/schema.xsd" - - inputs.files schema - outputs.dir classesDir - - doLast() { - project.ant { - taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask", - classpath: configurations.jaxb.asPath - mkdir(dir: sourcesDir) - mkdir(dir: classesDir) - - xjc(destdir: sourcesDir, schema: schema, - package: "org.springframework.ws.samples.mtom.client.sws") { - produces(dir: sourcesDir, includes: "**/*.java") - } - - javac(destdir: classesDir, source: 1.6, target: 1.6, debug: true, - debugLevel: "lines,vars,source", - classpath: configurations.jaxb.asPath) { - src(path: sourcesDir) - include(name: "**/*.java") - include(name: "*.java") - } - - copy(todir: classesDir) { - fileset(dir: sourcesDir, erroronmissingdir: false) { - exclude(name: "**/*.java") - } - } - } - } -} - -dependencies { - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - compile("org.springframework:spring-context:$springVersion") - compile("org.apache.ws.commons.axiom:axiom-api:1.2.14") - compile(files(genJaxb.classesDir).builtBy(genJaxb)) - - runtime("log4j:log4j:1.2.16") - runtime("org.apache.ws.commons.axiom:axiom-impl:1.2.14") - - jaxb "com.sun.xml.bind:jaxb-xjc:2.1.7" -} - -task runClient(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.mtom.client.sws.Driver" - classpath = sourceSets.main.runtimeClasspath - systemProperty("java.awt.headless", "true") -} \ No newline at end of file diff --git a/mtom/client/spring-ws/pom.xml b/mtom/client/spring-ws/pom.xml new file mode 100644 index 0000000..0f38c57 --- /dev/null +++ b/mtom/client/spring-ws/pom.xml @@ -0,0 +1,112 @@ + + + 4.0.0 + + + org.springframework.ws + spring-ws-samples + 1.0.0.BUILD-SNAPSHOT + ../../../ + + + org.springframework.ws + mtom-client-spring-ws + 0.0.1-SNAPSHOT + Spring Web Services Samples - MTOM - Client - Spring WS + Demo project for Spring Web Services + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web-services + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.codehaus.mojo + jaxb2-maven-plugin + 2.5.0 + + + xjc + + xjc + + + + + WSDL + ${project.basedir}/../../server/src/main/resources/contentStore.wsdl + org.springframework.ws.samples.mtom.client.sws + 2.1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.1 + + + add-source + process-sources + + add-source + + + + ${project.basedir}/target/generated-sources/jaxb + + + + + + + + + + diff --git a/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/AxiomMtomClient.java b/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/AxiomMtomClient.java deleted file mode 100644 index a6ec661..0000000 --- a/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/AxiomMtomClient.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2002-2009 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. - */ - -package org.springframework.ws.samples.mtom.client.sws; - -import java.io.IOException; -import java.util.Iterator; -import javax.activation.DataHandler; -import javax.activation.DataSource; -import javax.activation.FileDataSource; -import javax.imageio.ImageIO; -import javax.xml.transform.TransformerException; - -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.OMNamespace; -import org.apache.axiom.om.OMOutputFormat; -import org.apache.axiom.om.OMText; -import org.apache.axiom.soap.SOAPBody; -import org.apache.axiom.soap.SOAPFactory; -import org.apache.axiom.soap.SOAPMessage; - -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.StopWatch; -import org.springframework.util.StringUtils; -import org.springframework.ws.WebServiceMessage; -import org.springframework.ws.client.core.WebServiceMessageCallback; -import org.springframework.ws.client.core.WebServiceMessageExtractor; -import org.springframework.ws.client.core.support.WebServiceGatewaySupport; -import org.springframework.ws.soap.axiom.AxiomSoapMessage; -import org.springframework.ws.soap.axiom.AxiomSoapMessageFactory; -import org.springframework.ws.soap.client.SoapFaultClientException; - -/** - * Simple client that demonstartes MTOM by invoking StoreImage and LoadImage using a - * WebServiceTemplate and Axiom. - * - * @author Arjen Poutsma - */ -public class AxiomMtomClient extends WebServiceGatewaySupport { - - private StopWatch stopWatch = new StopWatch(ClassUtils.getShortName(getClass())); - - public AxiomMtomClient(AxiomSoapMessageFactory messageFactory) { - super(messageFactory); - } - - public void doIt(String path) { - try { - store(path); - load(path); - System.out.println(stopWatch.prettyPrint()); - } - catch (SoapFaultClientException ex) { - System.err.format("SOAP Fault Code %1s%n", ex.getFaultCode()); - System.err.format("SOAP Fault String: %1s%n", ex.getFaultStringOrReason()); - } - - } - - private void store(final String path) { - stopWatch.start("store"); - getWebServiceTemplate().sendAndReceive(new WebServiceMessageCallback() { - public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { - AxiomSoapMessage soapMessage = (AxiomSoapMessage) message; - SOAPMessage axiomMessage = soapMessage.getAxiomMessage(); - SOAPFactory factory = (SOAPFactory) axiomMessage.getOMFactory(); - SOAPBody body = axiomMessage.getSOAPEnvelope().getBody(); - - OMNamespace ns = - factory.createOMNamespace("http://www.springframework.org/spring-ws/samples/mtom", "tns"); - - OMElement storeImageRequestElement = factory.createOMElement("StoreImageRequest", ns); - body.addChild(storeImageRequestElement); - OMElement nameElement = factory.createOMElement("name", ns); - storeImageRequestElement.addChild(nameElement); - nameElement.setText(StringUtils.getFilename(path)); - OMElement imageElement = factory.createOMElement("image", ns); - storeImageRequestElement.addChild(imageElement); - DataSource dataSource = new FileDataSource(path); - DataHandler dataHandler = new DataHandler(dataSource); - OMText text = factory.createOMText(dataHandler, true); - imageElement.addChild(text); - - OMOutputFormat outputFormat = new OMOutputFormat(); - outputFormat.setSOAP11(true); - outputFormat.setDoOptimize(true); - soapMessage.setOutputFormat(outputFormat); - } - }, new WebServiceMessageExtractor() { - public Object extractData(WebServiceMessage message) throws IOException, TransformerException { - return null; - } - }); - stopWatch.stop(); - } - - private void load(final String path) { - final StringBuilder name = new StringBuilder(); - stopWatch.start("load"); - java.awt.Image image = (java.awt.Image) getWebServiceTemplate().sendAndReceive(new WebServiceMessageCallback() { - public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { - SOAPMessage axiomMessage = ((AxiomSoapMessage) message).getAxiomMessage(); - SOAPFactory factory = (SOAPFactory) axiomMessage.getOMFactory(); - SOAPBody body = axiomMessage.getSOAPEnvelope().getBody(); - - OMNamespace ns = - factory.createOMNamespace("http://www.springframework.org/spring-ws/samples/mtom", "tns"); - - OMElement loadImageRequestElement = factory.createOMElement("LoadImageRequest", ns); - loadImageRequestElement.setText(StringUtils.getFilename(path)); - body.addChild(loadImageRequestElement); - } - }, new WebServiceMessageExtractor() { - public Object extractData(WebServiceMessage message) throws IOException, TransformerException { - SOAPMessage axiomMessage = ((AxiomSoapMessage) message).getAxiomMessage(); - SOAPBody body = axiomMessage.getSOAPEnvelope().getBody(); - OMElement loadImageResponseElement = (OMElement) body.getChildElements().next(); - Assert.isTrue("LoadImageResponse".equals(loadImageResponseElement.getLocalName())); - Iterator childElements = loadImageResponseElement.getChildElements(); - OMElement nameElement = (OMElement) childElements.next(); - Assert.isTrue("name".equals(nameElement.getLocalName())); - name.append(nameElement.getText()); - OMElement imageElement = (OMElement) childElements.next(); - Assert.isTrue("image".equals(imageElement.getLocalName())); - OMText text = (OMText) imageElement.getFirstOMChild(); - - DataHandler dataHandler = (DataHandler) text.getDataHandler(); - return ImageIO.read(dataHandler.getInputStream()); - } - }); - stopWatch.stop(); - logger.info("Received image " + name + " [" + image.getWidth(null) + "x" + image.getHeight(null) + "]"); - } - - -} diff --git a/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/Driver.java b/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/Driver.java deleted file mode 100644 index 8bea663..0000000 --- a/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/Driver.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2002-2009 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. - */ - -package org.springframework.ws.samples.mtom.client.sws; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -public class Driver { - - public static void main(String[] args) { - String fileName = "../spring-ws-logo.png"; - if (args.length > 0) { - fileName = args[0]; - } - ApplicationContext applicationContext = - new AnnotationConfigApplicationContext(MtomClientConfig.class); - - SaajMtomClient saajClient = applicationContext.getBean("saajClient", SaajMtomClient.class); - saajClient.doIt(fileName); - - AxiomMtomClient axiomClient = applicationContext.getBean("axiomClient", AxiomMtomClient.class); - axiomClient.doIt(fileName); - } - -} diff --git a/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/MtomClientConfig.java b/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/MtomClientConfig.java index 6e18eac..04de5f7 100644 --- a/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/MtomClientConfig.java +++ b/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/MtomClientConfig.java @@ -3,7 +3,6 @@ package org.springframework.ws.samples.mtom.client.sws; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.oxm.jaxb.Jaxb2Marshaller; -import org.springframework.ws.soap.axiom.AxiomSoapMessageFactory; import org.springframework.ws.soap.saaj.SaajSoapMessageFactory; /** @@ -13,11 +12,12 @@ import org.springframework.ws.soap.saaj.SaajSoapMessageFactory; public class MtomClientConfig { @Bean - public SaajMtomClient saajClient() { - SaajMtomClient client = new SaajMtomClient(saajSoapMessageFactory()); + public SaajMtomClient saajClient(SaajSoapMessageFactory messageFactory, Jaxb2Marshaller marshaller) { + + SaajMtomClient client = new SaajMtomClient(messageFactory); client.setDefaultUri("http://localhost:8080/mtom-server/services"); - client.setMarshaller(marshaller()); - client.setUnmarshaller(marshaller()); + client.setMarshaller(marshaller); + client.setUnmarshaller(marshaller); return client; } @@ -26,20 +26,9 @@ public class MtomClientConfig { return new SaajSoapMessageFactory(); } - @Bean - public AxiomMtomClient axiomClient() { - AxiomMtomClient client = new AxiomMtomClient(axiomSoapMessageFactory()); - client.setDefaultUri("http://localhost:8080/mtom-server/services"); - return client; - } - - @Bean - public AxiomSoapMessageFactory axiomSoapMessageFactory() { - return new AxiomSoapMessageFactory(); - } - @Bean public Jaxb2Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath("org.springframework.ws.samples.mtom.client.sws"); marshaller.setMtomEnabled(true); diff --git a/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/SaajMtomClient.java b/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/SaajMtomClient.java index b891979..e70e4f0 100644 --- a/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/SaajMtomClient.java +++ b/mtom/client/spring-ws/src/main/java/org/springframework/ws/samples/mtom/client/sws/SaajMtomClient.java @@ -16,68 +16,121 @@ package org.springframework.ws.samples.mtom.client.sws; -import java.awt.Toolkit; -import javax.xml.bind.JAXBElement; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import javax.activation.DataHandler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; import org.springframework.util.ClassUtils; import org.springframework.util.StopWatch; -import org.springframework.util.StringUtils; import org.springframework.ws.client.core.support.WebServiceGatewaySupport; -import org.springframework.ws.soap.client.SoapFaultClientException; import org.springframework.ws.soap.saaj.SaajSoapMessageFactory; /** - * Simple client that demonstrates MTOM by invoking {@code StoreImage} and {@code LoadImage} using a - * WebServiceTemplate and SAAJ. + * Simple client that demonstrates MTOM by invoking {@code StoreImage} and {@code LoadImage} using a WebServiceTemplate + * and SAAJ. * * @author Tareq Abed Rabbo * @author Arjen Poutsma */ +@SpringBootApplication public class SaajMtomClient extends WebServiceGatewaySupport { - private ObjectFactory objectFactory = new ObjectFactory(); + public static void main(String[] args) { + SpringApplication.run(SaajMtomClient.class, args); + } - private StopWatch stopWatch = new StopWatch(ClassUtils.getShortName(getClass())); + @Bean + CommandLineRunner invoke(SaajMtomClient saajClient) { - public SaajMtomClient(SaajSoapMessageFactory messageFactory) { - super(messageFactory); - } + return args -> { + saajClient.storeContent(); + saajClient.loadContent(); + }; + } - public void doIt(String path) { - try { - store(path); - load(path); - System.out.println(stopWatch.prettyPrint()); - } - catch (SoapFaultClientException ex) { - System.err.format("SOAP Fault Code %1s%n", ex.getFaultCode()); - System.err.format("SOAP Fault String: %1s%n", ex.getFaultStringOrReason()); - } + private static final Logger logger = LoggerFactory.getLogger(SaajMtomClient.class); - } + private ObjectFactory objectFactory = new ObjectFactory(); + private StopWatch stopWatch = new StopWatch(ClassUtils.getShortName(getClass())); - private void store(String path) { - Image image = objectFactory.createImage(); - image.setName(StringUtils.getFilename(path)); - image.setImage(Toolkit.getDefaultToolkit().getImage(path)); - JAXBElement storeImageRequest = objectFactory.createStoreImageRequest(image); - stopWatch.start("store"); - getWebServiceTemplate().marshalSendAndReceive(storeImageRequest); - stopWatch.stop(); - } + public SaajMtomClient(SaajSoapMessageFactory messageFactory) { + super(messageFactory); + } - @SuppressWarnings("unchecked") - private void load(String path) { - JAXBElement loadImageRequest = objectFactory.createLoadImageRequest(StringUtils.getFilename(path)); + public void storeContent() { - stopWatch.start("load"); - JAXBElement loadImageResponse = - (JAXBElement) getWebServiceTemplate().marshalSendAndReceive(loadImageRequest); - stopWatch.stop(); - Image image = loadImageResponse.getValue(); - logger.info("Received image " + image.getName() + " [" + image.getImage().getWidth(null) + "x" + - image.getImage().getHeight(null) + "]"); + StoreContentRequest storeContentRequest = this.objectFactory.createStoreContentRequest(); - } + storeContentRequest.setName("spring-ws-logo"); + storeContentRequest + .setContent(new DataHandler(Thread.currentThread().getContextClassLoader().getResource("spring-ws-logo.png"))); + this.stopWatch.start("store"); + + getWebServiceTemplate().marshalSendAndReceive(storeContentRequest); + + this.stopWatch.stop(); + + logger.info(this.stopWatch.prettyPrint()); + } + + public void loadContent() throws IOException { + + LoadContentRequest loadContentRequest = this.objectFactory.createLoadContentRequest(); + loadContentRequest.setName("spring-ws-logo"); + + String tmpDir = System.getProperty("java.io.tmpdir"); + File out = new File(tmpDir, "spring_mtom_tmp.bin"); + + long freeBefore = Runtime.getRuntime().freeMemory(); + + this.stopWatch.start("load"); + + LoadContentResponse loadContentResponse = (LoadContentResponse) getWebServiceTemplate() + .marshalSendAndReceive(loadContentRequest); + + this.stopWatch.stop(); + + DataHandler content = loadContentResponse.getContent(); + long freeAfter = Runtime.getRuntime().freeMemory(); + + logger.info("Memory usage [kB]: " + ((freeAfter - freeBefore) / 1024)); + + this.stopWatch.start("loadAttachmentContent"); + + long size = saveContentToFile(content, out); + + this.stopWatch.stop(); + + logger.info("Received file size [kB]: " + size); + logger.info("Stored at " + out.getAbsolutePath()); + logger.info(this.stopWatch.prettyPrint()); + } + + private static long saveContentToFile(DataHandler content, File outFile) throws IOException { + + long size = 0; + + byte[] buffer = new byte[1024]; + try (InputStream in = content.getInputStream()) { + try (OutputStream out = new FileOutputStream(outFile)) { + for (int readBytes; (readBytes = in.read(buffer, 0, buffer.length)) > 0;) { + size += readBytes; + out.write(buffer, 0, readBytes); + } + } + } + + return size; + } } diff --git a/mtom/client/spring-ws/src/main/resources/application.yml b/mtom/client/spring-ws/src/main/resources/application.yml new file mode 100644 index 0000000..a74a6c1 --- /dev/null +++ b/mtom/client/spring-ws/src/main/resources/application.yml @@ -0,0 +1,3 @@ +logging: + level: + org.springframework.ws: DEBUG \ No newline at end of file diff --git a/mtom/client/spring-ws/src/main/resources/log4j.properties b/mtom/client/spring-ws/src/main/resources/log4j.properties deleted file mode 100644 index ecbc6e2..0000000 --- a/mtom/client/spring-ws/src/main/resources/log4j.properties +++ /dev/null @@ -1,6 +0,0 @@ -log4j.rootLogger=WARN, stdout -log4j.logger.org.springframework.ws.samples=INFO - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n diff --git a/mtom/client/spring-ws-logo.png b/mtom/client/spring-ws/src/main/resources/spring-ws-logo.png similarity index 100% rename from mtom/client/spring-ws-logo.png rename to mtom/client/spring-ws/src/main/resources/spring-ws-logo.png diff --git a/mtom/server/build.gradle b/mtom/server/build.gradle deleted file mode 100644 index c87f111..0000000 --- a/mtom/server/build.gradle +++ /dev/null @@ -1,78 +0,0 @@ -configurations { - jaxb -} - -buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.9' - } -} - -ext.tomcatVersion = '7.0.42' - - -apply plugin: 'war' -apply plugin: 'tomcat' - -task genJaxb { - ext.sourcesDir = "${buildDir}/generated-sources/jaxb" - ext.classesDir = "${buildDir}/classes/jaxb" - ext.schema = "${projectDir}/src/main/resources/schema.xsd" - - inputs.files schema - outputs.dir classesDir - - doLast() { - project.ant { - taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask", - classpath: configurations.jaxb.asPath - mkdir(dir: sourcesDir) - mkdir(dir: classesDir) - - xjc(destdir: sourcesDir, schema: schema, - package: "org.springframework.ws.samples.mtom.schema") { - produces(dir: sourcesDir, includes: "**/*.java") - } - - javac(destdir: classesDir, source: 1.6, target: 1.6, debug: true, - debugLevel: "lines,vars,source", - classpath: configurations.jaxb.asPath) { - src(path: sourcesDir) - include(name: "**/*.java") - include(name: "*.java") - } - - copy(todir: classesDir) { - fileset(dir: sourcesDir, erroronmissingdir: false) { - exclude(name: "**/*.java") - } - } - } - } -} - - -tomcatRun { - contextPath = 'mtom-server' -} - -dependencies { - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - compile("org.springframework:spring-context:$springVersion") - compile(files(genJaxb.classesDir).builtBy(genJaxb)) - - runtime("log4j:log4j:1.2.16") - runtime("wsdl4j:wsdl4j:1.6.1") - - jaxb "com.sun.xml.bind:jaxb-xjc:2.1.7" - - tomcat("org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion", - "org.apache.tomcat.embed:tomcat-embed-logging-juli:$tomcatVersion") - tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:$tomcatVersion") { - exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj' - } -} diff --git a/mtom/server/pom.xml b/mtom/server/pom.xml new file mode 100644 index 0000000..7298b3a --- /dev/null +++ b/mtom/server/pom.xml @@ -0,0 +1,119 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.3.1.RELEASE + + + + org.springframework.ws + mtom-server + 0.0.1-SNAPSHOT + Spring Web Services Samples - MTOM - Server + Demo project for Spring Web Services + + + 1.8 + 2.10.6 + 1.2.16 + 2.0.2 + + + + + + org.springframework.boot + spring-boot-starter-web-services + + + + wsdl4j + wsdl4j + + + + org.apache.ws.xmlschema + xmlschema-core + ${xmlschema.version} + runtime + + + + org.springframework + spring-test + test + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.codehaus.mojo + jaxb2-maven-plugin + 2.5.0 + + + xjc + + xjc + + + + + WSDL + ${project.basedir}/src/main/resources/contentStore.wsdl + org.springframework.ws.samples.mtom.schema + 2.1 + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.1 + + + add-source + process-sources + + add-source + + + + target/generated-sources/jaxb + + + + + + + + + + + + diff --git a/mtom/server/src/main/java/org/springframework/ws/samples/mtom/MtomServer.java b/mtom/server/src/main/java/org/springframework/ws/samples/mtom/MtomServer.java new file mode 100644 index 0000000..8ab8042 --- /dev/null +++ b/mtom/server/src/main/java/org/springframework/ws/samples/mtom/MtomServer.java @@ -0,0 +1,12 @@ +package org.springframework.ws.samples.mtom; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MtomServer { + + public static void main(String[] args) { + SpringApplication.run(MtomServer.class, args); + } +} diff --git a/mtom/server/src/main/java/org/springframework/ws/samples/mtom/config/MtomServerConfiguration.java b/mtom/server/src/main/java/org/springframework/ws/samples/mtom/config/MtomServerConfiguration.java index 307d942..8013e0b 100644 --- a/mtom/server/src/main/java/org/springframework/ws/samples/mtom/config/MtomServerConfiguration.java +++ b/mtom/server/src/main/java/org/springframework/ws/samples/mtom/config/MtomServerConfiguration.java @@ -1,66 +1,37 @@ package org.springframework.ws.samples.mtom.config; -import java.util.ArrayList; -import java.util.List; +import java.util.Collections; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.oxm.jaxb.Jaxb2Marshaller; -import org.springframework.ws.config.annotation.EnableWs; -import org.springframework.ws.config.annotation.WsConfigurationSupport; -import org.springframework.ws.samples.mtom.service.ImageRepository; -import org.springframework.ws.samples.mtom.service.StubImageRepository; -import org.springframework.ws.samples.mtom.ws.ImageRepositoryEndpoint; import org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter; import org.springframework.ws.server.endpoint.adapter.method.MarshallingPayloadMethodProcessor; -import org.springframework.ws.server.endpoint.adapter.method.MethodArgumentResolver; -import org.springframework.ws.server.endpoint.adapter.method.MethodReturnValueHandler; -import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition; -import org.springframework.xml.xsd.SimpleXsdSchema; +import org.springframework.ws.transport.http.MessageDispatcherServlet; +import org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition; /** * @author Arjen Poutsma */ -@EnableWs @Configuration -public class MtomServerConfiguration extends WsConfigurationSupport { +public class MtomServerConfiguration { @Bean - public ImageRepository imageRepository() { - return new StubImageRepository(); - } + ServletRegistrationBean webServicesRegistration(ApplicationContext ctx) { - @Bean - public ImageRepositoryEndpoint imageRepositoryEndpoint() { - return new ImageRepositoryEndpoint(imageRepository()); - } + MessageDispatcherServlet messageDispatcherServlet = new MessageDispatcherServlet(); + messageDispatcherServlet.setApplicationContext(ctx); + messageDispatcherServlet.setTransformWsdlLocations(true); - @Bean - @Override - public DefaultMethodEndpointAdapter defaultMethodEndpointAdapter() { - List argumentResolvers = - new ArrayList(); - argumentResolvers.add(methodProcessor()); - - List returnValueHandlers = - new ArrayList(); - returnValueHandlers.add(methodProcessor()); - - DefaultMethodEndpointAdapter adapter = new DefaultMethodEndpointAdapter(); - adapter.setMethodArgumentResolvers(argumentResolvers); - adapter.setMethodReturnValueHandlers(returnValueHandlers); - - return adapter; - } - - @Bean - public MarshallingPayloadMethodProcessor methodProcessor() { - return new MarshallingPayloadMethodProcessor(marshaller()); + return new ServletRegistrationBean<>(messageDispatcherServlet, "/mtom-server/*", "*.wsdl"); } @Bean public Jaxb2Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath("org.springframework.ws.samples.mtom.schema"); marshaller.setMtomEnabled(true); @@ -68,17 +39,25 @@ public class MtomServerConfiguration extends WsConfigurationSupport { } @Bean - public DefaultWsdl11Definition mtom() { - DefaultWsdl11Definition definition = new DefaultWsdl11Definition(); - definition.setSchema(schema()); - definition.setPortTypeName("ImageRepository"); - definition.setLocationUri("http://localhost:8080/mtom-server/"); - return definition; + public MarshallingPayloadMethodProcessor methodProcessor(Jaxb2Marshaller marshaller) { + return new MarshallingPayloadMethodProcessor(marshaller); } @Bean - public SimpleXsdSchema schema() { - return new SimpleXsdSchema(new ClassPathResource("/schema.xsd")); + DefaultMethodEndpointAdapter endpointAdapter(MarshallingPayloadMethodProcessor methodProcessor) { + + DefaultMethodEndpointAdapter adapter = new DefaultMethodEndpointAdapter(); + adapter.setMethodArgumentResolvers(Collections.singletonList(methodProcessor)); + adapter.setMethodReturnValueHandlers(Collections.singletonList(methodProcessor)); + return adapter; + } + + @Bean + public SimpleWsdl11Definition contentStore() { + + SimpleWsdl11Definition definition = new SimpleWsdl11Definition(); + definition.setWsdl(new ClassPathResource("/contentStore.wsdl")); + return definition; } } diff --git a/mtom/server/src/main/java/org/springframework/ws/samples/mtom/service/ImageRepository.java b/mtom/server/src/main/java/org/springframework/ws/samples/mtom/service/ContentRepository.java similarity index 78% rename from mtom/server/src/main/java/org/springframework/ws/samples/mtom/service/ImageRepository.java rename to mtom/server/src/main/java/org/springframework/ws/samples/mtom/service/ContentRepository.java index 3107214..f02ecc2 100644 --- a/mtom/server/src/main/java/org/springframework/ws/samples/mtom/service/ImageRepository.java +++ b/mtom/server/src/main/java/org/springframework/ws/samples/mtom/service/ContentRepository.java @@ -16,14 +16,16 @@ package org.springframework.ws.samples.mtom.service; -import java.awt.Image; +import java.io.File; import java.io.IOException; +import javax.activation.DataHandler; + /** @author Arjen Poutsma */ -public interface ImageRepository { +public interface ContentRepository { - Image readImage(String name) throws IOException; + File loadContent(String name); - void storeImage(String name, Image image) throws IOException; + void storeContent(String name, DataHandler content) throws IOException; } diff --git a/mtom/server/src/main/java/org/springframework/ws/samples/mtom/service/ContentRepositoryImpl.java b/mtom/server/src/main/java/org/springframework/ws/samples/mtom/service/ContentRepositoryImpl.java new file mode 100644 index 0000000..174301a --- /dev/null +++ b/mtom/server/src/main/java/org/springframework/ws/samples/mtom/service/ContentRepositoryImpl.java @@ -0,0 +1,63 @@ +/* + * Copyright 2002-2009 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. + */ + +package org.springframework.ws.samples.mtom.service; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import javax.activation.DataHandler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +/** @author Arjen Poutsma */ +@Service +class ContentRepositoryImpl implements ContentRepository { + + private static final Logger logger = LoggerFactory.getLogger(ContentRepositoryImpl.class); + + @Value(value = "#{ systemProperties['java.io.tmpdir'] }") // + private String fileStorePath; + + @Override + public File loadContent(String name) { + return new File(this.fileStorePath, name + ".tmp"); + } + + @Override + public void storeContent(String name, DataHandler content) throws IOException { + + File outFile = new File(this.fileStorePath, name + ".tmp"); + logger.info("Storing content in file: {}", outFile.getAbsolutePath()); + + int i = 0; + byte[] buffer = new byte[1024]; + try (InputStream in = content.getInputStream()) { + try (OutputStream out = new FileOutputStream(outFile)) { + while ((i = in.read(buffer, 0, buffer.length)) > 0) { + out.write(buffer, 0, i); + } + } + } + logger.info("Content stored."); + } +} diff --git a/mtom/server/src/main/java/org/springframework/ws/samples/mtom/service/StubImageRepository.java b/mtom/server/src/main/java/org/springframework/ws/samples/mtom/service/StubImageRepository.java deleted file mode 100644 index abdd25f..0000000 --- a/mtom/server/src/main/java/org/springframework/ws/samples/mtom/service/StubImageRepository.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2002-2009 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. - */ - -package org.springframework.ws.samples.mtom.service; - -import java.awt.Image; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** @author Arjen Poutsma */ -public class StubImageRepository implements ImageRepository { - - private static final Log logger = LogFactory.getLog(StubImageRepository.class); - - private Map images = new HashMap(); - - @Override - public Image readImage(String name) throws IOException { - logger.info("Loading image " + name); - return images.get(name); - } - - @Override - public void storeImage(String name, Image image) throws IOException { - logger.info("Storing image " + name + " [" + image.getWidth(null) + "x" + image.getHeight(null) + "]"); - images.put(name, image); - } -} diff --git a/mtom/server/src/main/java/org/springframework/ws/samples/mtom/ws/ContentRepositoryEndpoint.java b/mtom/server/src/main/java/org/springframework/ws/samples/mtom/ws/ContentRepositoryEndpoint.java new file mode 100644 index 0000000..dab267e --- /dev/null +++ b/mtom/server/src/main/java/org/springframework/ws/samples/mtom/ws/ContentRepositoryEndpoint.java @@ -0,0 +1,76 @@ +/* + * Copyright 2005-2012 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. + */ + +package org.springframework.ws.samples.mtom.ws; + +import java.io.File; +import java.io.IOException; + +import javax.activation.DataHandler; +import javax.activation.FileDataSource; + +import org.springframework.util.Assert; +import org.springframework.ws.samples.mtom.schema.LoadContentRequest; +import org.springframework.ws.samples.mtom.schema.LoadContentResponse; +import org.springframework.ws.samples.mtom.schema.ObjectFactory; +import org.springframework.ws.samples.mtom.schema.StoreContentRequest; +import org.springframework.ws.samples.mtom.schema.StoreContentResponse; +import org.springframework.ws.samples.mtom.service.ContentRepository; +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 org.springframework.ws.server.endpoint.annotation.ResponsePayload; + +/** @author Arjen Poutsma */ +@Endpoint +public class ContentRepositoryEndpoint { + + private ContentRepository contentRepository; + + private ObjectFactory objectFactory; + + public ContentRepositoryEndpoint(ContentRepository contentRepository) { + + Assert.notNull(contentRepository, "'imageRepository' must not be null"); + + this.contentRepository = contentRepository; + this.objectFactory = new ObjectFactory(); + } + + @PayloadRoot(localPart = "StoreContentRequest", namespace = "http://www.springframework.org/spring-ws/samples/mtom") + @ResponsePayload + public StoreContentResponse store(@RequestPayload StoreContentRequest storeContentRequest) throws IOException { + + this.contentRepository.storeContent(storeContentRequest.getName(), storeContentRequest.getContent()); + StoreContentResponse response = this.objectFactory.createStoreContentResponse(); + response.setMessage("Success"); + return response; + } + + @PayloadRoot(localPart = "LoadContentRequest", namespace = "http://www.springframework.org/spring-ws/samples/mtom") + @ResponsePayload + public LoadContentResponse load(@RequestPayload LoadContentRequest loadContentRequest) throws IOException { + + LoadContentResponse response = this.objectFactory.createLoadContentResponse(); + + File contentFile = this.contentRepository.loadContent(loadContentRequest.getName()); + DataHandler dataHandler = new DataHandler(new FileDataSource(contentFile)); + response.setName(loadContentRequest.getName()); + response.setContent(dataHandler); + return response; + } + +} diff --git a/mtom/server/src/main/java/org/springframework/ws/samples/mtom/ws/ImageRepositoryEndpoint.java b/mtom/server/src/main/java/org/springframework/ws/samples/mtom/ws/ImageRepositoryEndpoint.java deleted file mode 100644 index bacba4c..0000000 --- a/mtom/server/src/main/java/org/springframework/ws/samples/mtom/ws/ImageRepositoryEndpoint.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2005-2012 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. - */ - -package org.springframework.ws.samples.mtom.ws; - -import java.io.IOException; -import javax.xml.bind.JAXBElement; - -import org.springframework.util.Assert; -import org.springframework.ws.samples.mtom.schema.Image; -import org.springframework.ws.samples.mtom.schema.ObjectFactory; -import org.springframework.ws.samples.mtom.service.ImageRepository; -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 org.springframework.ws.server.endpoint.annotation.ResponsePayload; - -/** @author Arjen Poutsma */ -@Endpoint -public class ImageRepositoryEndpoint { - - private ImageRepository imageRepository; - - private ObjectFactory objectFactory; - - public ImageRepositoryEndpoint(ImageRepository imageRepository) { - Assert.notNull(imageRepository, "'imageRepository' must not be null"); - this.imageRepository = imageRepository; - this.objectFactory = new ObjectFactory(); - } - - @PayloadRoot(localPart = "StoreImageRequest", namespace = "http://www.springframework.org/spring-ws/samples/mtom") - @ResponsePayload - public void store(@RequestPayload JAXBElement requestElement) throws IOException { - Image request = requestElement.getValue(); - imageRepository.storeImage(request.getName(), request.getImage()); - } - - @PayloadRoot(localPart = "LoadImageRequest", namespace = "http://www.springframework.org/spring-ws/samples/mtom") - @ResponsePayload - public JAXBElement load(@RequestPayload JAXBElement requestElement) throws IOException { - String name = requestElement.getValue(); - Image response = new Image(); - response.setName(name); - response.setImage(imageRepository.readImage(name)); - return objectFactory.createLoadImageResponse(response); - } - - -} diff --git a/mtom/server/src/main/resources/application.yml b/mtom/server/src/main/resources/application.yml new file mode 100644 index 0000000..a74a6c1 --- /dev/null +++ b/mtom/server/src/main/resources/application.yml @@ -0,0 +1,3 @@ +logging: + level: + org.springframework.ws: DEBUG \ No newline at end of file diff --git a/mtom/server/src/main/resources/contentStore.wsdl b/mtom/server/src/main/resources/contentStore.wsdl new file mode 100644 index 0000000..8226e9b --- /dev/null +++ b/mtom/server/src/main/resources/contentStore.wsdl @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/mtom/server/src/main/resources/log4j.properties b/mtom/server/src/main/resources/log4j.properties deleted file mode 100644 index 5bb7c90..0000000 --- a/mtom/server/src/main/resources/log4j.properties +++ /dev/null @@ -1,8 +0,0 @@ -log4j.rootLogger=WARN, stdout -log4j.logger.org.springframework.ws=DEBUG -log4j.logger.org.springframework.xml=DEBUG -log4j.logger.org.springframework.ws.samples=INFO - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n diff --git a/mtom/server/src/main/resources/schema.xsd b/mtom/server/src/main/resources/schema.xsd deleted file mode 100644 index 54c033e..0000000 --- a/mtom/server/src/main/resources/schema.xsd +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/mtom/server/src/main/webapp/WEB-INF/web.xml b/mtom/server/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index b843902..0000000 --- a/mtom/server/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - MyCompany HR Holiday Service - - - spring-ws - org.springframework.ws.transport.http.MessageDispatcherServlet - - contextClass - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - contextConfigLocation - org.springframework.ws.samples.mtom.config.MtomServerConfiguration - - - - - spring-ws - /* - - - diff --git a/mtom/settings.gradle b/mtom/settings.gradle deleted file mode 100644 index b3428de..0000000 --- a/mtom/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ - -include "server", "client:jax-ws", "client:spring-ws" diff --git a/mvnw b/mvnw new file mode 100755 index 0000000..5551fde --- /dev/null +++ b/mvnw @@ -0,0 +1,286 @@ +#!/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 Mingw, 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 + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +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 "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..e5cfb0a --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,161 @@ +@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 set title of command window +title %0 +@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 + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%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% diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..8872957 --- /dev/null +++ b/pom.xml @@ -0,0 +1,83 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.3.1.RELEASE + + + + org.springframework.ws + spring-ws-samples + 1.0.0.BUILD-SNAPSHOT + pom + + Spring Web Services Samples + + 2019 + + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + + Copyright 2020 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. + + + + + + airline/client/axis1 + airline/client/jax-ws + airline/client/jms + airline/client/saaj + airline/client/spring-ws + airline/server + echo/client/saaj + echo/client/spring-ws + echo/server + mtom/client/spring-ws + mtom/server + tutorial + weather + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + org.springframework + spring-test + test + + + + + \ No newline at end of file diff --git a/stockquote/README.md b/stockquote/README.md deleted file mode 100644 index a2a5deb..0000000 --- a/stockquote/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# Stock Quote Sample - -This sample shows a Stock Quote service. Incoming messages are routed via -WS-Addressing, and SOAP message content is handled using JAXB2. Additionally, -this sample uses the HTTP server built into Java 6. - -## Running the Server - -The server can be built and run using the following command from -within the ``server`` folder. - - ```sh - $ ./gradlew runServer - ``` - -## Running the Client(s) - -There is a separate ``client`` directory containing clients that connect to the -server. You can run these clients by using the following command from within -each of client subdirectories: - - ```sh - $ gradle runClient - ``` - -## License - -[Spring Web Services] is released under version 2.0 of the [Apache License]. - -[Spring Web Services]: https://projects.spring.io/spring-ws -[Apache License]: http://www.apache.org/licenses/LICENSE-2.0 \ No newline at end of file diff --git a/stockquote/build.gradle b/stockquote/build.gradle deleted file mode 100644 index 33585ee..0000000 --- a/stockquote/build.gradle +++ /dev/null @@ -1,18 +0,0 @@ -ext.springWsVersion = '2.2.0.RELEASE' -ext.springVersion = '4.0.5.RELEASE' - -subprojects { - apply plugin: 'java' - apply plugin: 'eclipse' - apply plugin: 'idea' - - repositories { - maven { url 'https://repo.spring.io/libs-release' } - } - - dependencies { - testCompile("junit:junit:4.10") - testCompile("org.easymock:easymock:3.1") - } - -} diff --git a/stockquote/client/jax-ws/build.gradle b/stockquote/client/jax-ws/build.gradle deleted file mode 100644 index f89b89c..0000000 --- a/stockquote/client/jax-ws/build.gradle +++ /dev/null @@ -1,38 +0,0 @@ -configurations { - wsimport -} - -ext.springWsVersion = '2.1.4.RELEASE' - -task wsImport { - ext.outputDir = "${buildDir}/classes/wsimport" - ext.wsdl = "${projectDir}/../../server//src/main/resources/org/springframework/ws/samples/stockquote/ws/stockquote.wsdl" - - inputs.files wsdl - outputs.dir outputDir - - doLast() { - project.ant { - taskdef name: "wsimport", classname: "com.sun.tools.ws.ant.WsImport", - classpath: configurations.wsimport.asPath - mkdir(dir: outputDir) - - wsimport(destdir: outputDir, wsdl: wsdl, - package: "org.springframework.ws.samples.stockquote.client.jaxws") { - produces(dir: outputDir, includes: "**/*.class") - } - } - } -} - -dependencies { - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - compile(files(wsImport.outputDir).builtBy(wsImport)) - runtime("log4j:log4j:1.2.16") - wsimport "com.sun.xml.ws:jaxws-tools:2.1.7" -} - -task runClient(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.stockquote.client.jaxws.Main" - classpath = sourceSets.main.runtimeClasspath -} \ No newline at end of file diff --git a/stockquote/client/jax-ws/src/main/java/org/springframework/ws/samples/stockquote/client/jaxws/Main.java b/stockquote/client/jax-ws/src/main/java/org/springframework/ws/samples/stockquote/client/jaxws/Main.java deleted file mode 100644 index 8931d2f..0000000 --- a/stockquote/client/jax-ws/src/main/java/org/springframework/ws/samples/stockquote/client/jaxws/Main.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2006 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. - */ - -package org.springframework.ws.samples.stockquote.client.jaxws; - -import java.net.URL; -import javax.xml.namespace.QName; - -/** - * Simple client that calls the StockQuote operations using JAX-WS. - * - * @author Arjen Poutsma - */ -public class Main { - - public static void main(String[] args) throws Exception { - StockService service; - if (args.length == 0) { - service = new StockService(); - } - else { - QName serviceName = new QName("http://www.springframework.org/spring-ws/samples/stockquote", "StockSoap11"); - service = new StockService(new URL(args[0]), serviceName); - } - Stock stock = service.getStockSoap11(); - StockQuoteRequest request = new StockQuoteRequest(); - request.getSymbol().add("FABRIKAM"); - request.getSymbol().add("CONTOSO"); - - System.out.format("Requesting quotes for %s%n", request.getSymbol()); - - StockQuoteResponse response = stock.stockQuote(request); - - System.out.format("Got %d results%n", response.getStockQuote().size()); - for (StockQuote quote : response.getStockQuote()) { - System.out.println(); - System.out.println("Symbol: " + quote.getSymbol()); - System.out.println("\tName:\t\t\t" + quote.getName()); - System.out.println("\tLast Price:\t\t" + quote.getLast()); - System.out.println("\tPrevious Change:\t" + quote.getChange() + "%"); - } - } - -} diff --git a/stockquote/client/spring-ws/build.gradle b/stockquote/client/spring-ws/build.gradle deleted file mode 100644 index b441968..0000000 --- a/stockquote/client/spring-ws/build.gradle +++ /dev/null @@ -1,9 +0,0 @@ -dependencies { - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - runtime("log4j:log4j:1.2.16") -} - -task runClient(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.stockquote.client.sws.StockClient" - classpath = sourceSets.main.runtimeClasspath -} \ No newline at end of file diff --git a/stockquote/client/spring-ws/src/main/java/org/springframework/ws/samples/stockquote/client/sws/StockClient.java b/stockquote/client/spring-ws/src/main/java/org/springframework/ws/samples/stockquote/client/sws/StockClient.java deleted file mode 100644 index fafd272..0000000 --- a/stockquote/client/spring-ws/src/main/java/org/springframework/ws/samples/stockquote/client/sws/StockClient.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2007 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. - */ - -package org.springframework.ws.samples.stockquote.client.sws; - -import java.io.IOException; -import java.net.URI; -import javax.xml.transform.Source; - -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.ws.client.core.support.WebServiceGatewaySupport; -import org.springframework.ws.soap.addressing.client.ActionCallback; -import org.springframework.xml.transform.ResourceSource; -import org.springframework.xml.transform.StringResult; - -public class StockClient extends WebServiceGatewaySupport { - - private Resource request; - - private URI action; - - public void setRequest(Resource request) { - this.request = request; - } - - public void setAction(URI action) { - this.action = action; - } - - public void quotes() throws IOException { - Source requestSource = new ResourceSource(request); - StringResult result = new StringResult(); - getWebServiceTemplate().sendSourceAndReceiveToResult(requestSource, new ActionCallback(action), result); - System.out.println(); - System.out.println(result); - System.out.println(); - } - - public static void main(String[] args) throws Exception { - StockClient stockClient = new StockClient(); - stockClient.setDefaultUri("http://localhost:8080/StockService"); - stockClient.setRequest(new ClassPathResource("/org/springframework/ws/samples/stockquote/client/sws/quotesRequest.xml")); - stockClient.setAction(new URI("http://www.springframework.org/spring-ws/samples/stockquote/StockService/GetQuote")); - - stockClient.quotes(); - } - -} diff --git a/stockquote/client/spring-ws/src/main/resources/log4j.properties b/stockquote/client/spring-ws/src/main/resources/log4j.properties deleted file mode 100644 index 0f73a75..0000000 --- a/stockquote/client/spring-ws/src/main/resources/log4j.properties +++ /dev/null @@ -1,7 +0,0 @@ -log4j.rootLogger=WARN, stdout -log4j.logger.org.springframework.ws=DEBUG -log4j.logger.org.springframework.xml=DEBUG - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n \ No newline at end of file diff --git a/stockquote/client/spring-ws/src/main/resources/org/springframework/ws/samples/stockquote/client/sws/quotesRequest.xml b/stockquote/client/spring-ws/src/main/resources/org/springframework/ws/samples/stockquote/client/sws/quotesRequest.xml deleted file mode 100644 index b40a2dc..0000000 --- a/stockquote/client/spring-ws/src/main/resources/org/springframework/ws/samples/stockquote/client/sws/quotesRequest.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - FABRIKAM - CONTOSO - diff --git a/stockquote/server/build.gradle b/stockquote/server/build.gradle deleted file mode 100644 index 38c3e36..0000000 --- a/stockquote/server/build.gradle +++ /dev/null @@ -1,57 +0,0 @@ -configurations { - jaxb -} - -task genJaxb { - ext.sourcesDir = "${buildDir}/generated-sources/jaxb" - ext.classesDir = "${buildDir}/classes/jaxb" - ext.schema = "${projectDir}/src/main/resources/org/springframework/ws/samples/stockquote/ws/stockquote.wsdl" - - inputs.files schema - outputs.dir classesDir - - doLast() { - project.ant { - taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask", - classpath: configurations.jaxb.asPath - mkdir(dir: sourcesDir) - mkdir(dir: classesDir) - - xjc(destdir: sourcesDir, schema: schema, - package: "org.springframework.ws.samples.stockquote.schema") { - arg(value: "-wsdl") - produces(dir: sourcesDir, includes: "**/*.java") - } - - javac(destdir: classesDir, source: 1.6, target: 1.6, debug: true, - debugLevel: "lines,vars,source", - classpath: configurations.jaxb.asPath) { - src(path: sourcesDir) - include(name: "**/*.java") - include(name: "*.java") - } - - copy(todir: classesDir) { - fileset(dir: sourcesDir, erroronmissingdir: false) { - exclude(name: "**/*.java") - } - } - } - } -} - -task runServer(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.stockquote.Driver" - standardInput = System.in - classpath = sourceSets.main.runtimeClasspath -} - -dependencies { - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - compile("org.springframework.ws:spring-ws-support:$springWsVersion") - compile(files(genJaxb.classesDir).builtBy(genJaxb)) - - runtime("log4j:log4j:1.2.16") - - jaxb "com.sun.xml.bind:jaxb-xjc:2.1.7" -} \ No newline at end of file diff --git a/stockquote/server/src/main/java/org/springframework/ws/samples/stockquote/Driver.java b/stockquote/server/src/main/java/org/springframework/ws/samples/stockquote/Driver.java deleted file mode 100644 index d938957..0000000 --- a/stockquote/server/src/main/java/org/springframework/ws/samples/stockquote/Driver.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2008 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. - */ - -package org.springframework.ws.samples.stockquote; - -import java.io.IOException; -import java.net.InetSocketAddress; - -import com.sun.net.httpserver.HttpServer; - -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.ws.samples.stockquote.ws.StockServiceConfiguration; -import org.springframework.ws.transport.http.WebServiceMessageReceiverHttpHandler; -import org.springframework.ws.transport.http.WsdlDefinitionHttpHandler; - -public class Driver { - - public static void main(String[] args) throws IOException { - AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext( - StockServiceConfiguration.class); - - HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), -1); - httpServer.createContext("/StockService", applicationContext.getBean( - WebServiceMessageReceiverHttpHandler.class)); - httpServer.createContext("/StockService.wsdl", applicationContext.getBean( - WsdlDefinitionHttpHandler.class)); - - httpServer.start(); - System.out.println(); - System.out.println("Press [Enter] to shut down..."); - System.in.read(); - httpServer.stop(0); - } - -} diff --git a/stockquote/server/src/main/java/org/springframework/ws/samples/stockquote/ws/StockService.java b/stockquote/server/src/main/java/org/springframework/ws/samples/stockquote/ws/StockService.java deleted file mode 100644 index 7f09ae4..0000000 --- a/stockquote/server/src/main/java/org/springframework/ws/samples/stockquote/ws/StockService.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2008 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. - */ - -package org.springframework.ws.samples.stockquote.ws; - -import java.util.GregorianCalendar; -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; - -import org.springframework.ws.samples.stockquote.schema.StockQuote; -import org.springframework.ws.samples.stockquote.schema.StockQuoteRequest; -import org.springframework.ws.samples.stockquote.schema.StockQuoteResponse; -import org.springframework.ws.server.endpoint.annotation.Endpoint; -import org.springframework.ws.server.endpoint.annotation.RequestPayload; -import org.springframework.ws.server.endpoint.annotation.ResponsePayload; -import org.springframework.ws.soap.addressing.server.annotation.Action; -import org.springframework.ws.soap.addressing.server.annotation.Address; - -@Endpoint -@Address("http://localhost:8080/StockService") // optional -public class StockService { - - private DatatypeFactory datatypeFactory; - - public StockService() throws DatatypeConfigurationException { - datatypeFactory = DatatypeFactory.newInstance(); - } - - @Action(value = "http://www.springframework.org/spring-ws/samples/stockquote/StockService/GetQuote", - output = "http://www.springframework.org/spring-ws/samples/stockquote/StockService/Quotes") - @ResponsePayload - public StockQuoteResponse getStockQuotes(@RequestPayload StockQuoteRequest request) { - StockQuoteResponse response = new StockQuoteResponse(); - - XMLGregorianCalendar now = datatypeFactory.newXMLGregorianCalendar(new GregorianCalendar()); - for (String symbol : request.getSymbol()) { - StockQuote quote = new StockQuote(); - quote.setSymbol(symbol); - quote.setDate(now); - if ("FABRIKAM".equals(symbol)) { - quote.setName("Fabrikam, Inc."); - quote.setLast(120.00); - quote.setChange(5.5); - } - else { - quote.setName("Contoso Corp."); - quote.setLast(50.07); - quote.setChange(1.15); - } - response.getStockQuote().add(quote); - } - - return response; - } - -} diff --git a/stockquote/server/src/main/java/org/springframework/ws/samples/stockquote/ws/StockServiceConfiguration.java b/stockquote/server/src/main/java/org/springframework/ws/samples/stockquote/ws/StockServiceConfiguration.java deleted file mode 100644 index 5d9f0dd..0000000 --- a/stockquote/server/src/main/java/org/springframework/ws/samples/stockquote/ws/StockServiceConfiguration.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.springframework.ws.samples.stockquote.ws; - -import java.util.Collections; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.ClassPathResource; -import org.springframework.ws.server.EndpointAdapter; -import org.springframework.ws.server.EndpointInterceptor; -import org.springframework.ws.server.EndpointMapping; -import org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter; -import org.springframework.ws.soap.addressing.server.AnnotationActionEndpointMapping; -import org.springframework.ws.soap.saaj.SaajSoapMessageFactory; -import org.springframework.ws.soap.server.SoapMessageDispatcher; -import org.springframework.ws.soap.server.endpoint.interceptor.SoapEnvelopeLoggingInterceptor; -import org.springframework.ws.transport.http.HttpUrlConnectionMessageSender; -import org.springframework.ws.transport.http.WebServiceMessageReceiverHttpHandler; -import org.springframework.ws.transport.http.WsdlDefinitionHttpHandler; -import org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition; - -/** - * @author Arjen Poutsma - */ -@Configuration -@ComponentScan("org.springframework.ws.samples.stockquote.ws") -public class StockServiceConfiguration { - - @Bean - public WebServiceMessageReceiverHttpHandler soapHandler() { - WebServiceMessageReceiverHttpHandler soapHandler = new WebServiceMessageReceiverHttpHandler(); - soapHandler.setMessageFactory(messageFactory()); - soapHandler.setMessageReceiver(messageReceiver()); - return soapHandler; - } - - @Bean - public SaajSoapMessageFactory messageFactory() { - return new SaajSoapMessageFactory(); - } - - @Bean - public SoapMessageDispatcher messageReceiver() { - SoapMessageDispatcher messageReceiver = new SoapMessageDispatcher(); - messageReceiver.setEndpointAdapters( - Collections.singletonList(endpointAdapter())); - messageReceiver.setEndpointMappings( - Collections.singletonList(endpointMapping())); - return messageReceiver; - } - - @Bean - public DefaultMethodEndpointAdapter endpointAdapter() { - return new DefaultMethodEndpointAdapter(); - } - - @Bean - public AnnotationActionEndpointMapping endpointMapping() { - AnnotationActionEndpointMapping endpointMapping = new AnnotationActionEndpointMapping(); - endpointMapping.setMessageSender(messageSender()); - endpointMapping.setPreInterceptors(new EndpointInterceptor[] { new SoapEnvelopeLoggingInterceptor()}); - return endpointMapping; - } - - @Bean - public HttpUrlConnectionMessageSender messageSender() { - return new HttpUrlConnectionMessageSender(); - } - - @Bean - public WsdlDefinitionHttpHandler wsdlHandler() { - return new WsdlDefinitionHttpHandler(wsdlDefinition()); - } - - @Bean - public SimpleWsdl11Definition wsdlDefinition() { - return new SimpleWsdl11Definition(new ClassPathResource("/org/springframework/ws/samples/stockquote/ws/stockquote.wsdl")); - } - - -} diff --git a/stockquote/server/src/main/resources/log4j.properties b/stockquote/server/src/main/resources/log4j.properties deleted file mode 100644 index 0f73a75..0000000 --- a/stockquote/server/src/main/resources/log4j.properties +++ /dev/null @@ -1,7 +0,0 @@ -log4j.rootLogger=WARN, stdout -log4j.logger.org.springframework.ws=DEBUG -log4j.logger.org.springframework.xml=DEBUG - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n \ No newline at end of file diff --git a/stockquote/server/src/main/resources/org/springframework/ws/samples/stockquote/ws/stockquote.wsdl b/stockquote/server/src/main/resources/org/springframework/ws/samples/stockquote/ws/stockquote.wsdl deleted file mode 100644 index 81d404e..0000000 --- a/stockquote/server/src/main/resources/org/springframework/ws/samples/stockquote/ws/stockquote.wsdl +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/stockquote/settings.gradle b/stockquote/settings.gradle deleted file mode 100644 index b3428de..0000000 --- a/stockquote/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ - -include "server", "client:jax-ws", "client:spring-ws" diff --git a/tutorial/build.gradle b/tutorial/build.gradle deleted file mode 100644 index 7055368..0000000 --- a/tutorial/build.gradle +++ /dev/null @@ -1,47 +0,0 @@ -buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.9' - } -} - -apply plugin: 'eclipse' -apply plugin: 'idea' -apply plugin: 'war' -apply plugin: 'tomcat' - -ext.springVersion = '4.0.2.RELEASE' -ext.springWsVersion = '2.2.0.BUILD-SNAPSHOT' -ext.tomcatVersion = '7.0.42' - -dependencies { - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - compile("org.jdom:jdom:2.0.1") - runtime("jaxen:jaxen:1.1.4") - runtime("log4j:log4j:1.2.16") - runtime("org.apache.ws.xmlschema:xmlschema-core:2.1.0") - runtime("wsdl4j:wsdl4j:1.6.1") - - providedCompile("javax.servlet:javax.servlet-api:3.0.1") - - testCompile("junit:junit:4.10") - testCompile("org.easymock:easymock:3.1") - - tomcat("org.apache.tomcat.embed:tomcat-embed-core:$tomcatVersion", - "org.apache.tomcat.embed:tomcat-embed-logging-juli:$tomcatVersion") - tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:$tomcatVersion") { - exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj' - } -} - -repositories { - maven { url 'https://repo.spring.io/libs-release' } - maven { url 'https://repo.spring.io/libs-snapshot' } -} - -task wrapper(type: Wrapper) { - gradleVersion = '1.8' -} \ No newline at end of file diff --git a/tutorial/gradle/wrapper/gradle-wrapper.jar b/tutorial/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 667288a..0000000 Binary files a/tutorial/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/tutorial/gradle/wrapper/gradle-wrapper.properties b/tutorial/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index ee84d1f..0000000 --- a/tutorial/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Thu Nov 07 14:43:21 CET 2013 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-bin.zip diff --git a/tutorial/gradlew b/tutorial/gradlew deleted file mode 100755 index 91a7e26..0000000 --- a/tutorial/gradlew +++ /dev/null @@ -1,164 +0,0 @@ -#!/usr/bin/env bash - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn ( ) { - echo "$*" -} - -die ( ) { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; -esac - -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -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 -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -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 - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" - -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/tutorial/gradlew.bat b/tutorial/gradlew.bat deleted file mode 100644 index 8a0b282..0000000 --- a/tutorial/gradlew.bat +++ /dev/null @@ -1,90 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/tutorial/pom.xml b/tutorial/pom.xml new file mode 100644 index 0000000..6c051da --- /dev/null +++ b/tutorial/pom.xml @@ -0,0 +1,143 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.3.1.RELEASE + + + + org.springframework.ws + tutorial + 0.0.1-SNAPSHOT + Spring Web Services Samples - Tutorial + Demo project for Spring Web Services + + + 1.8 + 1.1.4 + 2.0.1 + 2.10.6 + 1.2.16 + ${project.basedir}/target/generated-sources/axis + ${project.basedir}/target/classes + ${project.basedir}/../airline.wsdl + 1.6.1 + 2.1.0 + + + + + + org.springframework.boot + spring-boot-starter-web-services + + + + org.jdom + jdom + ${jdom.version} + + + + jaxen + jaxen + ${jaxen.version} + + + + org.apache.ws.xmlschema + xmlschema-core + ${xmlschema.version} + runtime + + + + wsdl4j + wsdl4j + ${wsdl4j.version} + runtime + + + + org.springframework.ws + spring-ws-support + + + + org.springframework + spring-test + test + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.codehaus.mojo + jaxb2-maven-plugin + 2.5.0 + + + xjc + + xjc + + + + + ${project.basedir}/src/main/resources/hr.xsd + org.springframework.ws.samples.tutorial.schema + 2.1 + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.1 + + + add-source + process-sources + + add-source + + + + target/generated-sources/xjc + + + + + + + + + + + + diff --git a/tutorial/src/main/java/com/mycompany/hr/HrApplication.java b/tutorial/src/main/java/com/mycompany/hr/HrApplication.java new file mode 100644 index 0000000..bb79949 --- /dev/null +++ b/tutorial/src/main/java/com/mycompany/hr/HrApplication.java @@ -0,0 +1,12 @@ +package com.mycompany.hr; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class HrApplication { + + public static void main(String[] args) { + SpringApplication.run(HrApplication.class, args); + } +} diff --git a/tutorial/src/main/java/com/mycompany/hr/config/HRConfiguration.java b/tutorial/src/main/java/com/mycompany/hr/config/HRConfiguration.java index 941b1fd..1927da0 100644 --- a/tutorial/src/main/java/com/mycompany/hr/config/HRConfiguration.java +++ b/tutorial/src/main/java/com/mycompany/hr/config/HRConfiguration.java @@ -1,24 +1,20 @@ package com.mycompany.hr.config; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.ws.config.annotation.EnableWs; import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition; import org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection; /** * @author Arjen Poutsma */ -@EnableWs @Configuration -@ComponentScan("com.mycompany.hr") public class HRConfiguration { @Bean public DefaultWsdl11Definition holiday() { + DefaultWsdl11Definition definition = new DefaultWsdl11Definition(); definition.setPortTypeName("HumanResource"); definition.setLocationUri("/holidayService/"); @@ -29,12 +25,9 @@ public class HRConfiguration { @Bean public CommonsXsdSchemaCollection holidayXsd() { - CommonsXsdSchemaCollection collection = - new CommonsXsdSchemaCollection(new Resource[] { new ClassPathResource("/hr.xsd")}); + + CommonsXsdSchemaCollection collection = new CommonsXsdSchemaCollection(new ClassPathResource("/hr.xsd")); collection.setInline(true); return collection; } - - - } diff --git a/tutorial/src/main/java/com/mycompany/hr/config/HRServletInitializer.java b/tutorial/src/main/java/com/mycompany/hr/config/HRServletInitializer.java deleted file mode 100644 index 54b9bcb..0000000 --- a/tutorial/src/main/java/com/mycompany/hr/config/HRServletInitializer.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.mycompany.hr.config; - -import org.springframework.ws.transport.http.support.AbstractAnnotationConfigMessageDispatcherServletInitializer; - -/** - * @author Arjen Poutsma - */ -public class HRServletInitializer - extends AbstractAnnotationConfigMessageDispatcherServletInitializer { - - @Override - protected Class[] getRootConfigClasses() { - return null; - } - - @Override - protected Class[] getServletConfigClasses() { - return new Class[]{HRConfiguration.class}; - } - - @Override - public boolean isTransformWsdlLocations() { - return true; - } - - @Override - protected String[] getServletMappings() { - return new String[]{"/*"}; - } -} diff --git a/tutorial/src/main/java/com/mycompany/hr/ws/HolidayEndpoint.java b/tutorial/src/main/java/com/mycompany/hr/ws/HolidayEndpoint.java index 8442a8a..00e5442 100644 --- a/tutorial/src/main/java/com/mycompany/hr/ws/HolidayEndpoint.java +++ b/tutorial/src/main/java/com/mycompany/hr/ws/HolidayEndpoint.java @@ -18,21 +18,19 @@ package com.mycompany.hr.ws; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.Arrays; import java.util.Date; +import org.jdom2.Element; +import org.jdom2.Namespace; +import org.jdom2.filter.Filters; +import org.jdom2.xpath.XPathExpression; +import org.jdom2.xpath.XPathFactory; 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; /** * This endpoint handles holiday requests. It uses a combination of JDOM and XPath to extract interesting pieces of XML @@ -43,46 +41,51 @@ import org.jdom2.xpath.XPathFactory; @Endpoint public class HolidayEndpoint { - private static final String NAMESPACE_URI = "http://mycompany.com/hr/schemas"; + private static final String NAMESPACE_URI = "http://mycompany.com/hr/schemas"; - private XPathExpression startDateExpression; + private XPathExpression startDateExpression; - private XPathExpression endDateExpression; + private XPathExpression endDateExpression; - private XPathExpression firstNameExpression; + private XPathExpression firstNameExpression; - private XPathExpression lastNameExpression; + private XPathExpression lastNameExpression; - private HumanResourceService humanResourceService; + 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); - } + @Autowired + public HolidayEndpoint(HumanResourceService humanResourceService) { - @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(); + 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); + } - humanResourceService.bookHoliday(startDate, endDate, name); - } + @PayloadRoot(namespace = NAMESPACE_URI, localPart = "HolidayRequest") + public void handleHolidayRequest(@RequestPayload Element holidayRequest) throws Exception { - private Date parseDate(XPathExpression 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 + "]"); - } - } + 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 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 + "]"); + } + } } diff --git a/tutorial/src/test/java/com/mycompany/hr/ws/HolidayEndpointTest.java b/tutorial/src/test/java/com/mycompany/hr/ws/HolidayEndpointTest.java index 7471790..d1fcca6 100644 --- a/tutorial/src/test/java/com/mycompany/hr/ws/HolidayEndpointTest.java +++ b/tutorial/src/test/java/com/mycompany/hr/ws/HolidayEndpointTest.java @@ -16,56 +16,58 @@ package com.mycompany.hr.ws; +import static org.mockito.Mockito.*; + import java.io.InputStream; import java.util.Calendar; -import com.mycompany.hr.service.HumanResourceService; import org.jdom2.Document; import org.jdom2.input.SAXBuilder; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.easymock.EasyMock.*; +import com.mycompany.hr.service.HumanResourceService; public class HolidayEndpointTest { - private Document holidayRequest; + private Document holidayRequest; - private HolidayEndpoint endpoint; + private HolidayEndpoint endpoint; - private HumanResourceService serviceMock; + private HumanResourceService serviceMock; - private Calendar startCalendar; + private Calendar startCalendar; - private Calendar endCalendar; + private Calendar endCalendar; - @Before - public void setUp() throws Exception { - serviceMock = createMock(HumanResourceService.class); - SAXBuilder builder = new SAXBuilder(); - InputStream is = getClass().getResourceAsStream("holidayRequest.xml"); - try { - holidayRequest = builder.build(is); - } - finally { - is.close(); - } - endpoint = new HolidayEndpoint(serviceMock); - startCalendar = Calendar.getInstance(); - startCalendar.clear(); - startCalendar.set(2006, Calendar.JULY, 3); - endCalendar = Calendar.getInstance(); - endCalendar.clear(); - endCalendar.set(2006, Calendar.JULY, 7); - } + @BeforeEach + public void setUp() throws Exception { - @Test - public void handleHolidayRequest() throws Exception { - serviceMock.bookHoliday(startCalendar.getTime(), endCalendar.getTime(), "John Doe"); - replay(serviceMock); - endpoint.handleHolidayRequest(holidayRequest.getRootElement()); - verify(serviceMock); - } + serviceMock = mock(HumanResourceService.class); + SAXBuilder builder = new SAXBuilder(); + InputStream is = getClass().getResourceAsStream("holidayRequest.xml"); + try { + holidayRequest = builder.build(is); + } finally { + is.close(); + } + endpoint = new HolidayEndpoint(serviceMock); + startCalendar = Calendar.getInstance(); + startCalendar.clear(); + startCalendar.set(2006, Calendar.JULY, 3); + endCalendar = Calendar.getInstance(); + endCalendar.clear(); + endCalendar.set(2006, Calendar.JULY, 7); + } + @Test + public void handleHolidayRequest() throws Exception { + + serviceMock.bookHoliday(startCalendar.getTime(), endCalendar.getTime(), "John Doe"); + + endpoint.handleHolidayRequest(holidayRequest.getRootElement()); + + verify(serviceMock); + } } diff --git a/weather/build.gradle b/weather/build.gradle deleted file mode 100644 index ea0379b..0000000 --- a/weather/build.gradle +++ /dev/null @@ -1,65 +0,0 @@ -configurations { - jaxb -} - -ext.springVersion = '3.2.4.RELEASE' -ext.springWsVersion = '2.1.4.RELEASE' - -apply plugin: 'java' -apply plugin: 'eclipse' -apply plugin: 'idea' - -repositories { - maven { url 'https://repo.spring.io/libs-release' } -} - -task genJaxb { - ext.sourcesDir = "${buildDir}/generated-sources/jaxb" - ext.classesDir = "${buildDir}/classes/jaxb" - ext.schema = "http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl" - - outputs.dir classesDir - - doLast() { - project.ant { - taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask", - classpath: configurations.jaxb.asPath - mkdir(dir: sourcesDir) - mkdir(dir: classesDir) - - xjc(destdir: sourcesDir, schema: schema, - package: "org.springframework.ws.samples.weather") { - arg(value: "-wsdl") - produces(dir: sourcesDir, includes: "**/*.java") - } - - javac(destdir: classesDir, source: 1.6, target: 1.6, debug: true, - debugLevel: "lines,vars,source", - classpath: configurations.jaxb.asPath) { - src(path: sourcesDir) - include(name: "**/*.java") - include(name: "*.java") - } - - copy(todir: classesDir) { - fileset(dir: sourcesDir, erroronmissingdir: false) { - exclude(name: "**/*.java") - } - } - } - } -} - -dependencies { - compile("org.springframework.ws:spring-ws-core:$springWsVersion") - compile(files(genJaxb.classesDir).builtBy(genJaxb)) - - runtime("log4j:log4j:1.2.16") - - jaxb "com.sun.xml.bind:jaxb-xjc:2.1.7" -} - -task runClient(dependsOn: 'classes', type:JavaExec) { - main = "org.springframework.ws.samples.weather.WeatherClient" - classpath = sourceSets.main.runtimeClasspath -} diff --git a/weather/pom.xml b/weather/pom.xml new file mode 100644 index 0000000..c6368a4 --- /dev/null +++ b/weather/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + + + org.springframework.ws + spring-ws-samples + 1.0.0.BUILD-SNAPSHOT + ../ + + + org.springframework.ws + weather-client-spring-ws + 0.0.1-SNAPSHOT + Spring Web Services Samples - Weather - Client - Spring WS + Demo project for Spring Web Services + + + 1.8 + ${project.basedir}/target/generated-sources/xjc + ${project.basedir}/target/classes + ${project.basedir}/../../server/src/main/resources + http://wsf.cdyne.com/WeatherWS/Weather.asmx?wsdl + + + + + + org.springframework.ws + spring-ws-core + + + + + + + + + + org.jvnet.jaxb2.maven2 + maven-jaxb2-plugin + 0.14.0 + + + + generate + + + + + WSDL + + + ${wsdl} + + + org.springframework.ws.samples.weather + true + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.1 + + + add-source + process-sources + + add-source + + + + ${sourcesDir} + + + + + + + + + + diff --git a/weather/src/main/java/org/springframework/ws/samples/weather/WeatherClient.java b/weather/src/main/java/org/springframework/ws/samples/weather/WeatherClient.java index 3b5c5b7..d7f4d48 100644 --- a/weather/src/main/java/org/springframework/ws/samples/weather/WeatherClient.java +++ b/weather/src/main/java/org/springframework/ws/samples/weather/WeatherClient.java @@ -26,39 +26,35 @@ import org.springframework.ws.soap.client.core.SoapActionCallback; public class WeatherClient extends WebServiceGatewaySupport { public GetCityForecastByZIPResponse getCityForecastByZip(String zipCode) { + GetCityForecastByZIP request = new GetCityForecastByZIP(); request.setZIP(zipCode); System.out.println(); System.out.println("Requesting forecast for " + zipCode); - GetCityForecastByZIPResponse response = - (GetCityForecastByZIPResponse) getWebServiceTemplate() - .marshalSendAndReceive(request, new SoapActionCallback( - "https://ws.cdyne.com/WeatherWS/GetCityForecastByZIP")); + GetCityForecastByZIPResponse response = (GetCityForecastByZIPResponse) getWebServiceTemplate() + .marshalSendAndReceive(request, new SoapActionCallback("http://ws.cdyne.com/WeatherWS/GetCityForecastByZIP")); return response; } public void printResponse(GetCityForecastByZIPResponse response) { - ForecastReturn forecastReturn = response.getGetCityForecastByZIPResult(); + ForecastReturn forecastReturn = response.getGetCityForecastByZIPResult(); if (forecastReturn.isSuccess()) { System.out.println(); - System.out.println("Forecast for " + forecastReturn.getCity() + ", " + - forecastReturn.getState()); + System.out.println("Forecast for " + forecastReturn.getCity() + ", " + forecastReturn.getState()); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); for (Forecast forecast : forecastReturn.getForecastResult().getForecast()) { - System.out.print(format - .format(forecast.getDate().toGregorianCalendar().getTime())); + System.out.print(format.format(forecast.getDate().toGregorianCalendar().getTime())); System.out.print(" "); System.out.print(forecast.getDesciption()); System.out.print(" "); Temp temperature = forecast.getTemperatures(); - System.out.print(temperature.getMorningLow() + "\u00b0-" + - temperature.getDaytimeHigh() + "\u00b0 "); + System.out.print(temperature.getMorningLow() + "\u00b0-" + temperature.getDaytimeHigh() + "\u00b0 "); System.out.println(); } } else { @@ -68,8 +64,8 @@ public class WeatherClient extends WebServiceGatewaySupport { } public static void main(String[] args) { - ApplicationContext context = - new AnnotationConfigApplicationContext(WeatherConfiguration.class); + + ApplicationContext context = new AnnotationConfigApplicationContext(WeatherConfiguration.class); WeatherClient client = context.getBean(WeatherClient.class); String zipCode = "94304"; @@ -79,7 +75,5 @@ public class WeatherClient extends WebServiceGatewaySupport { GetCityForecastByZIPResponse response = client.getCityForecastByZip(zipCode); client.printResponse(response); - } - } diff --git a/weather/src/main/java/org/springframework/ws/samples/weather/WeatherConfiguration.java b/weather/src/main/java/org/springframework/ws/samples/weather/WeatherConfiguration.java index 2453adf..0c4cda8 100644 --- a/weather/src/main/java/org/springframework/ws/samples/weather/WeatherConfiguration.java +++ b/weather/src/main/java/org/springframework/ws/samples/weather/WeatherConfiguration.java @@ -25,18 +25,21 @@ public class WeatherConfiguration { @Bean public Jaxb2Marshaller marshaller() { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath("org.springframework.ws.samples.weather"); return marshaller; } @Bean - public WeatherClient weatherClient() { + public WeatherClient weatherClient(Jaxb2Marshaller marshaller) { + WeatherClient client = new WeatherClient(); client.setDefaultUri("http://wsf.cdyne.com/WeatherWS/Weather.asmx"); - Jaxb2Marshaller marshaller = marshaller(); + client.setMarshaller(marshaller); client.setUnmarshaller(marshaller); + return client; } diff --git a/weather/src/main/resources/log4j.properties b/weather/src/main/resources/log4j.properties deleted file mode 100644 index f50b419..0000000 --- a/weather/src/main/resources/log4j.properties +++ /dev/null @@ -1,5 +0,0 @@ -log4j.rootLogger=WARN, stdout - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n \ No newline at end of file