Refactoring samples

Restructuring the samples repository
Add more docker support
Add acceptance tests for the apps
Adding sensor average processor sample
Remove aggregate samples
This commit is contained in:
Soby Chacko
2018-03-08 16:06:52 -05:00
parent b2cecb08bc
commit e94de0d535
368 changed files with 4428 additions and 3470 deletions

View File

@@ -0,0 +1 @@
../.mvn

View File

@@ -0,0 +1,10 @@
=== Samples Acceptance Tests
This is an accptance test module for the samples in this repo.
The tests launch the Spring Cloud Stream samples as stand alone Spring Boot applications and then verify their correctness.
By default, these tests are not run as part of the normal build, as they are mainly intended for continuous integration testing with ongoing changes in the framework.
In order to run the tests, we recommend to run the script `./runAcceptanceTest.sh` in this directory.
The script will launch all the middleware and other components in docker containers first.
Then it builds the applications and run them.

View File

@@ -0,0 +1,54 @@
version: '3'
volumes:
data-volume: {}
services:
mysql:
image: mariadb
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: pwd
MYSQL_DATABASE: sample_mysql_db
volumes:
- data-volume:/var/lib/mysql
kafka:
image: wurstmeister/kafka
ports:
- "9092:9092"
environment:
- KAFKA_ADVERTISED_HOST_NAME=127.0.0.1
- KAFKA_ADVERTISED_PORT=9092
- KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181
depends_on:
- zookeeper
zookeeper:
image: wurstmeister/zookeeper
ports:
- "2181:2181"
environment:
- KAFKA_ADVERTISED_HOST_NAME=zookeeper
rabbitmq:
image: rabbitmq:management
ports:
- 5672:5672
- 15672:15672
# used for multi Kafka cluster testing
kafka2:
image: wurstmeister/kafka
container_name: kafka-2
ports:
- "9093:9092"
environment:
- KAFKA_ADVERTISED_HOST_NAME=127.0.0.1
- KAFKA_ADVERTISED_PORT=9092
- KAFKA_ZOOKEEPER_CONNECT=zookeeper2:2181
depends_on:
- zookeeper2
zookeeper2:
image: wurstmeister/zookeeper
ports:
- "2182:2181"
environment:
- KAFKA_ADVERTISED_HOST_NAME=zookeeper2

226
samples-acceptance-tests/mvnw vendored Executable file
View File

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

145
samples-acceptance-tests/mvnw.cmd vendored Normal file
View File

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

View File

