Added checkstyle

This commit is contained in:
Marcin Grzejszczak
2019-02-05 15:21:41 +01:00
parent 7867256b90
commit 004e83b1e8
45 changed files with 848 additions and 620 deletions

14
.editorconfig Normal file
View File

@@ -0,0 +1,14 @@
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
[*]
indent_style = tab
indent_size = 4
end_of_line = lf
insert_final_newline = true
[*.yml]
indent_style = space
indent_size = 2

110
.mvn/wrapper/MavenWrapperDownloader.java vendored Executable file
View File

@@ -0,0 +1,110 @@
/*
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.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: : " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

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

Binary file not shown.

2
.mvn/wrapper/maven-wrapper.properties vendored Normal file → Executable file
View File

@@ -1 +1 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip

View File

@@ -1,66 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<settings> <settings>
<servers> <servers>
<server> <server>
<id>repo.spring.io</id> <id>repo.spring.io</id>
<username>${env.CI_DEPLOY_USERNAME}</username> <username>${env.CI_DEPLOY_USERNAME}</username>
<password>${env.CI_DEPLOY_PASSWORD}</password> <password>${env.CI_DEPLOY_PASSWORD}</password>
</server> </server>
</servers> </servers>
<profiles> <profiles>
<profile> <profile>
<!-- <!--
N.B. this profile is only here to support users and IDEs that do not use Maven 3.3. N.B. this profile is only here to support users and IDEs that do not use Maven 3.3.
It isn't needed on the command line if you use the wrapper script (mvnw) or if you use It isn't needed on the command line if you use the wrapper script (mvnw) or if you use
a native Maven with the right version. Eclipse users should points their Maven tooling to a native Maven with the right version. Eclipse users should points their Maven tooling to
this settings file, or copy the profile into their ~/.m2/settings.xml. this settings file, or copy the profile into their ~/.m2/settings.xml.
--> -->
<id>spring</id> <id>spring</id>
<activation><activeByDefault>true</activeByDefault></activation> <activation>
<repositories> <activeByDefault>true</activeByDefault>
<repository> </activation>
<id>spring-snapshots</id> <repositories>
<name>Spring Snapshots</name> <repository>
<url>http://repo.spring.io/libs-snapshot-local</url> <id>spring-snapshots</id>
<snapshots> <name>Spring Snapshots</name>
<enabled>true</enabled> <url>http://repo.spring.io/libs-snapshot-local</url>
</snapshots> <snapshots>
</repository> <enabled>true</enabled>
<repository> </snapshots>
<id>spring-milestones</id> </repository>
<name>Spring Milestones</name> <repository>
<url>http://repo.spring.io/libs-milestone-local</url> <id>spring-milestones</id>
<snapshots> <name>Spring Milestones</name>
<enabled>false</enabled> <url>http://repo.spring.io/libs-milestone-local</url>
</snapshots> <snapshots>
</repository> <enabled>false</enabled>
<repository> </snapshots>
<id>spring-releases</id> </repository>
<name>Spring Releases</name> <repository>
<url>http://repo.spring.io/release</url> <id>spring-releases</id>
<snapshots> <name>Spring Releases</name>
<enabled>false</enabled> <url>http://repo.spring.io/release</url>
</snapshots> <snapshots>
</repository> <enabled>false</enabled>
</repositories> </snapshots>
<pluginRepositories> </repository>
<pluginRepository> </repositories>
<id>spring-snapshots</id> <pluginRepositories>
<name>Spring Snapshots</name> <pluginRepository>
<url>http://repo.spring.io/libs-snapshot-local</url> <id>spring-snapshots</id>
<snapshots> <name>Spring Snapshots</name>
<enabled>true</enabled> <url>http://repo.spring.io/libs-snapshot-local</url>
</snapshots> <snapshots>
</pluginRepository> <enabled>true</enabled>
<pluginRepository> </snapshots>
<id>spring-milestones</id> </pluginRepository>
<name>Spring Milestones</name> <pluginRepository>
<url>http://repo.spring.io/libs-milestone-local</url> <id>spring-milestones</id>
<snapshots> <name>Spring Milestones</name>
<enabled>false</enabled> <url>http://repo.spring.io/libs-milestone-local</url>
</snapshots> <snapshots>
</pluginRepository> <enabled>false</enabled>
</pluginRepositories> </snapshots>
</profile> </pluginRepository>
</profiles> </pluginRepositories>
</profile>
</profiles>
</settings> </settings>

0
.springformat Normal file
View File

View File

@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <project 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"> xmlns="http://maven.apache.org/POM/4.0.0"
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> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
@@ -16,14 +17,14 @@
<main.basedir>${basedir}/..</main.basedir> <main.basedir>${basedir}/..</main.basedir>
<docs.whitelisted.branches>1.0.x,1.1.x</docs.whitelisted.branches> <docs.whitelisted.branches>1.0.x,1.1.x</docs.whitelisted.branches>
</properties> </properties>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<artifactId>maven-deploy-plugin</artifactId> <artifactId>maven-deploy-plugin</artifactId>
<configuration> <configuration>
<skip>true</skip> <skip>true</skip>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<profiles> <profiles>

177
mvnw vendored
View File

@@ -54,38 +54,16 @@ case "`uname`" in
CYGWIN*) cygwin=true ;; CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;; MINGW*) mingw=true;;
Darwin*) darwin=true Darwin*) darwin=true
# # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# Look for the Apple JDKs first to preserve the existing behaviour, and then look # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
# for the new JDKs provided by Oracle. if [ -z "$JAVA_HOME" ]; then
# if [ -x "/usr/libexec/java_home" ]; then
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then export JAVA_HOME="`/usr/libexec/java_home`"
# else
# Apple JDKs export JAVA_HOME="/Library/Java/Home"
# fi
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home fi
fi ;;
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
#
# Oracle JDKs
#
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
#
# Apple JDKs
#
export JAVA_HOME=`/usr/libexec/java_home`
fi
;;
esac esac
if [ -z "$JAVA_HOME" ] ; then if [ -z "$JAVA_HOME" ] ; then
@@ -130,7 +108,7 @@ if $cygwin ; then
CLASSPATH=`cygpath --path --unix "$CLASSPATH"` CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi fi
# For Migwn, ensure paths are in UNIX format before anything is touched # For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then if $mingw ; then
[ -n "$M2_HOME" ] && [ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`" M2_HOME="`(cd "$M2_HOME"; pwd)`"
@@ -184,27 +162,28 @@ fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# 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"`
fi
# traverses directory structure from process work directory to filesystem root # traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory # first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() { find_maven_basedir() {
local basedir=$(pwd)
local wdir=$(pwd) if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir basedir=$wdir
break break
fi fi
wdir=$(cd "$wdir/.."; pwd) # workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done done
echo "${basedir}" echo "${basedir}"
} }
@@ -216,38 +195,92 @@ concat_lines() {
fi fi
} }
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} 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" MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# Provide a "standardized" way to retrieve the CLI args that will # For Cygwin, switch paths to Windows format before running java
# work with both Windows and non-Windows executions. if $cygwin; then
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" [ -n "$M2_HOME" ] &&
export MAVEN_CMD_LINE_ARGS 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 WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
echo "Running version check"
VERSION=$( sed '\!<parent!,\!</parent!d' `dirname $0`/pom.xml | grep '<version' | head -1 | sed -e 's/.*<version>//' -e 's!</version>.*$!!' )
echo "The found version is [${VERSION}]"
if echo $VERSION | egrep -q 'M|RC'; then
echo Activating \"milestone\" profile for version=\"$VERSION\"
echo $MAVEN_ARGS | grep -q milestone || MAVEN_ARGS="$MAVEN_ARGS -Pmilestone"
else
echo Deactivating \"milestone\" profile for version=\"$VERSION\"
echo $MAVEN_ARGS | grep -q milestone && MAVEN_ARGS=$(echo $MAVEN_ARGS | sed -e 's/-Pmilestone//')
fi
if echo $VERSION | egrep -q 'RELEASE'; then
echo Activating \"central\" profile for version=\"$VERSION\"
echo $MAVEN_ARGS | grep -q milestone || MAVEN_ARGS="$MAVEN_ARGS -Pcentral"
else
echo Deactivating \"central\" profile for version=\"$VERSION\"
echo $MAVEN_ARGS | grep -q central && MAVEN_ARGS=$(echo $MAVEN_ARGS | sed -e 's/-Pcentral//')
fi
exec "$JAVACMD" \ exec "$JAVACMD" \
$MAVEN_OPTS \ $MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} ${MAVEN_ARGS} "$@" ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

306
mvnw.cmd vendored Normal file → Executable file
View File

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

26
pom.xml
View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 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> <modelVersion>4.0.0</modelVersion>
@@ -20,6 +21,12 @@
<main.basedir>${basedir}</main.basedir> <main.basedir>${basedir}</main.basedir>
<spring-cloud-netflix.version>2.1.1.BUILD-SNAPSHOT</spring-cloud-netflix.version> <spring-cloud-netflix.version>2.1.1.BUILD-SNAPSHOT</spring-cloud-netflix.version>
<spring-cloud-commons.version>2.1.1.BUILD-SNAPSHOT</spring-cloud-commons.version> <spring-cloud-commons.version>2.1.1.BUILD-SNAPSHOT</spring-cloud-commons.version>
<maven-checkstyle-plugin.failsOnError>true</maven-checkstyle-plugin.failsOnError>
<maven-checkstyle-plugin.failsOnViolation>true
</maven-checkstyle-plugin.failsOnViolation>
<maven-checkstyle-plugin.includeTestSourceDirectory>true
</maven-checkstyle-plugin.includeTestSourceDirectory>
</properties> </properties>
<scm> <scm>
@@ -53,9 +60,26 @@
<target>1.8</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
<plugin>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
</plugin>
</plugins> </plugins>
</build> </build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</reporting>
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>

View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 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> <modelVersion>4.0.0</modelVersion>

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -30,6 +30,7 @@ import org.cloudfoundry.reactor.tokenprovider.PasswordGrantTokenProvider;
import org.cloudfoundry.reactor.uaa.ReactorUaaClient; import org.cloudfoundry.reactor.uaa.ReactorUaaClient;
import org.cloudfoundry.routing.RoutingClient; import org.cloudfoundry.routing.RoutingClient;
import org.cloudfoundry.uaa.UaaClient; import org.cloudfoundry.uaa.UaaClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@@ -46,9 +47,12 @@ import org.springframework.context.annotation.Lazy;
* @author Scott Frederick * @author Scott Frederick
*/ */
@Configuration @Configuration
@ConditionalOnProperty(prefix = "spring.cloud.cloudfoundry", name = {"username", "password"}) @ConditionalOnProperty(prefix = "spring.cloud.cloudfoundry", name = { "username",
@ConditionalOnClass(name = {"reactor.core.publisher.Flux", "org.cloudfoundry.operations.DefaultCloudFoundryOperations", "password" })
"org.cloudfoundry.reactor.client.ReactorCloudFoundryClient", "org.reactivestreams.Publisher"}) @ConditionalOnClass(name = { "reactor.core.publisher.Flux",
"org.cloudfoundry.operations.DefaultCloudFoundryOperations",
"org.cloudfoundry.reactor.client.ReactorCloudFoundryClient",
"org.reactivestreams.Publisher" })
@EnableConfigurationProperties(CloudFoundryProperties.class) @EnableConfigurationProperties(CloudFoundryProperties.class)
public class CloudFoundryClientAutoConfiguration { public class CloudFoundryClientAutoConfiguration {
@@ -61,67 +65,59 @@ public class CloudFoundryClientAutoConfiguration {
@Bean @Bean
@Lazy @Lazy
@ConditionalOnMissingBean @ConditionalOnMissingBean
public CloudFoundryService cloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { public CloudFoundryService cloudFoundryService(
CloudFoundryOperations cloudFoundryOperations) {
return new CloudFoundryService(cloudFoundryOperations); return new CloudFoundryService(cloudFoundryOperations);
} }
@Bean @Bean
@Lazy @Lazy
@ConditionalOnMissingBean @ConditionalOnMissingBean
public DefaultCloudFoundryOperations cloudFoundryOperations(CloudFoundryClient cloudFoundryClient, public DefaultCloudFoundryOperations cloudFoundryOperations(
DopplerClient dopplerClient, CloudFoundryClient cloudFoundryClient, DopplerClient dopplerClient,
RoutingClient routingClient, RoutingClient routingClient, UaaClient uaaClient) {
UaaClient uaaClient) {
String organization = this.cloudFoundryProperties.getOrg(); String organization = this.cloudFoundryProperties.getOrg();
String space = this.cloudFoundryProperties.getSpace(); String space = this.cloudFoundryProperties.getSpace();
return DefaultCloudFoundryOperations return DefaultCloudFoundryOperations.builder()
.builder() .cloudFoundryClient(cloudFoundryClient).dopplerClient(dopplerClient)
.cloudFoundryClient(cloudFoundryClient) .routingClient(routingClient).uaaClient(uaaClient)
.dopplerClient(dopplerClient) .organization(organization).space(space).build();
.routingClient(routingClient)
.uaaClient(uaaClient)
.organization(organization)
.space(space)
.build();
}
@Bean
@Lazy
@ConditionalOnMissingBean
public ReactorCloudFoundryClient cloudFoundryClient(ConnectionContext connectionContext, TokenProvider tokenProvider) {
return ReactorCloudFoundryClient.builder()
.connectionContext(connectionContext)
.tokenProvider(tokenProvider)
.build();
} }
@Bean @Bean
@Lazy @Lazy
@ConditionalOnMissingBean @ConditionalOnMissingBean
public DopplerClient dopplerClient(ConnectionContext connectionContext, TokenProvider tokenProvider) { public ReactorCloudFoundryClient cloudFoundryClient(
return ReactorDopplerClient.builder() ConnectionContext connectionContext, TokenProvider tokenProvider) {
.connectionContext(connectionContext) return ReactorCloudFoundryClient.builder().connectionContext(connectionContext)
.tokenProvider(tokenProvider) .tokenProvider(tokenProvider).build();
.build();
} }
@Bean @Bean
@Lazy @Lazy
@ConditionalOnMissingBean @ConditionalOnMissingBean
public RoutingClient routingClient(ConnectionContext connectionContext, TokenProvider tokenProvider) { public DopplerClient dopplerClient(ConnectionContext connectionContext,
return ReactorRoutingClient.builder() TokenProvider tokenProvider) {
.connectionContext(connectionContext) return ReactorDopplerClient.builder().connectionContext(connectionContext)
.tokenProvider(tokenProvider) .tokenProvider(tokenProvider).build();
.build();
} }
@Bean @Bean
@Lazy @Lazy
@ConditionalOnMissingBean @ConditionalOnMissingBean
public ReactorUaaClient uaaClient(ConnectionContext connectionContext, TokenProvider tokenProvider) { public RoutingClient routingClient(ConnectionContext connectionContext,
return ReactorUaaClient.builder() TokenProvider tokenProvider) {
.connectionContext(connectionContext) return ReactorRoutingClient.builder().connectionContext(connectionContext)
.tokenProvider(tokenProvider) .tokenProvider(tokenProvider).build();
.build(); }
@Bean
@Lazy
@ConditionalOnMissingBean
public ReactorUaaClient uaaClient(ConnectionContext connectionContext,
TokenProvider tokenProvider) {
return ReactorUaaClient.builder().connectionContext(connectionContext)
.tokenProvider(tokenProvider).build();
} }
@Bean @Bean
@@ -131,10 +127,8 @@ public class CloudFoundryClientAutoConfiguration {
String apiHost = this.cloudFoundryProperties.getUrl(); String apiHost = this.cloudFoundryProperties.getUrl();
Boolean skipSslValidation = this.cloudFoundryProperties.isSkipSslValidation(); Boolean skipSslValidation = this.cloudFoundryProperties.isSkipSslValidation();
return DefaultConnectionContext.builder() return DefaultConnectionContext.builder().apiHost(apiHost)
.apiHost(apiHost) .skipSslValidation(skipSslValidation).build();
.skipSslValidation(skipSslValidation)
.build();
} }
@Bean @Bean
@@ -143,11 +137,8 @@ public class CloudFoundryClientAutoConfiguration {
public PasswordGrantTokenProvider tokenProvider() { public PasswordGrantTokenProvider tokenProvider() {
String username = this.cloudFoundryProperties.getUsername(); String username = this.cloudFoundryProperties.getUsername();
String password = this.cloudFoundryProperties.getPassword(); String password = this.cloudFoundryProperties.getPassword();
return PasswordGrantTokenProvider.builder() return PasswordGrantTokenProvider.builder().password(password).username(username)
.password(password)
.username(username)
.build(); .build();
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,17 +16,17 @@
package org.springframework.cloud.cloudfoundry; package org.springframework.cloud.cloudfoundry;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** /**
* Configuration properties for a connection to a Cloud Foundry platform. * Configuration properties for a connection to a Cloud Foundry platform.
* *
@@ -69,6 +69,10 @@ public class CloudFoundryProperties implements InitializingBean {
return this.url; return this.url;
} }
public void setUrl(String cloudControllerUrl) {
this.url = cloudControllerUrl;
}
private String safeUrl(String t) { private String safeUrl(String t) {
String input = t.trim().toLowerCase(); String input = t.trim().toLowerCase();
Pattern p = Pattern.compile("(http(s)?://)(.*)"); Pattern p = Pattern.compile("(http(s)?://)(.*)");
@@ -82,10 +86,6 @@ public class CloudFoundryProperties implements InitializingBean {
return t; return t;
} }
public void setUrl(String cloudControllerUrl) {
this.url = cloudControllerUrl;
}
public String getUsername() { public String getUsername() {
return this.username; return this.username;
} }
@@ -119,7 +119,7 @@ public class CloudFoundryProperties implements InitializingBean {
} }
public boolean isSkipSslValidation() { public boolean isSkipSslValidation() {
return skipSslValidation; return this.skipSslValidation;
} }
public boolean getSkipSslValidation() { public boolean getSkipSslValidation() {
@@ -146,6 +146,8 @@ public class CloudFoundryProperties implements InitializingBean {
vals.put("url", getUrl()); vals.put("url", getUrl());
vals.put("username", getUsername()); vals.put("username", getUsername());
vals.put("password", getPassword()); vals.put("password", getPassword());
vals.forEach((key, value) -> Assert.hasText(value, String.format("'%s' must be provided", key))); vals.forEach((key, value) -> Assert.hasText(value,
String.format("'%s' must be provided", key)));
} }
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.springframework.cloud.cloudfoundry; package org.springframework.cloud.cloudfoundry;
import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.CloudFoundryOperations;
import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.ApplicationDetail;
import org.cloudfoundry.operations.applications.GetApplicationRequest; import org.cloudfoundry.operations.applications.GetApplicationRequest;
@@ -38,15 +37,17 @@ public class CloudFoundryService {
this.cloudFoundryOperations = cloudFoundryOperations; this.cloudFoundryOperations = cloudFoundryOperations;
} }
public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(
GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); String serviceId) {
return this.cloudFoundryOperations GetApplicationRequest applicationRequest = GetApplicationRequest.builder()
.applications() .name(serviceId).build();
.get(applicationRequest) return this.cloudFoundryOperations.applications().get(applicationRequest)
.flatMapMany(applicationDetail -> { .flatMapMany(applicationDetail -> {
Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) Flux<InstanceDetail> ids = Flux
.fromStream(applicationDetail.getInstanceDetails().stream())
.filter(id -> id.getState().equalsIgnoreCase("RUNNING")); .filter(id -> id.getState().equalsIgnoreCase("RUNNING"));
Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); Flux<ApplicationDetail> generate = Flux
.generate(sink -> sink.next(applicationDetail));
return generate.zipWith(ids); return generate.zipWith(ids);
}); });
} }

View File

@@ -1,3 +1,2 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.cloudfoundry.CloudFoundryClientAutoConfiguration org.springframework.cloud.cloudfoundry.CloudFoundryClientAutoConfiguration

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -27,6 +27,7 @@ import org.cloudfoundry.reactor.uaa.ReactorUaaClient;
import org.cloudfoundry.routing.RoutingClient; import org.cloudfoundry.routing.RoutingClient;
import org.junit.Assume; import org.junit.Assume;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext; import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.test.context.runner.ApplicationContextRunner;
@@ -35,13 +36,12 @@ import static org.assertj.core.api.Assertions.assertThat;
public class CloudFoundryClientAutoConfigurationTest { public class CloudFoundryClientAutoConfigurationTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final static String[] SPRING_CLOUD_PROPERTIES = {
.withConfiguration(AutoConfigurations.of(CloudFoundryClientAutoConfiguration.class)); "spring.cloud.cloudfoundry.username", "spring.cloud.cloudfoundry.password", };
private final static String SPRING_CLOUD_PROPERTIES[] = { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
"spring.cloud.cloudfoundry.username", .withConfiguration(
"spring.cloud.cloudfoundry.password", AutoConfigurations.of(CloudFoundryClientAutoConfiguration.class));
};
private static boolean requiredPropertiesSet() { private static boolean requiredPropertiesSet() {
for (String k : SPRING_CLOUD_PROPERTIES) { for (String k : SPRING_CLOUD_PROPERTIES) {
@@ -53,23 +53,19 @@ public class CloudFoundryClientAutoConfigurationTest {
} }
private static String envVarFromProperty(String propertyName) { private static String envVarFromProperty(String propertyName) {
return propertyName return propertyName.replaceAll("\\.", "_").toUpperCase();
.replaceAll("\\.", "_")
.toUpperCase();
} }
@Test @Test
public void autoConfiguresBeansWithAllProperties() { public void autoConfiguresBeansWithAllProperties() {
this.contextRunner this.contextRunner.withPropertyValues("spring.cloud.cloudfoundry.username=user",
.withPropertyValues( "spring.cloud.cloudfoundry.password=secret",
"spring.cloud.cloudfoundry.username=user", "spring.cloud.cloudfoundry.org=myorg",
"spring.cloud.cloudfoundry.password=secret", "spring.cloud.cloudfoundry.space=myspace").run((context) -> {
"spring.cloud.cloudfoundry.org=myorg",
"spring.cloud.cloudfoundry.space=myspace")
.run((context) -> {
assertCloudFoundryClientBeansPresent(context); assertCloudFoundryClientBeansPresent(context);
DefaultCloudFoundryOperations operations = context.getBean(DefaultCloudFoundryOperations.class); DefaultCloudFoundryOperations operations = context
.getBean(DefaultCloudFoundryOperations.class);
assertThat(operations.getOrganization()).isEqualTo("myorg"); assertThat(operations.getOrganization()).isEqualTo("myorg");
assertThat(operations.getSpace()).isEqualTo("myspace"); assertThat(operations.getSpace()).isEqualTo("myspace");
}); });
@@ -77,14 +73,12 @@ public class CloudFoundryClientAutoConfigurationTest {
@Test @Test
public void autoConfiguresBeansWithMinimalProperties() { public void autoConfiguresBeansWithMinimalProperties() {
this.contextRunner this.contextRunner.withPropertyValues("spring.cloud.cloudfoundry.username=user",
.withPropertyValues( "spring.cloud.cloudfoundry.password=secret").run((context) -> {
"spring.cloud.cloudfoundry.username=user",
"spring.cloud.cloudfoundry.password=secret")
.run((context) -> {
assertCloudFoundryClientBeansPresent(context); assertCloudFoundryClientBeansPresent(context);
DefaultCloudFoundryOperations operations = context.getBean(DefaultCloudFoundryOperations.class); DefaultCloudFoundryOperations operations = context
.getBean(DefaultCloudFoundryOperations.class);
assertThat(operations.getOrganization()).isNullOrEmpty(); assertThat(operations.getOrganization()).isNullOrEmpty();
assertThat(operations.getSpace()).isNullOrEmpty(); assertThat(operations.getSpace()).isNullOrEmpty();
}); });
@@ -94,23 +88,21 @@ public class CloudFoundryClientAutoConfigurationTest {
public void organizationsRetrievedWithUserProvidedProperties() { public void organizationsRetrievedWithUserProvidedProperties() {
Assume.assumeTrue(requiredPropertiesSet()); Assume.assumeTrue(requiredPropertiesSet());
this.contextRunner this.contextRunner.run((context) -> {
.run((context) -> { assertCloudFoundryClientBeansPresent(context);
assertCloudFoundryClientBeansPresent(context); CloudFoundryOperations operations = context
CloudFoundryOperations operations = context.getBean(CloudFoundryOperations.class); .getBean(CloudFoundryOperations.class);
OrganizationSummary summary = operations OrganizationSummary summary = operations.organizations().list().blockFirst();
.organizations()
.list()
.blockFirst();
assertThat(summary).isNotNull(); assertThat(summary).isNotNull();
assertThat(summary.getId()).isNotEmpty(); assertThat(summary.getId()).isNotEmpty();
assertThat(summary.getName()).isNotEmpty(); assertThat(summary.getName()).isNotEmpty();
}); });
} }
private void assertCloudFoundryClientBeansPresent(AssertableApplicationContext context) { private void assertCloudFoundryClientBeansPresent(
AssertableApplicationContext context) {
assertThat(context).hasSingleBean(ReactorCloudFoundryClient.class); assertThat(context).hasSingleBean(ReactorCloudFoundryClient.class);
assertThat(context).hasSingleBean(DefaultCloudFoundryOperations.class); assertThat(context).hasSingleBean(DefaultCloudFoundryOperations.class);
assertThat(context).hasSingleBean(DefaultConnectionContext.class); assertThat(context).hasSingleBean(DefaultConnectionContext.class);
@@ -119,4 +111,5 @@ public class CloudFoundryClientAutoConfigurationTest {
assertThat(context).hasSingleBean(PasswordGrantTokenProvider.class); assertThat(context).hasSingleBean(PasswordGrantTokenProvider.class);
assertThat(context).hasSingleBean(ReactorUaaClient.class); assertThat(context).hasSingleBean(ReactorUaaClient.class);
} }
}
}

View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 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> <modelVersion>4.0.0</modelVersion>
<parent> <parent>

View File

@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <project 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"> xmlns="http://maven.apache.org/POM/4.0.0"
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> <modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-cloudfoundry-discovery</artifactId> <artifactId>spring-cloud-cloudfoundry-discovery</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
@@ -51,4 +52,4 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -42,14 +42,16 @@ import org.springframework.cloud.cloudfoundry.CloudFoundryService;
public class CloudFoundryDiscoveryClient implements DiscoveryClient { public class CloudFoundryDiscoveryClient implements DiscoveryClient {
private final CloudFoundryService cloudFoundryService; private final CloudFoundryService cloudFoundryService;
private final CloudFoundryOperations cloudFoundryOperations; private final CloudFoundryOperations cloudFoundryOperations;
private final CloudFoundryDiscoveryProperties properties; private final CloudFoundryDiscoveryProperties properties;
private final String description = "Cloud Foundry " + DiscoveryClient.class.getName() + " implementation"; private final String description = "Cloud Foundry " + DiscoveryClient.class.getName()
+ " implementation";
CloudFoundryDiscoveryClient(CloudFoundryOperations cloudFoundryOperations, CloudFoundryDiscoveryClient(CloudFoundryOperations cloudFoundryOperations,
CloudFoundryService svc, CloudFoundryService svc, CloudFoundryDiscoveryProperties properties) {
CloudFoundryDiscoveryProperties properties) {
this.cloudFoundryService = svc; this.cloudFoundryService = svc;
this.cloudFoundryOperations = cloudFoundryOperations; this.cloudFoundryOperations = cloudFoundryOperations;
this.properties = properties; this.properties = properties;
@@ -62,37 +64,30 @@ public class CloudFoundryDiscoveryClient implements DiscoveryClient {
@Override @Override
public List<ServiceInstance> getInstances(String serviceId) { public List<ServiceInstance> getInstances(String serviceId) {
return cloudFoundryService return this.cloudFoundryService.getApplicationInstances(serviceId).map(tuple -> {
.getApplicationInstances(serviceId) ApplicationDetail applicationDetail = tuple.getT1();
.map(tuple -> { InstanceDetail instanceDetail = tuple.getT2();
ApplicationDetail applicationDetail = tuple.getT1();
InstanceDetail instanceDetail = tuple.getT2();
String applicationId = applicationDetail.getId(); String applicationId = applicationDetail.getId();
String applicationIndex = instanceDetail.getIndex(); String applicationIndex = instanceDetail.getIndex();
String name = applicationDetail.getName(); String name = applicationDetail.getName();
String url = applicationDetail.getUrls().size() > 0 ? applicationDetail.getUrls().get(0) : null; String url = applicationDetail.getUrls().size() > 0
boolean secure = (url + "").toLowerCase().startsWith("https"); ? applicationDetail.getUrls().get(0) : null;
boolean secure = (url + "").toLowerCase().startsWith("https");
HashMap<String, String> metadata = new HashMap<>(); HashMap<String, String> metadata = new HashMap<>();
metadata.put("applicationId", applicationId); metadata.put("applicationId", applicationId);
metadata.put("instanceId", applicationIndex); metadata.put("instanceId", applicationIndex);
return (ServiceInstance) new DefaultServiceInstance(name, url, 80, secure, metadata); return (ServiceInstance) new DefaultServiceInstance(name, url, 80, secure,
}) metadata);
.collectList() }).collectList().blockOptional().orElse(new ArrayList<>());
.blockOptional()
.orElse(new ArrayList<>());
} }
@Override @Override
public List<String> getServices() { public List<String> getServices() {
return this.cloudFoundryOperations return this.cloudFoundryOperations.applications().list()
.applications() .map(ApplicationSummary::getName).collectList().blockOptional()
.list()
.map(ApplicationSummary::getName)
.collectList()
.blockOptional()
.orElse(new ArrayList<>()); .orElse(new ArrayList<>());
} }
@@ -100,4 +95,5 @@ public class CloudFoundryDiscoveryClient implements DiscoveryClient {
public int getOrder() { public int getOrder() {
return this.properties.getOrder(); return this.properties.getOrder();
} }
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -44,7 +44,9 @@ public class CloudFoundryDiscoveryClientConfiguration {
} }
@Bean @Bean
public CloudFoundryHeartbeatSender cloudFoundryHeartbeatSender(CloudFoundryDiscoveryClient client) { public CloudFoundryHeartbeatSender cloudFoundryHeartbeatSender(
CloudFoundryDiscoveryClient client) {
return new CloudFoundryHeartbeatSender(client); return new CloudFoundryHeartbeatSender(client);
} }
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -21,7 +21,7 @@ import org.springframework.core.Ordered;
/** /**
* Properties used for configuring the CloudFoundry implementation of * Properties used for configuring the CloudFoundry implementation of
* {@link org.springframework.cloud.client.discovery.DiscoveryClient} * {@link org.springframework.cloud.client.discovery.DiscoveryClient}.
* *
* @author Olga Maciaszek-Sharma * @author Olga Maciaszek-Sharma
*/ */
@@ -37,4 +37,5 @@ public class CloudFoundryDiscoveryClientProperties {
public void setOrder(int order) { public void setOrder(int order) {
this.order = order; this.order = order;
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -41,12 +41,13 @@ public class CloudFoundryDiscoveryProperties {
private int defaultServerPort = 80; private int defaultServerPort = 80;
/** /**
* Order of the discovery client used by `CompositeDiscoveryClient` for sorting available clients. * Order of the discovery client used by `CompositeDiscoveryClient` for sorting
* available clients.
*/ */
private int order = 0; private int order = 0;
public boolean isEnabled() { public boolean isEnabled() {
return enabled; return this.enabled;
} }
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
@@ -62,7 +63,7 @@ public class CloudFoundryDiscoveryProperties {
} }
public int getDefaultServerPort() { public int getDefaultServerPort() {
return defaultServerPort; return this.defaultServerPort;
} }
public void setDefaultServerPort(int defaultServerPort) { public void setDefaultServerPort(int defaultServerPort) {
@@ -70,7 +71,7 @@ public class CloudFoundryDiscoveryProperties {
} }
public int getOrder() { public int getOrder() {
return order; return this.order;
} }
public void setOrder(int order) { public void setOrder(int order) {
@@ -79,11 +80,10 @@ public class CloudFoundryDiscoveryProperties {
@Override @Override
public String toString() { public String toString() {
return "CloudFoundryDiscoveryProperties{" + return "CloudFoundryDiscoveryProperties{" + "enabled=" + this.enabled
"enabled=" + enabled + + ", heartbeatFrequency=" + this.heartbeatFrequency
", heartbeatFrequency=" + heartbeatFrequency + + ", defaultServerPort=" + this.defaultServerPort + ", order="
", defaultServerPort=" + defaultServerPort + + this.order + '}';
", order=" + order +
'}';
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2015 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -35,6 +35,7 @@ import org.springframework.stereotype.Component;
public class CloudFoundryHeartbeatSender implements ApplicationEventPublisherAware { public class CloudFoundryHeartbeatSender implements ApplicationEventPublisherAware {
private final CloudFoundryDiscoveryClient client; private final CloudFoundryDiscoveryClient client;
private ApplicationEventPublisher publisher; private ApplicationEventPublisher publisher;
public CloudFoundryHeartbeatSender(CloudFoundryDiscoveryClient client) { public CloudFoundryHeartbeatSender(CloudFoundryDiscoveryClient client) {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -18,6 +18,9 @@ package org.springframework.cloud.cloudfoundry.discovery;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ServerList;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.CloudFoundryService;
import org.springframework.cloud.netflix.ribbon.RibbonClientName; import org.springframework.cloud.netflix.ribbon.RibbonClientName;
@@ -25,9 +28,6 @@ import org.springframework.cloud.netflix.ribbon.RibbonUtils;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ServerList;
/** /**
* @author Josh Long * @author Josh Long
*/ */
@@ -47,8 +47,9 @@ public class CloudFoundryRibbonClientConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public ServerList<?> ribbonServerList(CloudFoundryService svc, IClientConfig config, public ServerList<?> ribbonServerList(CloudFoundryService svc, IClientConfig config,
CloudFoundryDiscoveryProperties properties) { CloudFoundryDiscoveryProperties properties) {
CloudFoundryServerList cloudFoundryServerList = new CloudFoundryServerList(svc, properties); CloudFoundryServerList cloudFoundryServerList = new CloudFoundryServerList(svc,
properties);
cloudFoundryServerList.initWithNiwsConfig(config); cloudFoundryServerList.initWithNiwsConfig(config);
return cloudFoundryServerList; return cloudFoundryServerList;
} }
@@ -58,4 +59,4 @@ public class CloudFoundryRibbonClientConfiguration {
RibbonUtils.initializeRibbonDefaults(this.serviceId); RibbonUtils.initializeRibbonDefaults(this.serviceId);
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -54,4 +54,5 @@ public class CloudFoundryServer extends Server {
public MetaInfo getMetaInfo() { public MetaInfo getMetaInfo() {
return this.metaInfo; return this.metaInfo;
} }
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -19,24 +19,28 @@ package org.springframework.cloud.cloudfoundry.discovery;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractServerList;
import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.CloudFoundryService;
import org.springframework.cloud.netflix.ribbon.RibbonProperties; import org.springframework.cloud.netflix.ribbon.RibbonProperties;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractServerList;
/** /**
* @author Josh Long * @author Josh Long
*/ */
public class CloudFoundryServerList extends AbstractServerList<CloudFoundryServer> { public class CloudFoundryServerList extends AbstractServerList<CloudFoundryServer> {
private final CloudFoundryService cloudFoundryService; private final CloudFoundryService cloudFoundryService;
private final CloudFoundryDiscoveryProperties properties; private final CloudFoundryDiscoveryProperties properties;
private IClientConfig clientConfig; private IClientConfig clientConfig;
private String serviceId; private String serviceId;
CloudFoundryServerList(CloudFoundryService svc, CloudFoundryDiscoveryProperties properties) { CloudFoundryServerList(CloudFoundryService svc,
CloudFoundryDiscoveryProperties properties) {
this.cloudFoundryService = svc; this.cloudFoundryService = svc;
this.properties = properties; this.properties = properties;
} }
@@ -60,7 +64,7 @@ public class CloudFoundryServerList extends AbstractServerList<CloudFoundryServe
private List<CloudFoundryServer> cloudFoundryServers() { private List<CloudFoundryServer> cloudFoundryServers() {
Assert.notNull(this.clientConfig, "clientConfig may not be null"); Assert.notNull(this.clientConfig, "clientConfig may not be null");
RibbonProperties ribbon = RibbonProperties.from(clientConfig); RibbonProperties ribbon = RibbonProperties.from(this.clientConfig);
Boolean secure = ribbon.getSecure(); Boolean secure = ribbon.getSecure();
Integer securePort = ribbon.getSecurePort(); Integer securePort = ribbon.getSecurePort();
@@ -69,21 +73,23 @@ public class CloudFoundryServerList extends AbstractServerList<CloudFoundryServe
final int port; final int port;
if (secure != null && secure && securePort != null) { if (secure != null && secure && securePort != null) {
port = securePort; port = securePort;
} else if (nonSecurePort != null) { }
else if (nonSecurePort != null) {
port = nonSecurePort; port = nonSecurePort;
} else { }
else {
port = this.properties.getDefaultServerPort(); port = this.properties.getDefaultServerPort();
} }
return cloudFoundryService return this.cloudFoundryService.getApplicationInstances(this.serviceId)
.getApplicationInstances(this.serviceId) .map(tpl -> new CloudFoundryServer(tpl.getT1().getName(),
.map(tpl -> new CloudFoundryServer(tpl.getT1().getName(), tpl.getT1().getUrls().get(0), port)) tpl.getT1().getUrls().get(0), port))
.collectList() .collectList().blockOptional().orElse(new ArrayList<>());
.blockOptional()
.orElse(new ArrayList<>());
} }
/** for testing */ String getServiceId() { // for testing
return serviceId; String getServiceId() {
return this.serviceId;
} }
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2015 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -26,9 +26,10 @@ import java.lang.annotation.Target;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/** /**
* Convenience annotation for clients to enable Cloud Foundry discovery configuration (specifically). * Convenience annotation for clients to enable Cloud Foundry discovery configuration
* Use this (optionally) in case you want discovery and know for sure that it is Cloud Foundry you want. * (specifically). Use this (optionally) in case you want discovery and know for sure that
* All it does is turn on discovery and let the auto-configuration find the Cloud Foundry classes. * it is Cloud Foundry you want. All it does is turn on discovery and let the
* auto-configuration find the Cloud Foundry classes.
* *
* @author Josh Long * @author Josh Long
*/ */
@@ -38,4 +39,5 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@Inherited @Inherited
@EnableDiscoveryClient @EnableDiscoveryClient
public @interface EnableCloudFoundryClient { public @interface EnableCloudFoundryClient {
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2015 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.cloud.cloudfoundry.discovery; package org.springframework.cloud.cloudfoundry.discovery;
import com.netflix.client.IClient;
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@@ -26,8 +28,11 @@ import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import com.netflix.client.IClient; /**
* Auto configuration for Ribbon.
*
* @author Josh Long
*/
@Configuration @Configuration
@EnableConfigurationProperties @EnableConfigurationProperties
@ConditionalOnClass(IClient.class) @ConditionalOnClass(IClient.class)
@@ -36,4 +41,5 @@ import com.netflix.client.IClient;
@AutoConfigureAfter(RibbonAutoConfiguration.class) @AutoConfigureAfter(RibbonAutoConfiguration.class)
@RibbonClients(defaultConfiguration = CloudFoundryRibbonClientConfiguration.class) @RibbonClients(defaultConfiguration = CloudFoundryRibbonClientConfiguration.class)
public class RibbonCloudFoundryAutoConfiguration { public class RibbonCloudFoundryAutoConfiguration {
}
}

View File

@@ -1,6 +1,5 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.cloudfoundry.discovery.RibbonCloudFoundryAutoConfiguration org.springframework.cloud.cloudfoundry.discovery.RibbonCloudFoundryAutoConfiguration
# Discovery Client Configuration # Discovery Client Configuration
org.springframework.cloud.client.discovery.EnableDiscoveryClient=\ org.springframework.cloud.client.discovery.EnableDiscoveryClient=\
org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryClientConfiguration org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryClientConfiguration

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2014 the original author or authors. * Copyright 2012-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -27,7 +27,7 @@ import org.junit.runners.Suite.SuiteClasses;
* @author Dave Syer * @author Dave Syer
*/ */
@RunWith(Suite.class) @RunWith(Suite.class)
@SuiteClasses({CloudFoundryServerListTest.class}) @SuiteClasses({ CloudFoundryServerListTest.class })
@Ignore @Ignore
public class AdhocTestSuite { public class AdhocTestSuite {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,6 +16,9 @@
package org.springframework.cloud.cloudfoundry.discovery; package org.springframework.cloud.cloudfoundry.discovery;
import java.util.List;
import java.util.UUID;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.CloudFoundryOperations;
@@ -23,20 +26,17 @@ import org.cloudfoundry.operations.applications.ApplicationDetail;
import org.cloudfoundry.operations.applications.ApplicationSummary; import org.cloudfoundry.operations.applications.ApplicationSummary;
import org.cloudfoundry.operations.applications.Applications; import org.cloudfoundry.operations.applications.Applications;
import org.cloudfoundry.operations.applications.InstanceDetail; import org.cloudfoundry.operations.applications.InstanceDetail;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.cloudfoundry.CloudFoundryService;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import reactor.util.function.Tuple2; import reactor.util.function.Tuple2;
import reactor.util.function.Tuples; import reactor.util.function.Tuples;
import java.util.List; import org.springframework.cloud.client.ServiceInstance;
import java.util.UUID; import org.springframework.cloud.cloudfoundry.CloudFoundryService;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@@ -45,60 +45,53 @@ import static org.mockito.Mockito.mock;
public class CloudFoundryDiscoveryClientTest { public class CloudFoundryDiscoveryClientTest {
private final Log log = LogFactory.getLog(getClass()); private final Log log = LogFactory.getLog(getClass());
private CloudFoundryDiscoveryClient cloudFoundryDiscoveryClient; private CloudFoundryDiscoveryClient cloudFoundryDiscoveryClient;
private String hiServiceServiceId = "hi-service"; private String hiServiceServiceId = "hi-service";
private CloudFoundryOperations ops; private CloudFoundryOperations ops;
private CloudFoundryService svc; private CloudFoundryService svc;
@Before @Before
public void setUp() { public void setUp() {
this.ops = mock(CloudFoundryOperations.class); this.ops = mock(CloudFoundryOperations.class);
this.svc = mock(CloudFoundryService.class); this.svc = mock(CloudFoundryService.class);
this.cloudFoundryDiscoveryClient = new CloudFoundryDiscoveryClient(this.ops, this.svc, this.cloudFoundryDiscoveryClient = new CloudFoundryDiscoveryClient(this.ops,
new CloudFoundryDiscoveryProperties()); this.svc, new CloudFoundryDiscoveryProperties());
} }
@Test @Test
public void testServiceResolution() { public void testServiceResolution() {
Applications apps = mock(Applications.class); Applications apps = mock(Applications.class);
ApplicationSummary s = ApplicationSummary.builder() ApplicationSummary s = ApplicationSummary.builder()
.id(UUID.randomUUID().toString()) .id(UUID.randomUUID().toString()).instances(2).memoryLimit(1024)
.instances(2) .requestedState("requestedState").diskQuota(1024)
.memoryLimit(1024) .name(this.hiServiceServiceId).runningInstances(2).build();
.requestedState("requestedState")
.diskQuota(1024)
.name(this.hiServiceServiceId)
.runningInstances(2)
.build();
Mockito.when(apps.list()).thenReturn(Flux.just(s)); Mockito.when(apps.list()).thenReturn(Flux.just(s));
Mockito.when(this.ops.applications()).thenReturn(apps); Mockito.when(this.ops.applications()).thenReturn(apps);
List<String> serviceNames = this.cloudFoundryDiscoveryClient.getServices(); List<String> serviceNames = this.cloudFoundryDiscoveryClient.getServices();
Assert.assertTrue("there should be one registered service.", serviceNames.contains(this.hiServiceServiceId)); assertThat(serviceNames.contains(this.hiServiceServiceId))
serviceNames.forEach(serviceName -> this.log.debug("\t discovered serviceName: " + serviceName)); .as("there should be one registered service.").isTrue();
serviceNames.forEach(serviceName -> this.log
.debug("\t discovered serviceName: " + serviceName));
} }
@Test @Test
public void testInstances() { public void testInstances() {
ApplicationDetail applicationDetail = ApplicationDetail ApplicationDetail applicationDetail = ApplicationDetail.builder().instances(2)
.builder() .name("my-app").stack("stack").memoryLimit(1024).id("id")
.instances(2) .requestedState("requestedState").runningInstances(2)
.name("my-app") .url("http://my-app.cfapps.io").diskQuota(20).build();
.stack("stack") InstanceDetail instanceDetail = InstanceDetail.builder().index("0").build();
.memoryLimit(1024) Tuple2<ApplicationDetail, InstanceDetail> tuple2 = Tuples.of(applicationDetail,
.id("id") instanceDetail);
.requestedState("requestedState") Mockito.when(this.svc.getApplicationInstances(this.hiServiceServiceId))
.runningInstances(2) .thenReturn(Flux.just(tuple2));
.url("http://my-app.cfapps.io")
.diskQuota(20)
.build();
InstanceDetail instanceDetail = InstanceDetail
.builder()
.index("0")
.build();
Tuple2<ApplicationDetail, InstanceDetail> tuple2 = Tuples.of(applicationDetail, instanceDetail);
Mockito.when(svc.getApplicationInstances(this.hiServiceServiceId)).thenReturn(Flux.just(tuple2));
List<ServiceInstance> instances = this.cloudFoundryDiscoveryClient List<ServiceInstance> instances = this.cloudFoundryDiscoveryClient
.getInstances(this.hiServiceServiceId); .getInstances(this.hiServiceServiceId);
assertEquals("Wrong instances: " + instances, 1, instances.size()); assertThat(instances.size()).as("Wrong instances: " + instances).isEqualTo(1);
} }
}
}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2018 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -18,36 +18,35 @@ package org.springframework.cloud.cloudfoundry.discovery;
import java.util.List; import java.util.List;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.config.IClientConfig;
import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.ApplicationDetail;
import org.cloudfoundry.operations.applications.InstanceDetail; import org.cloudfoundry.operations.applications.InstanceDetail;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.cloud.cloudfoundry.CloudFoundryService; import reactor.core.publisher.Flux;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
import com.netflix.client.config.CommonClientConfigKey; import org.springframework.cloud.cloudfoundry.CloudFoundryService;
import com.netflix.client.config.IClientConfig;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import reactor.core.publisher.Flux;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
/** /**
* @author Josh Long * @author Josh Long
*/ */
public class CloudFoundryServerListTest { public class CloudFoundryServerListTest {
private CloudFoundryServerList cloudFoundryServerList; private CloudFoundryServerList cloudFoundryServerList;
private String serviceId = "foo-service"; private String serviceId = "foo-service";
@Before @Before
public void setUp() { public void setUp() {
IClientConfig iClientConfig = IClientConfig.Builder.newBuilder(this.serviceId) IClientConfig iClientConfig = IClientConfig.Builder.newBuilder(this.serviceId)
.withSecure(true) .withSecure(true).build();
.build();
iClientConfig.set(CommonClientConfigKey.SecurePort, 443); iClientConfig.set(CommonClientConfigKey.SecurePort, 443);
Tuple2<ApplicationDetail, InstanceDetail> tuple2 = getInstanceDetail(); Tuple2<ApplicationDetail, InstanceDetail> tuple2 = getInstanceDetail();
@@ -55,7 +54,8 @@ public class CloudFoundryServerListTest {
CloudFoundryService cfs = mock(CloudFoundryService.class); CloudFoundryService cfs = mock(CloudFoundryService.class);
when(cfs.getApplicationInstances(this.serviceId)).thenReturn(Flux.just(tuple2)); when(cfs.getApplicationInstances(this.serviceId)).thenReturn(Flux.just(tuple2));
this.cloudFoundryServerList = new CloudFoundryServerList(cfs, new CloudFoundryDiscoveryProperties()); this.cloudFoundryServerList = new CloudFoundryServerList(cfs,
new CloudFoundryDiscoveryProperties());
this.cloudFoundryServerList.initWithNiwsConfig(iClientConfig); this.cloudFoundryServerList.initWithNiwsConfig(iClientConfig);
} }
@@ -85,8 +85,10 @@ public class CloudFoundryServerListTest {
@Test @Test
public void testListOfServers() { public void testListOfServers() {
List<CloudFoundryServer> initialListOfServers = this.cloudFoundryServerList.getInitialListOfServers(); List<CloudFoundryServer> initialListOfServers = this.cloudFoundryServerList
List<CloudFoundryServer> updatedListOfServers = this.cloudFoundryServerList.getUpdatedListOfServers(); .getInitialListOfServers();
List<CloudFoundryServer> updatedListOfServers = this.cloudFoundryServerList
.getUpdatedListOfServers();
assertThat(initialListOfServers) assertThat(initialListOfServers)
.containsExactly(updatedListOfServers.toArray(new CloudFoundryServer[0])) .containsExactly(updatedListOfServers.toArray(new CloudFoundryServer[0]))
.hasSize(1); .hasSize(1);
@@ -105,7 +107,8 @@ public class CloudFoundryServerListTest {
CloudFoundryService cfs = mock(CloudFoundryService.class); CloudFoundryService cfs = mock(CloudFoundryService.class);
when(cfs.getApplicationInstances(this.serviceId)).thenReturn(Flux.just(tuple2)); when(cfs.getApplicationInstances(this.serviceId)).thenReturn(Flux.just(tuple2));
CloudFoundryServerList serverList = new CloudFoundryServerList(cfs, new CloudFoundryDiscoveryProperties()); CloudFoundryServerList serverList = new CloudFoundryServerList(cfs,
new CloudFoundryDiscoveryProperties());
serverList.initWithNiwsConfig(iClientConfig); serverList.initWithNiwsConfig(iClientConfig);
CloudFoundryServer server = serverList.getInitialListOfServers().get(0); CloudFoundryServer server = serverList.getInitialListOfServers().get(0);

View File

@@ -13,8 +13,8 @@ import org.springframework.web.bind.annotation.RestController
@RestController @RestController
class GreetingRestController { class GreetingRestController {
@RequestMapping("/hi/{name}") @RequestMapping("/hi/{name}")
def hi(@PathVariable String name) { def hi(@PathVariable String name) {
[greeting: "Hello, " + name + "!"] [greeting: "Hello, " + name + "!"]
} }
} }

View File

@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <project 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"> xmlns="http://maven.apache.org/POM/4.0.0"
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> <modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-cloudfoundry-sample</artifactId> <artifactId>spring-cloud-cloudfoundry-sample</artifactId>

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2015 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.cloud.cloudfoundry.sample;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -26,22 +27,19 @@ import org.springframework.cloud.cloudfoundry.discovery.EnableCloudFoundryClient
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
/** /**
* This example uses the Spring Cloud {@code DiscoveryClient} abstraction to list all services * This example uses the Spring Cloud {@code DiscoveryClient} abstraction to list all
* available to the application. It should deployed to a Cloud Foundry organization and space that * services available to the application. It should deployed to a Cloud Foundry
* has other applications deployed to it. * organization and space that has other applications deployed to it.
* *
* There is a sample file in the project root called {@code hi-service.groovy} which can be * There is a sample file in the project root called {@code hi-service.groovy} which can
* deployed using the {@code spring} CLI and the {@code cf} CLI that works appropriately for * be deployed using the {@code spring} CLI and the {@code cf} CLI that works
* this example. * appropriately for this example.
* *
* Either modify this application's {@code application.yml} configuration file to provide credentials * Either modify this application's {@code application.yml} configuration file to provide
* and other information for the Cloud Foundry the app is deployed to, or set the following * credentials and other information for the Cloud Foundry the app is deployed to, or set
* environment variables on the application (using {@code cf set-env}): * the following environment variables on the application (using {@code cf set-env}):
* *
* * {@code CF_USERNAME} * * {@code CF_USERNAME} * {@code CF_PASSWORD} * {@code CF_ORG} * {@code CF_SPACE}
* * {@code CF_PASSWORD}
* * {@code CF_ORG}
* * {@code CF_SPACE}
* *
* @author Josh Long * @author Josh Long
* @author Spencer Gibb * @author Spencer Gibb
@@ -59,10 +57,11 @@ public class CloudFoundryApplication {
@Bean @Bean
CommandLineRunner demo(CloudFoundryDiscoveryClient discoveryClient) { CommandLineRunner demo(CloudFoundryDiscoveryClient discoveryClient) {
Log log = LogFactory.getLog(getClass()); Log log = LogFactory.getLog(getClass());
return args -> return args -> discoveryClient.getServices().forEach(svc -> {
discoveryClient.getServices().forEach(svc -> { log.info("service = " + svc);
log.info("service = " + svc); discoveryClient.getInstances(svc)
discoveryClient.getInstances(svc).forEach(si -> log.info("\tinstance = " + si)); .forEach(si -> log.info("\tinstance = " + si));
}); });
} }
} }

View File

@@ -1,9 +1,9 @@
spring: spring:
application: application:
name: test-app name: test-app
cloud: cloud:
cloudfoundry: cloudfoundry:
username: ${CF_USERNAME:starbuxman@gmail.com} username: ${CF_USERNAME:starbuxman@gmail.com}
password: ${CF_PASSWORD:xxxx} password: ${CF_PASSWORD:xxxx}
org: ${CF_ORG:} org: ${CF_ORG:}
space: ${CF_SPACE:} space: ${CF_SPACE:}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2015 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,11 +13,13 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.cloud.cloudfoundry.sample; package org.springframework.cloud.cloudfoundry.sample;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;

View File

@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <project 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"> xmlns="http://maven.apache.org/POM/4.0.0"
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> <modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-cloudfoundry-web</artifactId> <artifactId>spring-cloud-cloudfoundry-web</artifactId>

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2014 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.cloud.cloudfoundry.environment; package org.springframework.cloud.cloudfoundry.environment;
import java.util.Collections; import java.util.Collections;

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2014 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.cloud.cloudfoundry.session; package org.springframework.cloud.cloudfoundry.session;
import java.lang.annotation.Documented; import java.lang.annotation.Documented;
@@ -33,4 +34,4 @@ import org.springframework.context.annotation.Import;
@Import(StickyFilterConfiguration.class) @Import(StickyFilterConfiguration.class)
public @interface EnableStickyFilter { public @interface EnableStickyFilter {
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2014 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.cloud.cloudfoundry.session; package org.springframework.cloud.cloudfoundry.session;
import java.io.IOException; import java.io.IOException;
@@ -52,7 +53,8 @@ public class StickyFilterConfiguration {
HttpServletResponse response, FilterChain filterChain) HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException { throws ServletException, IOException {
if (!response.containsHeader("Set-Cookie")) { if (!response.containsHeader("Set-Cookie")) {
response.addCookie(new Cookie("JSESSIONID", cookie)); response.addCookie(new Cookie("JSESSIONID",
StickyFilterConfiguration.this.cookie));
} }
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
} }

View File

@@ -1,2 +1,2 @@
spring.cloud.cloudfoundry.web.cookie=${random} spring.cloud.cloudfoundry.web.cookie=${random}
eureka.instance.metadata-map.cookie=${spring.cloud.cloudfoundry.web.cookie} eureka.instance.metadata-map.cookie=${spring.cloud.cloudfoundry.web.cookie}

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2013-2014 the original author or authors. * Copyright 2013-2019 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,20 +13,21 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.cloud.cloudfoundry.environment; package org.springframework.cloud.cloudfoundry.environment;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.StandardEnvironment; import org.springframework.core.env.StandardEnvironment;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.cloud.cloudfoundry.environment.VcapServiceCredentialsEnvironmentPostProcessor.STRING_OBJECT_MAP; import static org.springframework.cloud.cloudfoundry.environment.VcapServiceCredentialsEnvironmentPostProcessor.STRING_OBJECT_MAP;
/** /**
@@ -42,66 +43,85 @@ public class VcapServiceCredentialsEnvironmentPostProcessorTests {
@Test @Test
public void noop() { public void noop() {
this.listener.postProcessEnvironment(this.environment, new SpringApplication()); this.listener.postProcessEnvironment(this.environment, new SpringApplication());
Map<String, Object> properties = Binder.get(environment) Map<String, Object> properties = Binder.get(this.environment)
.bind("security.oauth2", STRING_OBJECT_MAP).orElseGet(Collections::emptyMap); .bind("security.oauth2", STRING_OBJECT_MAP)
assertTrue(properties.isEmpty()); .orElseGet(Collections::emptyMap);
assertThat(properties.isEmpty()).isTrue();
} }
@Test @Test
public void addClientId() { public void addClientId() {
TestPropertyValues.of("vcap.services.sso.credentials.clientId:foo").applyTo(this.environment); TestPropertyValues.of("vcap.services.sso.credentials.clientId:foo")
.applyTo(this.environment);
this.listener.postProcessEnvironment(this.environment, new SpringApplication()); this.listener.postProcessEnvironment(this.environment, new SpringApplication());
assertEquals("foo", this.environment assertThat(this.environment
.resolvePlaceholders("${security.oauth2.client.client-id}")); .resolvePlaceholders("${security.oauth2.client.client-id}"))
.isEqualTo("foo");
} }
@Test @Test
public void addClientIdUnderscores() { public void addClientIdUnderscores() {
TestPropertyValues.of("vcap.services.sso.credentials.client-id:foo").applyTo(this.environment); TestPropertyValues.of("vcap.services.sso.credentials.client-id:foo")
.applyTo(this.environment);
this.listener.postProcessEnvironment(this.environment, new SpringApplication()); this.listener.postProcessEnvironment(this.environment, new SpringApplication());
assertEquals("foo", this.environment assertThat(this.environment
.resolvePlaceholders("${security.oauth2.client.client-id}")); .resolvePlaceholders("${security.oauth2.client.client-id}"))
.isEqualTo("foo");
} }
@Test @Test
public void addTokenUri() { public void addTokenUri() {
TestPropertyValues.of( "vcap.services.sso.credentials.accessTokenUri:http://example.com").applyTo(this.environment); TestPropertyValues
.of("vcap.services.sso.credentials.accessTokenUri:http://example.com")
.applyTo(this.environment);
this.listener.postProcessEnvironment(this.environment, new SpringApplication()); this.listener.postProcessEnvironment(this.environment, new SpringApplication());
assertEquals("http://example.com", this.environment assertThat(this.environment
.resolvePlaceholders("${security.oauth2.client.access-token-uri}")); .resolvePlaceholders("${security.oauth2.client.access-token-uri}"))
.isEqualTo("http://example.com");
} }
@Test @Test
public void addTokenUriAuthDomain() { public void addTokenUriAuthDomain() {
TestPropertyValues.of("vcap.services.sso.credentials.auth-domain:http://example.com").applyTo(this.environment); TestPropertyValues
.of("vcap.services.sso.credentials.auth-domain:http://example.com")
.applyTo(this.environment);
this.listener.postProcessEnvironment(this.environment, new SpringApplication()); this.listener.postProcessEnvironment(this.environment, new SpringApplication());
assertEquals("http://example.com/oauth/token", this.environment assertThat(this.environment
.resolvePlaceholders("${security.oauth2.client.access-token-uri}")); .resolvePlaceholders("${security.oauth2.client.access-token-uri}"))
.isEqualTo("http://example.com/oauth/token");
} }
@Test @Test
public void addUserInfoUri() { public void addUserInfoUri() {
TestPropertyValues.of( "vcap.services.sso.credentials.userInfoUri:http://example.com").applyTo(this.environment); TestPropertyValues
.of("vcap.services.sso.credentials.userInfoUri:http://example.com")
.applyTo(this.environment);
this.listener.postProcessEnvironment(this.environment, new SpringApplication()); this.listener.postProcessEnvironment(this.environment, new SpringApplication());
assertEquals("http://example.com", this.environment assertThat(this.environment
.resolvePlaceholders("${security.oauth2.resource.user-info-uri}")); .resolvePlaceholders("${security.oauth2.resource.user-info-uri}"))
.isEqualTo("http://example.com");
} }
@Test @Test
public void addServiceId() { public void addServiceId() {
TestPropertyValues.of("vcap.services.my.credentials.accessTokenUri:http://example.com", TestPropertyValues
"security.oauth2.sso.serviceId:my").applyTo(this.environment); .of("vcap.services.my.credentials.accessTokenUri:http://example.com",
"security.oauth2.sso.serviceId:my")
.applyTo(this.environment);
this.listener.postProcessEnvironment(this.environment, new SpringApplication()); this.listener.postProcessEnvironment(this.environment, new SpringApplication());
assertEquals("http://example.com", this.environment assertThat(this.environment
.resolvePlaceholders("${security.oauth2.client.access-token-uri}")); .resolvePlaceholders("${security.oauth2.client.access-token-uri}"))
.isEqualTo("http://example.com");
} }
@Test @Test
public void addJwtKeyUri() { public void addJwtKeyUri() {
TestPropertyValues.of("vcap.services.sso.credentials.keyUri:http://example.com").applyTo(this.environment); TestPropertyValues.of("vcap.services.sso.credentials.keyUri:http://example.com")
.applyTo(this.environment);
this.listener.postProcessEnvironment(this.environment, new SpringApplication()); this.listener.postProcessEnvironment(this.environment, new SpringApplication());
assertEquals("http://example.com", this.environment assertThat(this.environment
.resolvePlaceholders("${security.oauth2.resource.jwt.key-uri}")); .resolvePlaceholders("${security.oauth2.resource.jwt.key-uri}"))
.isEqualTo("http://example.com");
} }
} }

View File

@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <project 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"> xmlns="http://maven.apache.org/POM/4.0.0"
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> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>

View File

@@ -1 +1 @@
provides: spring-cloud-security provides: spring-cloud-security