@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>samples-acceptance-tests</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>samples-acceptance-tests</name>
<description>Collection of Spring Cloud Stream Aggregate Samples</description>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
</parent>
<properties>
<maven.test.skip>true</maven.test.skip>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>1.1.9</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,166 @@
#!/bin/bash
pushd () {
command pushd "$@" > /dev/null
}
popd () {
command popd "$@" > /dev/null
}
function prepare_jdbc_source_with_kafka_and_rabbit_binders() {
pushd ../source-samples/jdbc-source
./mvnw clean package -DskipTests
cp target/jdbc-source-*-SNAPSHOT.jar /tmp/jdbc-source-kafka-sample.jar
./mvnw clean package -P rabbit-binder -DskipTests
cp target/jdbc-source-*-SNAPSHOT.jar /tmp/jdbc-source-rabbit-sample.jar
popd
}
function prepare_jdbc_sink_with_kafka_and_rabbit_binders() {
pushd ../sink-samples/jdbc-sink
./mvnw clean package -DskipTests
cp target/jdbc-sink-*-SNAPSHOT.jar /tmp/jdbc-sink-kafka-sample.jar
./mvnw clean package -P rabbit-binder -DskipTests
cp target/jdbc-sink-*-SNAPSHOT.jar /tmp/jdbc-sink-rabbit-sample.jar
popd
}
function prepare_dynamic_source_with_kafka_and_rabbit_binders() {
pushd ../source-samples/dynamic-destination-source
./mvnw clean package -DskipTests
cp target/dynamic-destination-source-*-SNAPSHOT.jar /tmp/dynamic-destination-source-kafka-sample.jar
./mvnw clean package -P rabbit-binder -DskipTests
cp target/dynamic-destination-source-*-SNAPSHOT.jar /tmp/dynamic-destination-source-rabbit-sample.jar
popd
}
function prepare_multi_binder_with_kafka_rabbit() {
pushd ../multibinder-samples/multibinder-kafka-rabbit
./mvnw clean package -DskipTests
cp target/multibinder-kafka-rabbit-*-SNAPSHOT.jar /tmp/multibinder-kafka-rabbit-sample.jar
popd
}
function prepare_multi_binder_with_two_kafka_clusters() {
pushd ../multibinder-samples/multibinder-two-kafka-clusters
./mvnw clean package -DskipTests
cp target/multibinder-two-kafka-clusters-*-SNAPSHOT.jar /tmp/multibinder-two-kafka-clusters-sample.jar
popd
}
function prepare_kafka_streams_word_count() {
pushd ../kafka-streams-samples/kafka-streams-word-count
./mvnw clean package -DskipTests
cp target/kafka-streams-word-count-*-SNAPSHOT.jar /tmp/kafka-streams-word-count-sample.jar
popd
}
function prepare_streamlistener_basic_with_kafka_rabbit_binders() {
pushd ../processor-samples/streamlistener-basic
./mvnw clean package -DskipTests
cp target/streamlistener-basic-*-SNAPSHOT.jar /tmp/streamlistener-basic-kafka-sample.jar
./mvnw clean package -P rabbit-binder -DskipTests
cp target/streamlistener-basic-*-SNAPSHOT.jar /tmp/streamlistener-basic-rabbit-sample.jar
popd
}
function prepare_reactive_processor_with_kafka_rabbit_binders() {
pushd ../processor-samples/reactive-processor
./mvnw clean package -DskipTests
cp target/reactive-processor-*-SNAPSHOT.jar /tmp/reactive-processor-kafka-sample.jar
./mvnw clean package -P rabbit-binder -DskipTests
cp target/reactive-processor-*-SNAPSHOT.jar /tmp/reactive-processor-rabbit-sample.jar
popd
}
function prepare_sensor_average_reactive_with_kafka_rabbit_binders() {
pushd ../processor-samples/sensor-average-reactive
./mvnw clean package -DskipTests
cp target/sensor-average-reactive-*-SNAPSHOT.jar /tmp/sensor-average-reactive-kafka-sample.jar
./mvnw clean package -P rabbit-binder -DskipTests
cp target/sensor-average-reactive-*-SNAPSHOT.jar /tmp/sensor-average-reactive-rabbit-sample.jar
popd
}
#Main script starting
echo "Starting Kafka broker as a Docker container..."
docker-compose up -d
prepare_jdbc_source_with_kafka_and_rabbit_binders
prepare_jdbc_sink_with_kafka_and_rabbit_binders
prepare_dynamic_source_with_kafka_and_rabbit_binders
prepare_multi_binder_with_kafka_rabbit
prepare_multi_binder_with_two_kafka_clusters
prepare_kafka_streams_word_count
prepare_streamlistener_basic_with_kafka_rabbit_binders
prepare_reactive_processor_with_kafka_rabbit_binders
prepare_sensor_average_reactive_with_kafka_rabbit_binders
echo "Running tests"
./mvnw clean package -Dmaven.test.skip=false
docker-compose down
# Post cleanup
rm /tmp/jdbc-source-kafka-sample.jar
rm /tmp/jdbc-source-rabbit-sample.jar
rm /tmp/jdbc-sink-kafka-sample.jar
rm /tmp/jdbc-sink-rabbit-sample.jar
rm /tmp/dynamic-destination-source-kafka-sample.jar
rm /tmp/dynamic-destination-source-rabbit-sample.jar
rm /tmp/multibinder-kafka-rabbit-sample.jar
rm /tmp/multibinder-two-kafka-clusters-sample.jar
rm /tmp/kafka-streams-word-count-sample.jar
rm /tmp/streamlistener-basic-kafka-sample.jar
rm /tmp/streamlistener-basic-rabbit-sample.jar
rm /tmp/reactive-processor-kafka-sample.jar
rm /tmp/reactive-processor-rabbit-sample.jar
rm /tmp/sensor-average-reactive-kafka-sample.jar
rm /tmp/sensor-average-reactive-rabbit-sample.jar
rm /tmp/foobar.log

View File

@@ -0,0 +1,352 @@
/*
* Copyright 2018 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 sample.acceptance.tests;
import org.junit.After;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import org.springframework.util.StringUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import javax.sql.DataSource;
import java.util.stream.Stream;
import static org.junit.Assert.fail;
/**
* Do not run these tests as part of an IDE build or individually.
* These are acceptance tests for the spring cloud stream samples.
* The recommended way to run these tests are using the runAcceptanceTests.sh script in this module.
* More about running that script can be found in the README.
*
* @author Soby Chacko
*/
public class SampleAcceptanceTests {
private static final Logger logger = LoggerFactory.getLogger(SampleAcceptanceTests.class);
private Process process;
private Process startTheApp(String[] cmds) throws Exception {
ProcessBuilder pb = new ProcessBuilder(cmds);
process = pb.start();
return process;
}
@After
public void stopTheApp() {
if (process != null) {
process.destroyForcibly();
}
}
private void waitForExpectedMessagesToAppearInTheLogs(String app, String... textToSearch) {
boolean foundAssertionStrings = waitForLogEntry(app, textToSearch);
if (!foundAssertionStrings) {
fail("Did not find the text looking for after waiting for 30 seconds");
}
}
private void waitForAppToStartFully(String app, String message) {
boolean started = waitForLogEntry(app, message);
if (!started) {
fail("process didn't start in 30 seconds");
}
}
@Test
public void testJdbcSourceSampleKafka() throws Exception {
process = startTheApp(new String[]{
"java", "-jar", "/tmp/jdbc-source-kafka-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"
});
waitForAppToStartFully("JDBC Source", "Started SampleJdbcSource in");
waitForExpectedMessagesToAppearInTheLogs("JDBC Source",
"Data received...[{id=1, name=Bob, tag=null}, {id=2, name=Jane, tag=null}, {id=3, name=John, tag=null}]");
}
@Test
public void testJdbcSourceSampleRabbit() throws Exception {
process = startTheApp(new String[]{
"java", "-jar", "/tmp/jdbc-source-rabbit-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"
});
waitForAppToStartFully("JDBC Source", "Started SampleJdbcSource in");
waitForExpectedMessagesToAppearInTheLogs("JDBC Source",
"Data received...[{id=1, name=Bob, tag=null}, {id=2, name=Jane, tag=null}, {id=3, name=John, tag=null}]");
}
@Test
public void testJdbcSinkSampleKafka() throws Exception {
process = startTheApp(new String[]{
"java", "-jar", "/tmp/jdbc-sink-kafka-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"
});
waitForAppToStartFully("JDBC Sink", "Started SampleJdbcSink in");
verifyJdbcSink();
}
@Test
public void testJdbcSinkSampleRabbit() throws Exception {
process = startTheApp(new String[]{
"java", "-jar", "/tmp/jdbc-sink-rabbit-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"
});
waitForAppToStartFully("JDBC Sink", "Started SampleJdbcSink in");
verifyJdbcSink();
}
private void verifyJdbcSink() {
JdbcTemplate db;
DataSource dataSource = new SingleConnectionDataSource("jdbc:mariadb://localhost:3306/sample_mysql_db",
"root", "pwd", false);
db = new JdbcTemplate(dataSource);
long timeout = System.currentTimeMillis() + (30 * 1000);
boolean exists = false;
while (!exists && System.currentTimeMillis() < timeout) {
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e.getMessage(), e);
}
Integer count = db.queryForObject("select count(*) from test", Integer.class);
if (count > 0) {
exists = true;
}
}
if (!exists) {
fail("No records found in database!");
}
}
@Test
public void testDynamicSourceSampleKafka() throws Exception {
process = startTheApp(new String[]{
"java", "-jar", "/tmp/dynamic-destination-source-kafka-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"
});
verifyDynamicSourceApp();
}
@Test
public void testDynamicSourceSampleRabbit() throws Exception {
process = startTheApp(new String[]{
"java", "-jar", "/tmp/dynamic-destination-source-rabbit-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"
});
verifyDynamicSourceApp();
}
private void verifyDynamicSourceApp() {
waitForAppToStartFully("Dynamic Source", "Started SourceApplication in");
RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject(
"http://localhost:8080",
"{\"id\":\"customerId-1\",\"bill-pay\":\"100\"}", String.class);
waitForExpectedMessagesToAppearInTheLogs("Dynamic Source",
"Data received from customer-1...{\"id\":\"customerId-1\",\"bill-pay\":\"100\"}");
restTemplate.postForObject(
"http://localhost:8080",
"{\"id\":\"customerId-2\",\"bill-pay2\":\"200\"}", String.class);
waitForExpectedMessagesToAppearInTheLogs("Dynamic Source",
"Data received from customer-2...{\"id\":\"customerId-2\",\"bill-pay2\":\"200\"}");
}
@Test
public void testMultiBinderKafkaInputRabbitOutput() throws Exception {
startTheApp(new String[]{"java", "-jar", "/tmp/multibinder-kafka-rabbit-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"});
waitForAppToStartFully("Multibinder", "Started MultibinderApplication in");
waitForExpectedMessagesToAppearInTheLogs("Multibinder", "Data received...bar", "Data received...foo");
}
@Test
public void testMultiBinderTwoKafkaClusters() throws Exception {
startTheApp(new String[]{"java", "-jar", "/tmp/multibinder-two-kafka-clusters-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*",
"--kafkaBroker1=localhost:9092", "--zk1=localhost:2181",
"--kafkaBroker2=localhost:9093", "--zk2=localhost:2182"});
waitForAppToStartFully("Multibinder 2 Kafka Clusters", "Started MultibinderApplication in");
waitForExpectedMessagesToAppearInTheLogs("Multibinder 2 Kafka Clusters", "Data received...bar", "Data received...foo");
}
@Test
public void testStreamListenerBasicSampleKafka() throws Exception {
process = startTheApp(new String[]{
"java", "-jar", "/tmp/streamlistener-basic-kafka-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"
});
waitForAppToStartFully("Streamlistener basic", "Started TypeConversionApplication in");
waitForExpectedMessagesToAppearInTheLogs("Streamlistener basic",
"At the Source", "Sending value: {\"value\":\"hi\"}", "At the transformer",
"Received value hi of type class demo.Bar",
"Transforming the value to HI and with the type class demo.Bar",
"At the Sink",
"Received transformed message HI of type class demo.Foo");
}
@Test
public void testStreamListenerBasicSampleRabbit() throws Exception {
process = startTheApp(new String[]{
"java", "-jar", "/tmp/streamlistener-basic-rabbit-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"
});
waitForAppToStartFully("Streamlistener basic", "Started TypeConversionApplication in");
waitForExpectedMessagesToAppearInTheLogs("Streamlistener basic",
"At the Source", "Sending value: {\"value\":\"hi\"}", "At the transformer",
"Received value hi of type class demo.Bar",
"Transforming the value to HI and with the type class demo.Bar",
"At the Sink",
"Received transformed message HI of type class demo.Foo");
}
@Test
public void testReactiveProcessorSampleKafka() throws Exception {
process = startTheApp(new String[]{
"java", "-jar", "/tmp/reactive-processor-kafka-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"
});
waitForAppToStartFully("Reactive processor", "Started ReactiveProcessorApplication in");
waitForExpectedMessagesToAppearInTheLogs("Reactive processor",
"Data received: foobarfoobarfoo",
"Data received: barfoobarfoobar");
}
@Test
public void testReactiveProcessorSampleRabbit() throws Exception {
process = startTheApp(new String[]{
"java", "-jar", "/tmp/reactive-processor-rabbit-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"
});
waitForAppToStartFully("Reactive processor", "Started ReactiveProcessorApplication in");
waitForExpectedMessagesToAppearInTheLogs("Reactive processor",
"Data received: foobarfoobarfoo",
"Data received: barfoobarfoobar");
}
@Test
public void testSensorAverageReactiveSampleKafka() throws Exception {
process = startTheApp(new String[]{
"java", "-jar", "/tmp/sensor-average-reactive-kafka-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"
});
waitForAppToStartFully("Sensor average", "Started SensorAverageProcessorApplication in");
waitForExpectedMessagesToAppearInTheLogs("Sensor average",
"Data received: {\"id\":100100,\"average\":",
"Data received: {\"id\":100200,\"average\":", "Data received: {\"id\":100300,\"average\":");
}
@Test
public void testSensorAverageReactiveSampleRabbit() throws Exception {
process = startTheApp(new String[]{
"java", "-jar", "/tmp/sensor-average-reactive-rabbit-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*"
});
waitForAppToStartFully("Sensor average", "Started SensorAverageProcessorApplication in");
waitForExpectedMessagesToAppearInTheLogs("Sensor average",
"Data received: {\"id\":100100,\"average\":",
"Data received: {\"id\":100200,\"average\":", "Data received: {\"id\":100300,\"average\":");
}
@Test
public void testKafkaStreamsWordCount() throws Exception {
startTheApp(new String[]{"java", "-jar", "/tmp/kafka-streams-word-count-sample.jar", "--logging.file=/tmp/foobar.log",
"--management.endpoints.web.exposure.include=*",
"--spring.cloud.stream.kafka.streams.timeWindow.length=60000"});
waitForAppToStartFully("Kafka Streams WordCount", "Started KafkaStreamsWordCountApplication in");
waitForExpectedMessagesToAppearInTheLogs("Kafka Streams WordCount",
"Data received...{\"word\":\"foo\",\"count\":1,",
"Data received...{\"word\":\"bar\",\"count\":1,",
"Data received...{\"word\":\"foobar\",\"count\":1,",
"Data received...{\"word\":\"baz\",\"count\":1,",
"Data received...{\"word\":\"fox\",\"count\":1,");
}
boolean waitForLogEntry(String app, String... entries) {
logger.info("Looking for '" + StringUtils.arrayToCommaDelimitedString(entries) + "' in logfile for " + app);
long timeout = System.currentTimeMillis() + (30 * 1000);
boolean exists = false;
while (!exists && System.currentTimeMillis() < timeout) {
try {
Thread.sleep(7 * 1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e.getMessage(), e);
}
if (!exists) {
logger.info("Polling to get log file. Remaining poll time = "
+ (timeout - System.currentTimeMillis() + " ms."));
String log = getLog("http://localhost:8080/actuator");
if (log != null) {
if (Stream.of(entries).allMatch(s -> log.contains(s))) {
exists = true;
}
}
}
}
if (exists) {
logger.info("Matched all '" + StringUtils.arrayToCommaDelimitedString(entries) + "' in logfile for app " + app);
} else {
logger.error("ERROR: Couldn't find all '" + StringUtils.arrayToCommaDelimitedString(entries) + "' in logfile for " + app);
}
return exists;
}
String getLog(String url) {
RestTemplate restTemplate = new RestTemplate();
String logFileUrl = String.format("%s/logfile", url);
String log = null;
try {
log = restTemplate.getForObject(logFileUrl, String.class);
if (log == null) {
logger.info("Unable to retrieve logfile from '" + logFileUrl);
} else {
logger.info("Retrieved logfile from '" + logFileUrl);
}
} catch (HttpClientErrorException e) {
logger.info("Failed to access logfile from '" + logFileUrl + "' due to : " + e.getMessage());
} catch (Exception e) {
logger.warn("Error while trying to access logfile from '" + logFileUrl + "' due to : " + e);
}
return log;
}
}