├── .gitignore ├── authgateway ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── manifest.yml ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── org │ │ │ └── springframework │ │ │ └── cloud │ │ │ └── samples │ │ │ └── authgateway │ │ │ ├── AuthgatewayApplication.java │ │ │ ├── RoleBasedAuthenticationSuccessHandler.java │ │ │ └── RoleBasedServerLogoutSuccessHandler.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── org │ └── springframework │ └── cloud │ └── samples │ └── authgateway │ └── AuthgatewayApplicationTests.java ├── blueorgreenfrontend ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── manifest.yml ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── org │ │ │ └── springframework │ │ │ └── demo │ │ │ └── BlueOrGreenFrontendApplication.java │ └── resources │ │ ├── application.yml │ │ └── static │ │ └── index.html │ └── test │ └── java │ └── org │ └── springframework │ └── demo │ └── BlueOrGreenFrontendApplicationTests.java ├── blueorgreengateway ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── manifest.yml ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── org │ │ │ └── springframework │ │ │ └── demo │ │ │ └── blueorgreengateway │ │ │ ├── BlueorgreengatewayApplication.java │ │ │ └── CustomLoadBalancerClientFilter.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── org │ └── springframework │ └── demo │ └── blueorgreengateway │ └── BlueorgreengatewayApplicationTests.java ├── blueorgreenservice ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── manifest.yml ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── org │ │ │ └── springframework │ │ │ └── demo │ │ │ ├── BlueOrGreenApplication.java │ │ │ ├── ColorController.java │ │ │ └── ColorProperties.java │ └── resources │ │ ├── application-blue.yml │ │ ├── application-green.yml │ │ ├── application-slowgreen.yml │ │ ├── application-yellow.yml │ │ └── application.yml │ └── test │ ├── java │ └── org │ │ └── springframework │ │ └── demo │ │ ├── BlueApplicationTests.java │ │ ├── GreenApplicationTests.java │ │ └── base │ │ └── ColorBase.java │ └── resources │ └── contracts │ └── color │ └── shouldReturnColor.groovy ├── deploy.sh └── route-service-broker ├── .gitignore ├── 00_deploy.sh ├── README.adoc ├── build.gradle ├── deploy └── cloudfoundry │ └── README.adoc ├── gradle ├── pipeline.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── manifest.yml ├── settings.gradle └── src ├── main ├── java │ └── org │ │ └── springframework │ │ └── cloud │ │ └── sample │ │ └── routeservice │ │ ├── ServiceBrokerApplication.java │ │ ├── config │ │ ├── HeaderFilter.java │ │ ├── RoleTypeWebFilter.java │ │ ├── RouteConfiguration.java │ │ ├── SecurityConfiguration.java │ │ ├── ServiceConfiguration.java │ │ └── UndoHeaderFilter.java │ │ ├── filter │ │ ├── LoggingGatewayFilterFactory.java │ │ └── SubscriptionHandlerGatewayFilterFactory.java │ │ └── servicebroker │ │ ├── RateLimiters.java │ │ ├── RouteLoggingServiceBindingService.java │ │ ├── RouteLoggingServiceInstanceService.java │ │ ├── ServiceCatalogConfig.java │ │ ├── ServiceInstance.java │ │ └── ServiceInstanceRepository.java └── resources │ ├── application.yml │ └── static │ └── images │ ├── face-with-monocle-and-arrows.png │ ├── face-with-monocle.png │ └── service-broker-icon.png └── test └── java └── org └── springframework └── cloud └── sample └── routeservice ├── ServiceBrokerApplicationTests.java └── config └── RoleTypeWebFilterTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /authgateway/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /authgateway/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ryanjbaxter/gateway-s1p-2018/68cc10b09823fbc0cfb90735e2df82f35a749fff/authgateway/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /authgateway/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip 2 | -------------------------------------------------------------------------------- /authgateway/manifest.yml: -------------------------------------------------------------------------------- 1 | --- 2 | applications: 3 | - name: blueorgreenauthgateway 4 | memory: 1024M 5 | path: target/authgateway-0.0.1-SNAPSHOT.jar 6 | timeout: 60 7 | services: 8 | - bluegreen-registry -------------------------------------------------------------------------------- /authgateway/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /authgateway/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /authgateway/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.cloud.samples 7 | authgateway 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | authgateway 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.5.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Finchley.SR1 26 | 2.0.1.RELEASE 27 | 28 | 5.1.0.RC2 29 | 30 | 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-security 35 | 36 | 37 | org.springframework.cloud 38 | spring-cloud-starter-gateway 39 | 40 | 41 | org.springframework.cloud 42 | spring-cloud-starter-netflix-eureka-client 43 | 44 | 45 | io.pivotal.spring.cloud 46 | spring-cloud-services-starter-service-registry 47 | 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-test 52 | test 53 | 54 | 55 | org.springframework.security 56 | spring-security-test 57 | test 58 | 59 | 60 | 61 | 62 | 63 | 64 | org.springframework.cloud 65 | spring-cloud-dependencies 66 | ${spring-cloud.version} 67 | pom 68 | import 69 | 70 | 71 | io.pivotal.spring.cloud 72 | spring-cloud-services-dependencies 73 | ${scs.version} 74 | pom 75 | import 76 | 77 | 78 | 79 | 80 | 81 | 82 | spring-snapshots 83 | Spring Snapshots 84 | https://repo.spring.io/libs-milestone 85 | 86 | 87 | spring-releases 88 | https://repo.spring.io/libs-release 89 | 90 | 91 | 92 | 93 | 94 | 95 | org.springframework.boot 96 | spring-boot-maven-plugin 97 | 98 | 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /authgateway/src/main/java/org/springframework/cloud/samples/authgateway/AuthgatewayApplication.java: -------------------------------------------------------------------------------- 1 | package org.springframework.cloud.samples.authgateway; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.gateway.route.RouteLocator; 6 | import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 12 | import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; 13 | import org.springframework.security.config.web.server.ServerHttpSecurity; 14 | import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; 15 | import org.springframework.security.core.userdetails.User; 16 | import org.springframework.security.core.userdetails.UserDetails; 17 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 18 | import org.springframework.security.crypto.password.PasswordEncoder; 19 | import org.springframework.security.web.server.SecurityWebFilterChain; 20 | import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler; 21 | 22 | @SpringBootApplication 23 | public class AuthgatewayApplication { 24 | 25 | public static void main(String[] args) { 26 | SpringApplication.run(AuthgatewayApplication.class, args); 27 | } 28 | 29 | @Bean 30 | public RouteLocator routeLocator(RouteLocatorBuilder builder) { 31 | return builder.routes() 32 | .route(p -> p.path("/**").uri("lb://blueorgreengateway")) 33 | .build(); 34 | } 35 | 36 | @EnableWebFluxSecurity 37 | @Configuration 38 | public class MyExplicitSecurityConfiguration { 39 | @Bean 40 | public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { 41 | http.authorizeExchange().pathMatchers("/", "/color").authenticated() 42 | .and().logout().logoutSuccessHandler(new RoleBasedServerLogoutSuccessHandler()) 43 | .and().formLogin().authenticationSuccessHandler(new RoleBasedAuthenticationSuccessHandler()) 44 | .and().authorizeExchange().pathMatchers("/js/**", "favicon.ico", "/favicon.ico").permitAll(); 45 | return http.build(); 46 | } 47 | 48 | @Bean 49 | public MapReactiveUserDetailsService userDetailsService() { 50 | PasswordEncoder pwEncoder = new BCryptPasswordEncoder(); 51 | UserDetails premium = User.withDefaultPasswordEncoder().username("premium").password("pw").roles("PREMIUM").build(); 52 | UserDetails basic = User.withDefaultPasswordEncoder().username("user").password("pw").roles("BASIC").build(); 53 | return new MapReactiveUserDetailsService(premium, basic); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /authgateway/src/main/java/org/springframework/cloud/samples/authgateway/RoleBasedAuthenticationSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package org.springframework.cloud.samples.authgateway; 2 | 3 | import reactor.core.publisher.Mono; 4 | 5 | import org.springframework.http.ResponseCookie; 6 | import org.springframework.security.core.Authentication; 7 | import org.springframework.security.web.server.WebFilterExchange; 8 | import org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler; 9 | import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler; 10 | 11 | /** 12 | * @author Ryan Baxter 13 | */ 14 | public class RoleBasedAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler { 15 | 16 | private RedirectServerAuthenticationSuccessHandler redirectServerAuthenticationSuccessHandler = 17 | new RedirectServerAuthenticationSuccessHandler(); 18 | 19 | @Override 20 | public Mono onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) { 21 | if(authentication.getAuthorities().stream().anyMatch(a -> "role_premium".equalsIgnoreCase(a.getAuthority()))) { 22 | ResponseCookie cookie = ResponseCookie.from("type", "premium").path("/").build(); 23 | webFilterExchange.getExchange().getResponse().addCookie(cookie); 24 | } 25 | return redirectServerAuthenticationSuccessHandler.onAuthenticationSuccess(webFilterExchange, authentication); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /authgateway/src/main/java/org/springframework/cloud/samples/authgateway/RoleBasedServerLogoutSuccessHandler.java: -------------------------------------------------------------------------------- 1 | package org.springframework.cloud.samples.authgateway; 2 | 3 | import reactor.core.publisher.Mono; 4 | 5 | import org.springframework.http.ResponseCookie; 6 | import org.springframework.security.core.Authentication; 7 | import org.springframework.security.web.server.WebFilterExchange; 8 | import org.springframework.security.web.server.authentication.logout.RedirectServerLogoutSuccessHandler; 9 | import org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler; 10 | 11 | /** 12 | * @author Ryan Baxter 13 | */ 14 | public class RoleBasedServerLogoutSuccessHandler implements ServerLogoutSuccessHandler { 15 | 16 | private RedirectServerLogoutSuccessHandler redirectServerLogoutSuccessHandler = new RedirectServerLogoutSuccessHandler(); 17 | 18 | @Override 19 | public Mono onLogoutSuccess(WebFilterExchange webFilterExchange, Authentication authentication) { 20 | ResponseCookie responseCookie = ResponseCookie.from("type", "").build(); 21 | webFilterExchange.getExchange().getResponse().addCookie(responseCookie); 22 | return redirectServerLogoutSuccessHandler.onLogoutSuccess(webFilterExchange, authentication); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /authgateway/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | eureka: 2 | client: 3 | serviceUrl: 4 | defaultZone: http://localhost:8761/eureka/ 5 | instance: 6 | leaseRenewalIntervalInSeconds: 10 7 | metadataMap: 8 | instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${server.port}}} 9 | spring: 10 | application: 11 | name: blueorgreenauthgateway -------------------------------------------------------------------------------- /authgateway/src/test/java/org/springframework/cloud/samples/authgateway/AuthgatewayApplicationTests.java: -------------------------------------------------------------------------------- 1 | package org.springframework.cloud.samples.authgateway; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class AuthgatewayApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /blueorgreenfrontend/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /blueorgreenfrontend/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ryanjbaxter/gateway-s1p-2018/68cc10b09823fbc0cfb90735e2df82f35a749fff/blueorgreenfrontend/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /blueorgreenfrontend/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip 2 | -------------------------------------------------------------------------------- /blueorgreenfrontend/manifest.yml: -------------------------------------------------------------------------------- 1 | --- 2 | applications: 3 | - name: blueorgreenfrontend 4 | memory: 1024M 5 | path: target/blueorgreenfrontend-0.0.1-SNAPSHOT.jar 6 | timeout: 60 7 | services: 8 | - bluegreen-registry 9 | no-route: true 10 | -------------------------------------------------------------------------------- /blueorgreenfrontend/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /blueorgreenfrontend/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /blueorgreenfrontend/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.demo 7 | blueorgreenfrontend 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | blueorgreenfrontend 12 | Frontend For Blue Green App 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.16.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Edgware.SR4 26 | 1.6.4.RELEASE 27 | 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-web 33 | 34 | 35 | org.springframework.cloud 36 | spring-cloud-starter-netflix-eureka-client 37 | 38 | 39 | io.pivotal.spring.cloud 40 | spring-cloud-services-starter-service-registry 41 | 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-test 46 | test 47 | 48 | 49 | 50 | 51 | 52 | 53 | org.springframework.cloud 54 | spring-cloud-dependencies 55 | ${spring-cloud.version} 56 | pom 57 | import 58 | 59 | 60 | io.pivotal.spring.cloud 61 | spring-cloud-services-dependencies 62 | ${scs.version} 63 | pom 64 | import 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | org.springframework.boot 73 | spring-boot-maven-plugin 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /blueorgreenfrontend/src/main/java/org/springframework/demo/BlueOrGreenFrontendApplication.java: -------------------------------------------------------------------------------- 1 | package org.springframework.demo; 2 | 3 | import java.io.IOException; 4 | import java.net.URI; 5 | import java.net.URISyntaxException; 6 | import java.util.regex.Pattern; 7 | 8 | import javax.servlet.http.HttpServletResponse; 9 | import org.apache.catalina.servlet4preview.http.HttpServletRequest; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.beans.factory.annotation.Value; 14 | import org.springframework.boot.SpringApplication; 15 | import org.springframework.boot.autoconfigure.SpringBootApplication; 16 | import org.springframework.boot.web.client.RestTemplateBuilder; 17 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 18 | import org.springframework.cloud.client.loadbalancer.LoadBalanced; 19 | import org.springframework.context.annotation.Bean; 20 | import org.springframework.context.annotation.Configuration; 21 | import org.springframework.http.HttpMethod; 22 | import org.springframework.http.HttpStatus; 23 | import org.springframework.http.RequestEntity; 24 | import org.springframework.http.ResponseEntity; 25 | import org.springframework.http.client.ClientHttpResponse; 26 | import org.springframework.stereotype.Component; 27 | import org.springframework.util.LinkedMultiValueMap; 28 | import org.springframework.util.MultiValueMap; 29 | import org.springframework.web.bind.annotation.RequestMapping; 30 | import org.springframework.web.bind.annotation.RestController; 31 | import org.springframework.web.client.DefaultResponseErrorHandler; 32 | import org.springframework.web.client.RestTemplate; 33 | 34 | @SpringBootApplication 35 | @EnableDiscoveryClient 36 | @RestController 37 | public class BlueOrGreenFrontendApplication { 38 | private static final Logger log = LoggerFactory.getLogger(BlueOrGreenFrontendApplication.class); 39 | 40 | @Autowired 41 | RestTemplate rest; 42 | 43 | @Value("${removeTypeCookie:true}") 44 | private boolean removeTypeCookie; 45 | 46 | public static void main(String[] args) { 47 | SpringApplication.run(BlueOrGreenFrontendApplication.class, args); 48 | } 49 | 50 | private final static Pattern pattern = Pattern.compile(" *; *"); 51 | 52 | @RequestMapping("/color") 53 | public String color(HttpServletRequest request, HttpServletResponse response) throws URISyntaxException { 54 | String cookies = request.getHeader("cookie"); 55 | MultiValueMap headers = new LinkedMultiValueMap<>(); 56 | if (removeTypeCookie) { 57 | cookies = removeCookie(cookies, "type"); 58 | } 59 | if (cookies != null && cookies.length() > 0) { 60 | headers.set("cookie", cookies); 61 | } 62 | 63 | RequestEntity requestEntity = new RequestEntity(headers, HttpMethod.GET, new URI("http://blueorgreengateway/blueorgreen")); 64 | ResponseEntity responseEntity = rest.exchange(requestEntity, String.class); 65 | if(responseEntity.getStatusCode().value() == HttpStatus.TOO_MANY_REQUESTS.value()) { 66 | log.warn("Too many requests"); 67 | response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); 68 | return ""; 69 | } else { 70 | return responseEntity.getBody(); 71 | } 72 | } 73 | 74 | @Component 75 | protected static class RateLimitErrorHandler extends DefaultResponseErrorHandler { 76 | 77 | @Override 78 | public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException { 79 | if(clientHttpResponse.getStatusCode().value() == HttpStatus.TOO_MANY_REQUESTS.value()) { 80 | return false; 81 | } else { 82 | return super.hasError(clientHttpResponse); 83 | } 84 | } 85 | } 86 | 87 | @Configuration 88 | protected static class RestTemplateConfig { 89 | 90 | @LoadBalanced 91 | @Bean 92 | public RestTemplate rest(RateLimitErrorHandler rateLimitErrorHandler) { 93 | return new RestTemplateBuilder().errorHandler(rateLimitErrorHandler).build(); 94 | } 95 | } 96 | 97 | private String removeCookie(String cookies, String cookieName) { 98 | String newCookies = ""; 99 | if(cookies != null) { 100 | log.info("Got cookies: {}", cookies); 101 | String[] tokens = pattern.split(cookies); 102 | for(String token : tokens) { 103 | if (!token.substring(0, token.indexOf("=")).equals(cookieName)) { 104 | if (newCookies.length() > 0) { 105 | newCookies = newCookies.concat(" ; "); 106 | } 107 | newCookies = newCookies.concat(token); 108 | } 109 | } 110 | log.info("Processed cookies: {}", newCookies); 111 | } 112 | return newCookies; 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /blueorgreenfrontend/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: blueorgreenfrontend 4 | cloud: 5 | services: 6 | registrationMethod: direct 7 | server: 8 | port: 9090 9 | 10 | security: 11 | basic: 12 | enabled: false 13 | 14 | eureka: 15 | client: 16 | serviceUrl: 17 | defaultZone: http://localhost:8761/eureka/ 18 | instance: 19 | leaseRenewalIntervalInSeconds: 10 20 | metadataMap: 21 | instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${server.port}}} 22 | 23 | #removeTypeCookie: false -------------------------------------------------------------------------------- /blueorgreenfrontend/src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Blue Or Green 5 | 6 | 19 | 47 | 48 | 49 | 50 |
51 |

{{color.id}}

52 |
53 | 54 | -------------------------------------------------------------------------------- /blueorgreenfrontend/src/test/java/org/springframework/demo/BlueOrGreenFrontendApplicationTests.java: -------------------------------------------------------------------------------- 1 | package org.springframework.demo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class BlueOrGreenFrontendApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /blueorgreengateway/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /blueorgreengateway/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ryanjbaxter/gateway-s1p-2018/68cc10b09823fbc0cfb90735e2df82f35a749fff/blueorgreengateway/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /blueorgreengateway/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip 2 | -------------------------------------------------------------------------------- /blueorgreengateway/manifest.yml: -------------------------------------------------------------------------------- 1 | --- 2 | applications: 3 | - name: blueorgreengateway 4 | memory: 1024M 5 | path: target/blueorgreengateway-0.0.1-SNAPSHOT.jar 6 | timeout: 60 7 | services: 8 | - bluegreen-registry -------------------------------------------------------------------------------- /blueorgreengateway/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /blueorgreengateway/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /blueorgreengateway/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.demo 7 | blueorgreengateway 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | blueorgreengateway 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.5.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Finchley.BUILD-SNAPSHOT 26 | 2.0.1.RELEASE 27 | 28 | 29 | 30 | 31 | org.springframework.cloud 32 | spring-cloud-starter-gateway 33 | 34 | 35 | org.springframework.cloud 36 | spring-cloud-starter-netflix-eureka-client 37 | 38 | 39 | io.pivotal.spring.cloud 40 | spring-cloud-services-starter-service-registry 41 | 42 | 43 | org.springframework.cloud 44 | spring-cloud-starter-netflix-hystrix 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-security 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-actuator 53 | 54 | 55 | io.micrometer 56 | micrometer-registry-prometheus 57 | 58 | 59 | 60 | org.springframework.boot 61 | spring-boot-starter-test 62 | test 63 | 64 | 65 | 66 | 67 | 68 | 69 | org.springframework.cloud 70 | spring-cloud-dependencies 71 | ${spring-cloud.version} 72 | pom 73 | import 74 | 75 | 76 | io.pivotal.spring.cloud 77 | spring-cloud-services-dependencies 78 | ${scs.version} 79 | pom 80 | import 81 | 82 | 83 | 84 | 85 | 86 | 87 | spring-snapshots 88 | Spring Snapshots 89 | https://repo.spring.io/libs-snapshot 90 | 91 | true 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | org.springframework.boot 100 | spring-boot-maven-plugin 101 | 102 | 103 | 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /blueorgreengateway/src/main/java/org/springframework/demo/blueorgreengateway/BlueorgreengatewayApplication.java: -------------------------------------------------------------------------------- 1 | package org.springframework.demo.blueorgreengateway; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import org.springframework.boot.SpringApplication; 6 | import org.springframework.boot.autoconfigure.SpringBootApplication; 7 | import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; 8 | import org.springframework.cloud.gateway.filter.LoadBalancerClientFilter; 9 | import org.springframework.cloud.gateway.route.RouteLocator; 10 | import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | import org.springframework.security.config.web.server.ServerHttpSecurity; 14 | import org.springframework.security.web.server.SecurityWebFilterChain; 15 | import org.springframework.web.bind.annotation.RequestMapping; 16 | import org.springframework.web.bind.annotation.RestController; 17 | 18 | @SpringBootApplication 19 | @RestController 20 | public class BlueorgreengatewayApplication { 21 | 22 | public static void main(String[] args) { 23 | SpringApplication.run(BlueorgreengatewayApplication.class, args); 24 | } 25 | 26 | @Bean 27 | public RouteLocator routeLocator(RouteLocatorBuilder builder) { 28 | return builder.routes() 29 | .route(p -> p.path("/blueorgreen").uri("lb://blueorgreen")) 30 | .route(p -> p.path("/").or().path("/color").or().path("/js/**").uri("lb://blueorgreenfrontend")) 31 | .build(); 32 | } 33 | 34 | @Bean 35 | public LoadBalancerClientFilter loadBalancerClientFilter(LoadBalancerClient client) { 36 | return new CustomLoadBalancerClientFilter(client); 37 | } 38 | 39 | @Configuration 40 | public class SecurityConfig { 41 | 42 | @Bean 43 | public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { 44 | http.requestCache().disable().authorizeExchange().anyExchange().permitAll(); 45 | return http.build(); 46 | } 47 | } 48 | 49 | @RequestMapping("/colorfallback") 50 | public Map fallbackColor() { 51 | Map map = new HashMap<>(); 52 | map.put("id", "red"); 53 | return map; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /blueorgreengateway/src/main/java/org/springframework/demo/blueorgreengateway/CustomLoadBalancerClientFilter.java: -------------------------------------------------------------------------------- 1 | package org.springframework.demo.blueorgreengateway; 2 | 3 | import java.net.URI; 4 | import java.util.List; 5 | import org.apache.commons.logging.Log; 6 | import org.apache.commons.logging.LogFactory; 7 | import org.springframework.cloud.client.ServiceInstance; 8 | import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; 9 | import org.springframework.cloud.gateway.filter.LoadBalancerClientFilter; 10 | import org.springframework.http.HttpCookie; 11 | import org.springframework.util.MultiValueMap; 12 | import org.springframework.web.server.ServerWebExchange; 13 | 14 | import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR; 15 | 16 | /** 17 | * @author Ryan Baxter 18 | */ 19 | public class CustomLoadBalancerClientFilter extends LoadBalancerClientFilter { 20 | 21 | private static final Log log = LogFactory.getLog(LoadBalancerClientFilter.class); 22 | 23 | public CustomLoadBalancerClientFilter(LoadBalancerClient loadBalancer) { 24 | super(loadBalancer); 25 | } 26 | 27 | @Override 28 | protected ServiceInstance choose(ServerWebExchange exchange) { 29 | if("blueorgreen".equals(((URI) exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR)).getHost())) { 30 | MultiValueMap cookies = exchange.getRequest().getCookies(); 31 | log.warn("cookie: " + exchange.getRequest().getHeaders().get("cookie")); 32 | if (!cookies.containsKey("type") || !"premium".equals(cookies.getFirst("type").getValue())) { 33 | long future = System.currentTimeMillis() + 3000; 34 | while (System.currentTimeMillis() < future) { 35 | ServiceInstance instance = super.choose(exchange); 36 | if (instance != null && (instance.getMetadata() == null || instance.getMetadata().get("type") == null || 37 | !"premium".equals(instance.getMetadata().get("type").toLowerCase()))) { 38 | return instance; 39 | } 40 | } 41 | return null; 42 | } 43 | } 44 | return super.choose(exchange); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /blueorgreengateway/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | 2 | eureka: 3 | client: 4 | serviceUrl: 5 | defaultZone: http://localhost:8761/eureka/ 6 | instance: 7 | leaseRenewalIntervalInSeconds: 10 8 | metadataMap: 9 | instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${server.port}}} 10 | spring: 11 | application: 12 | name: blueorgreengateway 13 | logging: 14 | level: 15 | org: 16 | springframework: 17 | cloud: 18 | gateway: DEBUG 19 | server: 20 | port: 8383 21 | 22 | management: 23 | endpoints: 24 | web: 25 | exposure: 26 | include: "*" 27 | base-path: /manage 28 | 29 | -------------------------------------------------------------------------------- /blueorgreengateway/src/test/java/org/springframework/demo/blueorgreengateway/BlueorgreengatewayApplicationTests.java: -------------------------------------------------------------------------------- 1 | package org.springframework.demo.blueorgreengateway; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class BlueorgreengatewayApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /blueorgreenservice/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /blueorgreenservice/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ryanjbaxter/gateway-s1p-2018/68cc10b09823fbc0cfb90735e2df82f35a749fff/blueorgreenservice/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /blueorgreenservice/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip 2 | -------------------------------------------------------------------------------- /blueorgreenservice/manifest.yml: -------------------------------------------------------------------------------- 1 | --- 2 | applications: 3 | - name: blueservice 4 | memory: 1024M 5 | path: target/blueorgreen-0.0.1-SNAPSHOT.jar 6 | timeout: 60 7 | services: 8 | - bluegreen-registry 9 | env: 10 | SPRING_PROFILES_ACTIVE: blue 11 | no-route: true 12 | - name: greenservice 13 | memory: 1024M 14 | path: target/blueorgreen-0.0.1-SNAPSHOT.jar 15 | timeout: 60 16 | services: 17 | - bluegreen-registry 18 | env: 19 | SPRING_PROFILES_ACTIVE: green 20 | no-route: true 21 | - name: yellowservice 22 | memory: 1024M 23 | path: target/blueorgreen-0.0.1-SNAPSHOT.jar 24 | timeout: 60 25 | services: 26 | - bluegreen-registry 27 | env: 28 | SPRING_PROFILES_ACTIVE: yellow 29 | no-route: true -------------------------------------------------------------------------------- /blueorgreenservice/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /blueorgreenservice/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /blueorgreenservice/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.test 7 | blueorgreen 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | blueorgreen 12 | Blue Green Deployment Demo 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.16.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Edgware.SR4 26 | 1.6.4.RELEASE 27 | 28 | 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-web 34 | 35 | 36 | org.springframework.cloud 37 | spring-cloud-starter-eureka 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-actuator 42 | 43 | 44 | io.pivotal.spring.cloud 45 | spring-cloud-services-starter-service-registry 46 | 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-test 51 | test 52 | 53 | 54 | org.springframework.cloud 55 | spring-cloud-starter-contract-verifier 56 | test 57 | 58 | 59 | 60 | 61 | 62 | spring-snapshots 63 | Spring Snapshots 64 | https://repo.spring.io/snapshot 65 | 66 | true 67 | 68 | 69 | 70 | spring-milestones 71 | Spring Milestones 72 | https://repo.spring.io/milestone 73 | 74 | false 75 | 76 | 77 | 78 | spring-releases 79 | Spring Releases 80 | https://repo.spring.io/release 81 | 82 | false 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | org.springframework.cloud 91 | spring-cloud-dependencies 92 | ${spring-cloud.version} 93 | pom 94 | import 95 | 96 | 97 | io.pivotal.spring.cloud 98 | spring-cloud-services-dependencies 99 | ${scs.version} 100 | pom 101 | import 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | org.springframework.boot 110 | spring-boot-maven-plugin 111 | 112 | 113 | org.springframework.cloud 114 | spring-cloud-contract-maven-plugin 115 | 1.2.1.RELEASE 116 | true 117 | 118 | org.springframework.demo.base 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | -------------------------------------------------------------------------------- /blueorgreenservice/src/main/java/org/springframework/demo/BlueOrGreenApplication.java: -------------------------------------------------------------------------------- 1 | package org.springframework.demo; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 7 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @SpringBootApplication 12 | @EnableDiscoveryClient 13 | @EnableConfigurationProperties(ColorProperties.class) 14 | public class BlueOrGreenApplication { 15 | 16 | public static void main(String[] args) { 17 | SpringApplication.run(BlueOrGreenApplication.class, args); 18 | } 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /blueorgreenservice/src/main/java/org/springframework/demo/ColorController.java: -------------------------------------------------------------------------------- 1 | package org.springframework.demo; 2 | 3 | import org.springframework.web.bind.annotation.RequestMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | /** 7 | * @author Ryan Baxter 8 | */ 9 | @RestController 10 | public class ColorController { 11 | 12 | private ColorProperties colorProperties; 13 | 14 | public ColorController(ColorProperties colorProperties) { 15 | this.colorProperties = colorProperties; 16 | } 17 | 18 | @RequestMapping 19 | public Color color() throws InterruptedException { 20 | if(colorProperties.isSlow()) { 21 | Thread.sleep(5000); 22 | } 23 | if(Color.BLUE.getId().equalsIgnoreCase(colorProperties.getColor())) { 24 | return Color.BLUE; 25 | } else if(Color.YELLOW.getId().equalsIgnoreCase(colorProperties.getColor())) { 26 | return Color.YELLOW; 27 | } 28 | return Color.GREEN; 29 | } 30 | 31 | static class Color { 32 | public static final Color GREEN = new Color("green"); 33 | public static final Color BLUE = new Color("blue"); 34 | public static final Color YELLOW = new Color("yellow"); 35 | private String id; 36 | 37 | public Color(){} 38 | 39 | public Color(String id) { this.id = id; } 40 | 41 | public String getId() { 42 | return id; 43 | } 44 | 45 | public void setId(String id) { 46 | this.id = id; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /blueorgreenservice/src/main/java/org/springframework/demo/ColorProperties.java: -------------------------------------------------------------------------------- 1 | package org.springframework.demo; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | /** 6 | * @author Ryan Baxter 7 | */ 8 | @ConfigurationProperties 9 | public class ColorProperties { 10 | 11 | private String color; 12 | 13 | private boolean slow = false; 14 | 15 | public boolean isSlow() { 16 | return slow; 17 | } 18 | 19 | public void setSlow(boolean slow) { 20 | this.slow = slow; 21 | } 22 | 23 | public String getColor() { 24 | return color; 25 | } 26 | 27 | public void setColor(String color) { 28 | this.color = color; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /blueorgreenservice/src/main/resources/application-blue.yml: -------------------------------------------------------------------------------- 1 | color: blue 2 | server: 3 | port: 8181 -------------------------------------------------------------------------------- /blueorgreenservice/src/main/resources/application-green.yml: -------------------------------------------------------------------------------- 1 | color: green 2 | server: 3 | port: 7070 -------------------------------------------------------------------------------- /blueorgreenservice/src/main/resources/application-slowgreen.yml: -------------------------------------------------------------------------------- 1 | color: green 2 | slow: true 3 | server: 4 | port: 6060 -------------------------------------------------------------------------------- /blueorgreenservice/src/main/resources/application-yellow.yml: -------------------------------------------------------------------------------- 1 | color: yellow 2 | server: 3 | port: 8282 4 | eureka: 5 | instance: 6 | metadataMap: 7 | type: premium -------------------------------------------------------------------------------- /blueorgreenservice/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: blueorgreen 4 | cloud: 5 | services: 6 | registrationMethod: direct 7 | 8 | 9 | eureka: 10 | client: 11 | serviceUrl: 12 | defaultZone: http://localhost:8761/eureka/ 13 | instance: 14 | leaseRenewalIntervalInSeconds: 10 15 | metadataMap: 16 | instanceId: ${vcap.application.instance_id:${spring.application.name}:${spring.application.instance_id:${server.port}}} 17 | # Initially launch the service with the status of OUT_OF_SERVICE 18 | # initial-status: out_of_service 19 | 20 | management: 21 | security: 22 | enabled: false 23 | 24 | security: 25 | basic: 26 | enabled: false 27 | server: 28 | port: 7070 -------------------------------------------------------------------------------- /blueorgreenservice/src/test/java/org/springframework/demo/BlueApplicationTests.java: -------------------------------------------------------------------------------- 1 | package org.springframework.demo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.boot.test.web.client.TestRestTemplate; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | import static org.junit.Assert.assertEquals; 11 | 12 | @RunWith(SpringRunner.class) 13 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {"color:blue", "eureka.client.enabled: false"}) 14 | public class BlueApplicationTests { 15 | 16 | @Autowired 17 | private TestRestTemplate rest; 18 | 19 | @Test 20 | public void contextLoads() { 21 | ColorController.Color color = rest.getForObject("/", ColorController.Color.class); 22 | assertEquals("blue", color.getId()); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /blueorgreenservice/src/test/java/org/springframework/demo/GreenApplicationTests.java: -------------------------------------------------------------------------------- 1 | package org.springframework.demo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.boot.test.web.client.TestRestTemplate; 8 | import org.springframework.test.context.junit4.SpringRunner; 9 | 10 | import static org.junit.Assert.assertEquals; 11 | 12 | /** 13 | * @author Ryan Baxter 14 | */ 15 | @RunWith(SpringRunner.class) 16 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {"color:green", "eureka.client.enabled: false"}) 17 | public class GreenApplicationTests { 18 | @Autowired 19 | private TestRestTemplate rest; 20 | 21 | @Test 22 | public void contextLoads() { 23 | ColorController.Color color = rest.getForObject("/", ColorController.Color.class); 24 | assertEquals("green", color.getId()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /blueorgreenservice/src/test/java/org/springframework/demo/base/ColorBase.java: -------------------------------------------------------------------------------- 1 | package org.springframework.demo.base; 2 | 3 | import io.restassured.module.mockmvc.RestAssuredMockMvc; 4 | 5 | import org.junit.Before; 6 | import org.springframework.demo.BlueOrGreenApplication; 7 | import org.springframework.demo.ColorController; 8 | import org.springframework.demo.ColorProperties; 9 | 10 | /** 11 | * @author Ryan Baxter 12 | */ 13 | public class ColorBase { 14 | 15 | @Before 16 | public void setup() { 17 | ColorProperties colorProperties = new ColorProperties(); 18 | colorProperties.setColor("blue"); 19 | RestAssuredMockMvc.standaloneSetup(new ColorController(colorProperties)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /blueorgreenservice/src/test/resources/contracts/color/shouldReturnColor.groovy: -------------------------------------------------------------------------------- 1 | package contracts.color 2 | 3 | import org.springframework.cloud.contract.spec.Contract 4 | 5 | Contract.make { 6 | request { 7 | method 'GET' 8 | url '/' 9 | headers { 10 | } 11 | } 12 | response { 13 | status 200 14 | body("{\"id\": \"blue\"}") 15 | headers { 16 | contentType(applicationJson()) 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | cd blueorgreenservice 2 | ./mvnw clean package 3 | cf push 4 | cd ../ 5 | cd blueorgreenfrontend 6 | ./mvnw clean package 7 | cf push 8 | cd ../ 9 | cd blueorgreengateway 10 | ./mvnw clean package 11 | cf push 12 | cd ../ 13 | 14 | #Add network policies 15 | cf add-network-policy blueorgreengateway --destination-app greenservice --protocol tcp --port 8080 16 | cf add-network-policy blueorgreengateway --destination-app blueservice --protocol tcp --port 8080 17 | cf add-network-policy blueorgreengateway --destination-app yellowservice --protocol tcp --port 8080 18 | cf add-network-policy blueorgreengateway --destination-app blueorgreenfrontend --protocol tcp --port 8080 19 | -------------------------------------------------------------------------------- /route-service-broker/.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | 5 | ### STS ### 6 | .apt_generated 7 | .classpath 8 | .factorypath 9 | .project 10 | .settings 11 | .springBeans 12 | .sts4-cache 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### NetBeans ### 21 | /nbproject/private/ 22 | /build/ 23 | /nbbuild/ 24 | /dist/ 25 | /nbdist/ 26 | /.nb-gradle/ 27 | 28 | out/ 29 | -------------------------------------------------------------------------------- /route-service-broker/00_deploy.sh: -------------------------------------------------------------------------------- 1 | # CLEANUP 2 | 3 | cf urs cfapps.io subscription-gateway --hostname cool-app -f 4 | cf unmap-route cool-app cfapps.io --hostname cool-app 5 | 6 | cf urs cfapps.io subscription-gateway --hostname appgateway -f 7 | #cf unmap-route appgateway cfapps.io --hostname appgateway 8 | 9 | cf ds subscription-gateway -f 10 | 11 | cf delete-service-broker route-service -f 12 | 13 | #cf d route-service-broker -f 14 | #cf ds route-service-mongodb -f 15 | #cf ds route-service-redis -f 16 | 17 | cf delete-orphaned-routes -f 18 | 19 | # DEPLOY 20 | 21 | #cd ~/workspace/route-service-broker-thumbnail 22 | #cf push 23 | 24 | cd ~/workspace/route-service-broker 25 | ./gradlew assemble 26 | #cf cs mlab sandbox route-service-mongodb 27 | #cf cs rediscloud 30mb route-service-redis 28 | cf push 29 | 30 | # RECONFIGURE 31 | 32 | cf create-service-broker route-service admin supersecret https://route-service-broker.cfapps.io --space-scoped 33 | 34 | cf cs route-service standard subscription-gateway 35 | 36 | cf map-route cool-app cfapps.io --hostname cool-app 37 | cf brs cfapps.io subscription-gateway --hostname cool-app 38 | 39 | #cf map-route appgateway cfapps.io --hostname appgateway 40 | cf brs cfapps.io subscription-gateway --hostname appgateway 41 | -------------------------------------------------------------------------------- /route-service-broker/README.adoc: -------------------------------------------------------------------------------- 1 | = Overview 2 | 3 | This project implements a sample service broker that adheres to the https://www.openservicebrokerapi.org/[Open Service Broker API] using the https://cloud.spring.io/spring-cloud-open-service-broker/[Spring Cloud Open Service Broker] framework. It can be deployed to Cloud Foundry and registered as a service broker. 4 | 5 | This sample was inspired by a https://medium.com/@fitzoh/creating-a-cloud-foundry-route-service-with-spring-cloud-gateway-2dcabf04540e[blog post] by https://github.com/Fitzoh[Andrew Fitzgerald] and a https://github.com/making/gateway-route-service[sample app] by https://github.com/making[Toshiaki Maki]. 6 | 7 | == Compatibility 8 | 9 | * https://projects.spring.io/spring-framework/[Spring Framework] 5.x 10 | * https://projects.spring.io/spring-boot/[Spring Boot] 2.x 11 | * https://cloud.spring.io/spring-cloud-open-service-broker/[Spring Cloud Open Service Broker] 2.0.0.BUILD-SNAPSHOT 12 | * https://cloud.spring.io/spring-cloud-gateway/[Spring Cloud Gateway] 2.0.0.RC1 13 | 14 | == Getting Started 15 | 16 | This service broker implements a Cloud Foundry https://docs.cloudfoundry.org/services/route-services.html[route service]. 17 | When a service instance is bound to an application, the route service will log all requests to the bound application and optionally provide rate limiting to the application. 18 | 19 | == Build 20 | 21 | This project requires Java 8 at a minimum. 22 | 23 | The project is built with Gradle. The https://docs.gradle.org/current/userguide/gradle_wrapper.html[Gradle wrapper] allows you to build the project on multiple platforms and even if you do not have Gradle installed; run it in place of the `gradle` command (as `./gradlew`) from the root of the main project directory. 24 | 25 | === To compile the project and run tests 26 | 27 | ./gradlew build 28 | 29 | == Deploy 30 | 31 | Once the project is built, it can be deployed and registered to Cloud Foundry. 32 | 33 | * link:deploy/cloudfoundry/README.adoc[deploy to Cloud Foundry] 34 | 35 | == Working with the code 36 | If you don't have an IDE preference we would recommend that you use 37 | http://www.springsource.com/developer/sts[Spring Tools Suite] or 38 | http://eclipse.org[Eclipse] when working with the code. We use the 39 | http://eclipse.org/m2e/[m2eclipse] eclipse plugin for maven support. Other IDEs and tools 40 | should also work without issue as long as they use Maven 3.3.3 or better. 41 | 42 | == Contributing 43 | 44 | Spring Cloud is released under the non-restrictive Apache 2.0 license, 45 | and follows a very standard Github development process, using Github 46 | tracker for issues and merging pull requests into master. If you want 47 | to contribute even something trivial please do not hesitate, but 48 | follow the guidelines below. 49 | 50 | === Sign the Contributor License Agreement 51 | Before we accept a non-trivial patch or pull request we will need you to sign the 52 | https://cla.pivotal.io/sign/spring[Contributor License Agreement]. 53 | Signing the contributor's agreement does not grant anyone commit rights to the main 54 | repository, but it does mean that we can accept your contributions, and you will get an 55 | author credit if we do. Active contributors might be asked to join the core team, and 56 | given the ability to merge pull requests. 57 | 58 | === Code of Conduct 59 | This project adheres to the Contributor Covenant link:/CODE_OF_CONDUCT.adoc[code of 60 | conduct]. By participating, you are expected to uphold this code. Please report 61 | unacceptable behavior to spring-code-of-conduct@pivotal.io. 62 | 63 | === Code Conventions and Housekeeping 64 | None of these is essential for a pull request, but they will all help. They can also be 65 | added after the original pull request but before a merge. 66 | 67 | * Use the Spring Framework code format conventions. If you use Eclipse 68 | you can import formatter settings using the 69 | `eclipse-code-formatter.xml` file from the 70 | https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml[Spring 71 | Cloud Build] project. If using IntelliJ, you can use the 72 | http://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter 73 | Plugin] to import the same file. 74 | * Make sure all new `.java` files to have a simple Javadoc class comment with at least an 75 | `@author` tag identifying you, and preferably at least a paragraph on what the class is 76 | for. 77 | * Add the ASF license header comment to all new `.java` files (copy from existing files 78 | in the project) 79 | * Add yourself as an `@author` to the .java files that you modify substantially (more 80 | than cosmetic changes). 81 | * Add some Javadocs and, if you change the namespace, some XSD doc elements. 82 | * A few unit tests would help a lot as well -- someone has to do it. 83 | * If no-one else is using your branch, please rebase it against the current master (or 84 | other target branch in the main project). 85 | * When writing a commit message please follow http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions], 86 | if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit 87 | message (where XXXX is the issue number). 88 | -------------------------------------------------------------------------------- /route-service-broker/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '2.0.1.RELEASE' 4 | } 5 | repositories { 6 | mavenCentral() 7 | } 8 | dependencies { 9 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 10 | } 11 | } 12 | 13 | apply plugin: 'maven-publish' 14 | apply plugin: 'java' 15 | apply plugin: 'eclipse' 16 | apply plugin: 'org.springframework.boot' 17 | apply plugin: 'io.spring.dependency-management' 18 | apply from: 'gradle/pipeline.gradle' 19 | 20 | group = 'io.pivotal' 21 | version = getProp('newVersion') ?: '0.0.1.BUILD-SNAPSHOT' 22 | sourceCompatibility = 1.8 23 | 24 | repositories { 25 | mavenCentral() 26 | maven { url "https://repo.spring.io/snapshot" } 27 | } 28 | 29 | ext['spring-security.version'] = '5.1.0.RELEASE' 30 | ext { 31 | springCloudVersion = 'Finchley.SR1' 32 | projectGroupId = project.group 33 | projectArtifactId = project.name 34 | projectVersion = project.version 35 | } 36 | 37 | dependencyManagement { 38 | imports { 39 | mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" 40 | } 41 | } 42 | 43 | dependencies { 44 | compile('org.springframework.boot:spring-boot-starter-webflux') 45 | compile('org.springframework.boot:spring-boot-starter-actuator') 46 | compile('org.springframework.boot:spring-boot-starter-security') 47 | 48 | compile('org.springframework.cloud:spring-cloud-starter-gateway') 49 | compile('org.springframework.cloud:spring-cloud-starter-open-service-broker:3.0.0.BUILD-SNAPSHOT') 50 | 51 | compile('org.springframework.boot:spring-boot-starter-cloud-connectors') 52 | compile('org.springframework.boot:spring-boot-starter-data-redis-reactive') 53 | compile('org.springframework.boot:spring-boot-starter-data-mongodb') 54 | compile('org.apache.commons:commons-pool2:2.2') 55 | compile('io.micrometer:micrometer-registry-prometheus') 56 | compileOnly('org.projectlombok:lombok') 57 | compileOnly ("org.springframework.boot:spring-boot-configuration-processor") 58 | 59 | testCompile('org.springframework.boot:spring-boot-starter-test') 60 | testCompile('io.projectreactor:reactor-test') 61 | testCompile('org.springframework.security:spring-security-test') 62 | } 63 | 64 | publishing { 65 | repositories { 66 | maven { 67 | url getProp('REPO_WITH_BINARIES_FOR_UPLOAD') ?: 'http://localhost:8081/artifactory/libs-release-local' 68 | credentials { 69 | username getProp('M2_SETTINGS_REPO_USERNAME') ?: 'admin' 70 | password getProp('M2_SETTINGS_REPO_PASSWORD') ?: 'password' 71 | } 72 | } 73 | } 74 | publications { 75 | mavenJava(MavenPublication) { 76 | artifactId project.name 77 | from components.java 78 | } 79 | } 80 | } 81 | 82 | String getProp(String propName) { 83 | return hasProperty(propName) ? 84 | (getProperty(propName) ?: System.properties[propName]) : System.properties[propName] ?: 85 | System.getenv(propName) 86 | } 87 | -------------------------------------------------------------------------------- /route-service-broker/deploy/cloudfoundry/README.adoc: -------------------------------------------------------------------------------- 1 | = Deploy to Cloud Foundry 2 | 3 | This document contains instructions for deploying the sample service broker to a Cloud Foundry foundation. 4 | 5 | All instructions below assume that the commands are being run from the root of the project repository. 6 | 7 | = Prerequisites 8 | 9 | == Cloud Foundry CLI 10 | 11 | These instructions use the `cf` CLI to interact with a running Cloud Foundry foundation. 12 | Follow the https://docs.cloudfoundry.org/cf-cli/[`cf` documentation] to install and verify the CLI. 13 | 14 | == Cloud Foundry foundation 15 | 16 | A Cloud Foundry foundation will be used to deploy the service broker application and register it to the service marketplace. 17 | This can be a public hosted Cloud Foundry, a private Cloud Foundry, or a workstation-deployed Cloud Foundry like https://github.com/cloudfoundry-incubator/cfdev[CF Dev] or https://pivotal.io/pcf-dev[PCF Dev]. 18 | 19 | Use the `cf` CLI to https://docs.cloudfoundry.org/cf-cli/getting-started.html#login[log into] Cloud Foundry and target an organization and space for deployment of an application. 20 | 21 | = Build the service broker application 22 | 23 | The Gradle build file for the service broker sample project can be used to build the application. 24 | 25 | ---- 26 | $ ./gradlew assemble 27 | ---- 28 | 29 | = Deploy and test the service broker 30 | 31 | == Deploy the service broker application 32 | 33 | Deploy the service broker application to Cloud Foundry: 34 | 35 | ---- 36 | $ cf push -f deploy/cloudfoundry/manifest.yml 37 | Pushing from manifest to org sample / space test as user@example.com... 38 | Using manifest file deploy/cloudfoundry/manifest.yml 39 | Getting app info... 40 | Creating app with these attributes... 41 | + name: route-service-broker 42 | path: build/libs/route-service-broker-0.0.1.BUILD-SNAPSHOT.jar 43 | + memory: 1G 44 | routes: 45 | + route-service-broker.apps.example.com 46 | 47 | ... 48 | 49 | name: route-service-broker 50 | requested state: started 51 | instances: 1/1 52 | usage: 1G x 1 instances 53 | routes: route-service-broker.apps.example.com 54 | 55 | ... 56 | 57 | state since cpu memory disk details 58 | #0 running 2018-02-13T21:58:44Z 0.0% 290.8M of 1G 144.7M of 1G 59 | ---- 60 | 61 | == Verify the service broker application 62 | 63 | Note the value of the `route` row in the output from the command above. 64 | Use this route to build a URL to access the `/v2/catalog` endpoint of the service broker application. 65 | 66 | ---- 67 | $ curl https://route-service-broker.apps.example.com/v2/catalog -u admin:supersecret 68 | {"services":[{"id":"d897c845-e15e-467e-9c34-71632e8807e1","name":"route-logger","description":"A simple route logging service","bindable":true,"plan_updateable":false,"instances_retrievable":false,"bindings_retrievable":false,"plans":[{"id":"3944a61c-ed68-45c5-b649-a99d1f301c69","name":"standard","description":"A simple plan","metadata":{},"bindable":true,"free":true}],"tags":["route-service","logging"],"metadata":{},"requires":["route_forwarding"]}]} 69 | ---- 70 | 71 | = Register and test the service broker 72 | 73 | == Register to the services marketplace 74 | 75 | Now that the application has been deployed and verified, it can be registered to the Cloud Foundry services marketplace. 76 | 77 | === With administrator privileges 78 | 79 | If you have administrator privileges on Cloud Foundry, you can make the service broker available in all organizations and spaces. 80 | 81 | The Open Service Broker API endpoints in the service broker application are secured with a basic auth username and password. 82 | Register the service broker using the URL from above and the credentials: 83 | 84 | ---- 85 | $ cf create-service-broker route-service admin supersecret https://route-service-broker.apps.example.com 86 | Creating service broker route-service as admin... 87 | OK 88 | ---- 89 | 90 | Make the service offerings from the service broker visible in the services marketplace: 91 | 92 | ---- 93 | $ cf enable-service-access route-service 94 | Enabling access to all plans of service route-service for all orgs as admin... 95 | OK 96 | ---- 97 | 98 | === Without administrator privileges 99 | 100 | If you do not have administrator privileges on Cloud Foundry, you can make the service broker available in a single organization and space that you have privileges in: 101 | 102 | ---- 103 | $ cf create-service-broker route-service admin supersecret https://route-service-broker.apps.example.com --space-scoped 104 | Creating service broker route-service in org sample / space test as user@example.com... 105 | OK 106 | ---- 107 | 108 | == View to the services marketplace 109 | 110 | Show the services marketplace: 111 | 112 | ---- 113 | $ cf marketplace 114 | Getting services from marketplace in org sample / space test as user@example.com... 115 | OK 116 | 117 | service plans description 118 | route-service standard A simple route logging service 119 | 120 | TIP: Use 'cf marketplace -s SERVICE' to view descriptions of individual plans of a given service. 121 | ---- 122 | 123 | ---- 124 | $ cf marketplace -s route-service 125 | Getting service plan information for service route-service as user@example.com... 126 | OK 127 | 128 | service plan description free or paid 129 | standard A simple plan free 130 | ---- 131 | 132 | = Use the service broker 133 | 134 | == Create a service instance 135 | 136 | Create an instance of a route service from the sample service broker: 137 | 138 | ---- 139 | $ cf create-service route-service standard my-route-service 140 | Creating service instance my-route-service in org sample / space test as user@example.com... 141 | OK 142 | ---- 143 | 144 | Show the details of the created service instance: 145 | 146 | ---- 147 | $ cf service my-route-service 148 | Showing info of service my-route-service in org sample / space test as user@example.com... 149 | 150 | name: route-service 151 | service: my-route-service 152 | tags: 153 | plan: standard 154 | description: A simple route logging service 155 | documentation: 156 | dashboard: 157 | 158 | There are no bound apps for this service. 159 | 160 | Showing status of last operation from service my-route-service... 161 | 162 | status: create succeeded 163 | message: 164 | ---- 165 | 166 | == Bind the service instance to an application 167 | 168 | Push any application to Cloud Foundry and bind a route to it. 169 | The examples below assume that the domain `apps.example.com` exists in Cloud Foundry, and that the application has a route `appname.apps.example.com` bound to it. 170 | 171 | Bind the service instance to the application: 172 | 173 | ---- 174 | $ cf bind-route-service apps.example.com my-route-service --hostname appname 175 | Binding route appname.apps.example.com to service instance my-route-service in org sample / space test as user@example.com... 176 | OK 177 | ---- 178 | 179 | Send any request to the application that the service instance is bound to: 180 | ---- 181 | $ curl https://appname.apps.example.com 182 | ---- 183 | 184 | View the logs of the service broker to verify that it intercepted the request to the application and logged it: 185 | 186 | ---- 187 | $ cf logs route-service-broker --recent 188 | Retrieving logs for app route-service-broker in org sample / space test as user@example.com... 189 | ... 190 | 2018-04-25T13:04:56.77-0500 [APP/PROC/WEB/0] OUT 2018-04-25 18:04:56.773 INFO 15 --- [ctor-http-nio-3] o.s.c.s.r.f.LoggingGatewayFilterFactory : Forwarding request: method=GET, headers={Host=[route-service-broker.apps.example.com], User-Agent=[curl/7.54.0], Accept=[*/*], X-B3-Spanid=[409cc4b017fb5936], X-B3-Traceid=[409cc4b017fb5936], X-Cf-Applicationid=[292e5ec7-0608-4c0d-b5fb-de83f9377446], X-Cf-Forwarded-Url=[https://appname.apps.example.com/actuator/info], X-Cf-Instanceid=[2452da9e-04c2-4077-5d0a-5a42], X-Cf-Instanceindex=[0], X-Cf-Proxy-Metadata=[eyJub25jZSI6InRNY1JtMGVQcGN5ZlNNNFEifQ==], X-Cf-Proxy-Signature=[yD8H40mQkoJwXMMChhRJXrwGv0346YQrLsHdeWw8C7cIRC-F2I5AJEsdRh9QtHFnwIq_mHavUUsVXtsVEiWOFUDBnZaXtC_JtisumCtLelsNQj3ytgbhezzqiUOScyv-wc1jxw9HT0EjcRhFNEE1-hoxF26bFVFNWSXuj4D7BY2wnDUdgpVQmrOo1wKs7GIue3I89WPfCMR3EnY5oHQ9], X-Forwarded-For=[192.168.1.1, 192.168.1.97, 127.0.0.1], X-Forwarded-Host=[appname.apps.example.com], X-Forwarded-Proto=[https], X-Forwarded-Server=[cf.example.com], X-Request-Start=[1524679496744], X-Vcap-Request-Id=[17782e7c-d307-4556-7c35-d1b21b2fc38b]}, url=https://appname.apps.example.com 191 | 2018-04-25T13:04:56.87-0500 [APP/PROC/WEB/0] OUT 2018-04-25 18:04:56.872 INFO 15 --- [ctor-http-nio-1] o.s.c.s.r.f.LoggingGatewayFilterFactory : Response: method=GET, headers={Host=[route-service-broker.apps.example.com], User-Agent=[curl/7.54.0], Accept=[*/*], X-B3-Spanid=[409cc4b017fb5936], X-B3-Traceid=[409cc4b017fb5936], X-Cf-Applicationid=[292e5ec7-0608-4c0d-b5fb-de83f9377446], X-Cf-Forwarded-Url=[https://appname.apps.example.com/actuator/info], X-Cf-Instanceid=[2452da9e-04c2-4077-5d0a-5a42], X-Cf-Instanceindex=[0], X-Cf-Proxy-Metadata=[eyJub25jZSI6InRNY1JtMGVQcGN5ZlNNNFEifQ==], X-Cf-Proxy-Signature=[yD8H40mQkoJwXMMChhRJXrwGv0346YQrLsHdeWw8C7cIRC-F2I5AJEsdRh9QtHFnwIq_mHavUUsVXtsVEiWOFUDBnZaXtC_JtisumCtLelsNQj3ytgbhezzqiUOScyv-wc1jxw9HT0EjcRhFNEE1-hoxF26bFVFNWSXuj4D7BY2wnDUdgpVQmrOo1wKs7GIue3I89WPfCMR3EnY5oHQ9], X-Forwarded-For=[192.168.1.1, 192.168.1.97, 127.0.0.1], X-Forwarded-Host=[appname.apps.example.com], X-Forwarded-Proto=[https], X-Forwarded-Server=[cf.example.com], X-Request-Start=[1524679496744], X-Vcap-Request-Id=[17782e7c-d307-4556-7c35-d1b21b2fc38b]}, url=https://appname.apps.example.com 192 | ... 193 | ---- 194 | -------------------------------------------------------------------------------- /route-service-broker/gradle/pipeline.gradle: -------------------------------------------------------------------------------- 1 | // TODO: Consider moving these to a plugin: 2 | 3 | test { 4 | description = "Task to run unit and integration tests" 5 | testLogging { 6 | exceptionFormat = 'full' 7 | } 8 | jvmArgs = systemPropsFromGradle() 9 | exclude 'smoke/**' 10 | exclude 'e2e/**' 11 | } 12 | 13 | task smoke(type: Test) { 14 | description = "Task to run smoke tests" 15 | testLogging { 16 | exceptionFormat = 'full' 17 | } 18 | jvmArgs = systemPropsFromGradle() 19 | include 'smoke/**' 20 | } 21 | 22 | task apiCompatibility(type: Test) { 23 | description = "Task to run api compatbility tests" 24 | testLogging { 25 | exceptionFormat = 'full' 26 | } 27 | jvmArgs = systemPropsFromGradle() 28 | include '**/contracttests/**' 29 | } 30 | 31 | task e2e(type: Test) { 32 | description = "Task to run end to end tests" 33 | testLogging { 34 | exceptionFormat = 'full' 35 | } 36 | jvmArgs = systemPropsFromGradle() 37 | include 'e2e/**' 38 | } 39 | 40 | task deploy(dependsOn: 'publish') { 41 | description = "Abstraction over publishing artifacts to Artifactory / Nexus" 42 | } 43 | 44 | task groupId { 45 | doLast { 46 | println projectGroupId 47 | } 48 | } 49 | groupId.description = "Task to retrieve Group ID" 50 | 51 | task artifactId { 52 | doLast { 53 | println projectArtifactId 54 | } 55 | } 56 | artifactId.description = "Task to retrieve Artifact ID" 57 | 58 | task currentVersion { 59 | doLast { 60 | println projectVersion 61 | } 62 | } 63 | currentVersion.description = "Task to retrieve version" 64 | 65 | task stubIds { 66 | doLast { 67 | println stubrunnerIds 68 | } 69 | } 70 | stubIds.description = "Task to retrieve Stub Runner IDS" 71 | 72 | [test, apiCompatibility, smoke, e2e, deploy, groupId, artifactId, currentVersion, stubIds].each { 73 | it.group = "Pipeline" 74 | } 75 | 76 | private List systemPropsFromGradle() { 77 | return project.gradle.startParameter.systemPropertiesArgs.entrySet().collect { "-D${it.key}=${it.value}" } 78 | } -------------------------------------------------------------------------------- /route-service-broker/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ryanjbaxter/gateway-s1p-2018/68cc10b09823fbc0cfb90735e2df82f35a749fff/route-service-broker/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /route-service-broker/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Apr 24 13:44:53 CDT 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-all.zip 7 | -------------------------------------------------------------------------------- /route-service-broker/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /route-service-broker/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /route-service-broker/manifest.yml: -------------------------------------------------------------------------------- 1 | --- 2 | applications: 3 | - name: route-service-broker 4 | memory: 1G 5 | path: build/libs/route-service-broker-0.0.1.BUILD-SNAPSHOT.jar 6 | buildpack: java_buildpack 7 | services: 8 | - route-service-mongodb 9 | - route-service-redis 10 | 11 | -------------------------------------------------------------------------------- /route-service-broker/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'route-service-broker' 2 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/ServiceBrokerApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.sample.routeservice; 18 | 19 | import org.springframework.boot.SpringApplication; 20 | import org.springframework.boot.autoconfigure.SpringBootApplication; 21 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 22 | import org.springframework.cloud.sample.routeservice.servicebroker.ServiceCatalogConfig; 23 | 24 | @SpringBootApplication 25 | @EnableConfigurationProperties(value={ServiceCatalogConfig.class}) 26 | public class ServiceBrokerApplication { 27 | 28 | public static void main(String[] args) { 29 | SpringApplication.run(ServiceBrokerApplication.class, args); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/config/HeaderFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.sample.routeservice.config; 18 | 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | import org.springframework.http.server.reactive.ServerHttpRequest; 22 | import org.springframework.web.server.ServerWebExchange; 23 | import org.springframework.web.server.WebFilter; 24 | import org.springframework.web.server.WebFilterChain; 25 | import org.springframework.web.util.UriComponentsBuilder; 26 | import reactor.core.publisher.Mono; 27 | 28 | import static org.springframework.cloud.gateway.handler.predicate.CloudFoundryRouteServiceRoutePredicateFactory.X_CF_FORWARDED_URL; 29 | 30 | 31 | /** 32 | * Cloud foundry routes to a different URL than the actual request being processed. The 33 | * request being processed is stored at X_CF_FORWARDED_URL. Since we want Spring Security 34 | * to act like it is within the application, this filter mutates the 35 | * {@link ServerWebExchange} to appear as though it is running within the application. 36 | * After Spring Security is done with the request the {@link UndoHeaderFilter} resets 37 | * the original request but with current principal. 38 | * 39 | * @author Rob Winch 40 | */ 41 | public class HeaderFilter implements WebFilter { 42 | private final Logger log = LoggerFactory.getLogger(HeaderFilter.class); 43 | 44 | public static final String ORIGINAL = "ORIGINAL_EXCHANGE"; 45 | 46 | @Override 47 | public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { 48 | ServerHttpRequest request = exchange.getRequest(); 49 | String url = request.getHeaders().getFirst(X_CF_FORWARDED_URL); 50 | log.info("Url: {}", url); 51 | if (url == null) { 52 | return chain.filter(exchange); 53 | } 54 | String path = UriComponentsBuilder.fromHttpUrl(url).build().getPath(); 55 | log.info("Path: {}", path); 56 | ServerHttpRequest modified = request.mutate() 57 | .path(path) 58 | .build(); 59 | ServerWebExchange modifiedExchange = exchange.mutate().request(modified).build(); 60 | modifiedExchange.getAttributes().put(ORIGINAL, exchange); 61 | return chain.filter(modifiedExchange); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/config/RoleTypeWebFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.sample.routeservice.config; 18 | 19 | import org.springframework.http.HttpCookie; 20 | import org.springframework.http.HttpHeaders; 21 | import org.springframework.security.core.Authentication; 22 | import org.springframework.security.core.GrantedAuthority; 23 | import org.springframework.web.server.ServerWebExchange; 24 | import org.springframework.web.server.WebFilter; 25 | import org.springframework.web.server.WebFilterChain; 26 | import reactor.core.publisher.Mono; 27 | 28 | import java.util.Collection; 29 | import java.util.function.Consumer; 30 | 31 | /** 32 | * Communicates to end applications what type of user is requesting the application via 33 | * a cookie named type. 34 | * 35 | * @author Rob Winch 36 | */ 37 | public class RoleTypeWebFilter implements WebFilter { 38 | 39 | @Override 40 | public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { 41 | // @formatter:off 42 | firewall(exchange); 43 | return exchange.getPrincipal() 44 | .cast(Authentication.class) 45 | .map(Authentication::getAuthorities) 46 | .filter(this::isPremium) 47 | .map(a -> withType("premium", exchange)) 48 | .defaultIfEmpty(exchange) 49 | .flatMap(chain::filter); 50 | // @formatter:on 51 | } 52 | 53 | private void firewall(ServerWebExchange exchange) { 54 | HttpCookie typeCookie = exchange.getRequest() 55 | .getCookies() 56 | .getFirst("type"); 57 | if (typeCookie != null) { 58 | throw new IllegalStateException("Malicious client tried to include Cookie named type"); 59 | } 60 | } 61 | 62 | private boolean isPremium(Collection authorities) { 63 | // @formatter:off 64 | return authorities 65 | .stream() 66 | .anyMatch(a -> "ROLE_PREMIUM".equalsIgnoreCase(a.getAuthority())); 67 | // @formatter:on 68 | } 69 | 70 | private ServerWebExchange withType(String role, ServerWebExchange exchange) { 71 | // @formatter:off 72 | return exchange.mutate() 73 | .request(r -> r.headers(withTypeCookie(role))) 74 | .build(); 75 | // @formatter:on 76 | } 77 | 78 | private Consumer withTypeCookie(String role) { 79 | return h -> { 80 | String cookieValue = h.getFirst(HttpHeaders.COOKIE); 81 | if (cookieValue == null) { 82 | cookieValue = "type=" + role; 83 | } else { 84 | cookieValue += " ; type=" + role; 85 | } 86 | h.set(HttpHeaders.COOKIE, cookieValue); 87 | }; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/config/RouteConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.sample.routeservice.config; 18 | 19 | import org.springframework.boot.autoconfigure.AutoConfigureBefore; 20 | import org.springframework.cloud.gateway.config.GatewayAutoConfiguration; 21 | import org.springframework.cloud.gateway.filter.GatewayFilter; 22 | import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; 23 | import org.springframework.cloud.gateway.handler.predicate.CloudFoundryRouteServiceRoutePredicateFactory; 24 | import org.springframework.cloud.gateway.route.RouteLocator; 25 | import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; 26 | import org.springframework.cloud.sample.routeservice.filter.LoggingGatewayFilterFactory; 27 | import org.springframework.cloud.sample.routeservice.filter.SubscriptionHandlerGatewayFilterFactory; 28 | import org.springframework.cloud.sample.routeservice.servicebroker.RateLimiters; 29 | import org.springframework.context.annotation.Bean; 30 | import org.springframework.context.annotation.Configuration; 31 | import org.springframework.web.server.ServerWebExchange; 32 | 33 | import java.util.function.Predicate; 34 | 35 | import static org.springframework.cloud.gateway.handler.predicate.CloudFoundryRouteServiceRoutePredicateFactory.X_CF_FORWARDED_URL; 36 | 37 | @Configuration 38 | @AutoConfigureBefore(GatewayAutoConfiguration.class) 39 | public class RouteConfiguration { 40 | 41 | @Bean 42 | public Predicate cloudFoundryPredicate() { 43 | return new CloudFoundryRouteServiceRoutePredicateFactory().apply(config -> {}); 44 | } 45 | 46 | @Bean 47 | public GatewayFilter logger() { 48 | return new LoggingGatewayFilterFactory().apply(config -> {}); 49 | } 50 | 51 | @Bean 52 | public RateLimiters rateLimiters() { return new RateLimiters();} 53 | 54 | @Bean 55 | public GatewayFilter subscriptionRateLimiter(KeyResolver resolver) { 56 | return new SubscriptionHandlerGatewayFilterFactory(rateLimiters(), resolver).apply(config -> {}); 57 | } 58 | 59 | 60 | @Bean 61 | public RouteLocator customRouteLocator(RouteLocatorBuilder builder, KeyResolver resolver) { 62 | return builder.routes() 63 | .route(r -> r 64 | .path("/instanceId/{instanceId}") 65 | .and() 66 | .predicate(cloudFoundryPredicate()) 67 | .filters(f -> { f 68 | .filter(logger()) 69 | .filter(subscriptionRateLimiter(resolver)) 70 | .requestHeaderToRequestUri(X_CF_FORWARDED_URL); 71 | return f; 72 | }) 73 | .uri("no://op")) 74 | .build(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/config/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.sample.routeservice.config; 18 | 19 | import org.springframework.boot.actuate.autoconfigure.security.reactive.EndpointRequest; 20 | import org.springframework.context.annotation.Bean; 21 | import org.springframework.context.annotation.Configuration; 22 | import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; 23 | import org.springframework.security.config.web.server.SecurityWebFiltersOrder; 24 | import org.springframework.security.config.web.server.ServerHttpSecurity; 25 | import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; 26 | import org.springframework.security.core.userdetails.User; 27 | import org.springframework.security.core.userdetails.UserDetails; 28 | import org.springframework.security.web.server.SecurityWebFilterChain; 29 | 30 | @Configuration 31 | @EnableWebFluxSecurity 32 | public class SecurityConfiguration { 33 | 34 | @Bean 35 | public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { 36 | // @formatter:off 37 | http 38 | .addFilterAt(new HeaderFilter(), SecurityWebFiltersOrder.FIRST) 39 | .addFilterAt(new UndoHeaderFilter(), SecurityWebFiltersOrder.LAST) 40 | .addFilterAt(new RoleTypeWebFilter(), SecurityWebFiltersOrder.LAST) 41 | .csrf().disable() 42 | .authorizeExchange() 43 | .pathMatchers("/v2/**").hasRole("ADMIN") 44 | .matchers(EndpointRequest.to("info", "health")).permitAll() 45 | .matchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN") 46 | .pathMatchers("/images/**").permitAll() 47 | .anyExchange().authenticated() 48 | .and() 49 | .formLogin() 50 | .and() 51 | .httpBasic(); 52 | // @formatter:on 53 | return http.build(); 54 | } 55 | 56 | @Bean 57 | public MapReactiveUserDetailsService userDetailsService() { 58 | // @formatter:off 59 | User.UserBuilder builder = User.withDefaultPasswordEncoder(); 60 | UserDetails admin = builder.username("admin") 61 | .password("supersecret") 62 | .roles("ADMIN") 63 | .build(); 64 | UserDetails trial = builder.username("trial") 65 | .password("pw") 66 | .roles("TRIAL") 67 | .build(); 68 | UserDetails basic = builder.username("basic") 69 | .password("pw") 70 | .roles("BASIC") 71 | .build(); 72 | UserDetails premium = builder.username("premium") 73 | .password("pw") 74 | .roles("PREMIUM") 75 | .build(); 76 | // @formatter:on 77 | return new MapReactiveUserDetailsService(admin, trial, premium, basic); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/config/ServiceConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.sample.routeservice.config; 18 | 19 | import org.springframework.cloud.config.java.ServiceScan; 20 | import org.springframework.context.annotation.Configuration; 21 | import org.springframework.context.annotation.Profile; 22 | 23 | @Configuration 24 | @ServiceScan 25 | @Profile("cloud") 26 | public class ServiceConfiguration { 27 | } 28 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/config/UndoHeaderFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.sample.routeservice.config; 18 | 19 | import org.springframework.web.server.ServerWebExchange; 20 | import org.springframework.web.server.WebFilter; 21 | import org.springframework.web.server.WebFilterChain; 22 | import reactor.core.publisher.Mono; 23 | 24 | /** 25 | * Resets to the original {@link ServerWebExchange} but modifies the principal to 26 | * the currently logged in user. 27 | * 28 | * @author Rob Winch 29 | */ 30 | public class UndoHeaderFilter implements WebFilter { 31 | @Override 32 | public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { 33 | ServerWebExchange original = exchange.getAttribute(HeaderFilter.ORIGINAL); 34 | if (original != null) { 35 | exchange = original.mutate() 36 | .principal(exchange.getPrincipal()) 37 | .build(); 38 | } 39 | return chain.filter(exchange); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/filter/LoggingGatewayFilterFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.sample.routeservice.filter; 18 | 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | import org.springframework.cloud.gateway.filter.GatewayFilter; 22 | import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; 23 | import org.springframework.http.server.reactive.ServerHttpRequest; 24 | import org.springframework.stereotype.Component; 25 | import org.springframework.web.server.ServerWebExchange; 26 | import org.springframework.web.util.pattern.PathPattern.PathMatchInfo; 27 | 28 | import java.net.URI; 29 | import java.net.URISyntaxException; 30 | import java.util.List; 31 | import java.util.Map; 32 | 33 | import static org.springframework.cloud.gateway.handler.predicate.CloudFoundryRouteServiceRoutePredicateFactory.X_CF_FORWARDED_URL; 34 | import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE; 35 | 36 | @Component 37 | public class LoggingGatewayFilterFactory extends AbstractGatewayFilterFactory { 38 | private final Logger log = LoggerFactory.getLogger(LoggingGatewayFilterFactory.class); 39 | 40 | @Override 41 | public GatewayFilter apply(Object config) { 42 | return (exchange, chain) -> { 43 | 44 | ServerHttpRequest request = exchange.getRequest(); 45 | 46 | String serviceInstanceId = getServiceInstanceId(exchange); 47 | 48 | URI forwardedUrl = getForwardedUrl(request); 49 | 50 | log.info("Forwarding request: serviceInstanceId={}, method={}, headers={}, url={}", 51 | serviceInstanceId, 52 | request.getMethod(), 53 | request.getHeaders(), 54 | forwardedUrl); 55 | 56 | return chain.filter(exchange) 57 | .doOnSuccess(x -> log.info("Response: serviceInstanceId={}, method={}, headers={}, url={}", 58 | serviceInstanceId, 59 | request.getMethod(), 60 | request.getHeaders(), 61 | forwardedUrl)) 62 | .doOnError(e -> log.error("Error: exception={}, serviceInstanceId={}, method={}, headers={}, url={}", 63 | e, 64 | serviceInstanceId, 65 | request.getMethod(), 66 | request.getHeaders(), 67 | forwardedUrl)); 68 | }; 69 | } 70 | 71 | private String getServiceInstanceId(ServerWebExchange exchange) { 72 | PathMatchInfo uriVariablesAttr = exchange.getAttribute(URI_TEMPLATE_VARIABLES_ATTRIBUTE); 73 | Map uriVariables = uriVariablesAttr.getUriVariables(); 74 | return uriVariables.get("instanceId"); 75 | } 76 | 77 | private URI getForwardedUrl(ServerHttpRequest request) { 78 | List headers = request.getHeaders().get(X_CF_FORWARDED_URL); 79 | if (headers == null || headers.isEmpty()) { 80 | log.warn("No " + X_CF_FORWARDED_URL + " header in request"); 81 | return null; 82 | } 83 | 84 | String forwardedUrl = headers.get(0); 85 | try { 86 | return new URI(forwardedUrl); 87 | } catch (URISyntaxException e) { 88 | log.warn("Invalid value for " + X_CF_FORWARDED_URL + " header: " + forwardedUrl); 89 | return null; 90 | } 91 | } 92 | } -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/filter/SubscriptionHandlerGatewayFilterFactory.java: -------------------------------------------------------------------------------- 1 | package org.springframework.cloud.sample.routeservice.filter; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.cloud.gateway.filter.GatewayFilter; 6 | import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; 7 | import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; 8 | import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; 9 | import org.springframework.cloud.gateway.route.Route; 10 | import org.springframework.cloud.gateway.support.ServerWebExchangeUtils; 11 | import org.springframework.cloud.sample.routeservice.servicebroker.RateLimiters; 12 | import org.springframework.http.HttpStatus; 13 | import org.springframework.security.core.Authentication; 14 | import org.springframework.security.core.GrantedAuthority; 15 | import org.springframework.stereotype.Component; 16 | import org.springframework.web.server.ServerWebExchange; 17 | import org.springframework.web.util.pattern.PathPattern.PathMatchInfo; 18 | import reactor.core.publisher.Flux; 19 | 20 | import java.util.Map; 21 | 22 | import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE; 23 | 24 | @Component 25 | public class SubscriptionHandlerGatewayFilterFactory extends AbstractGatewayFilterFactory { 26 | private final Logger log = LoggerFactory.getLogger(SubscriptionHandlerGatewayFilterFactory.class); 27 | 28 | private RateLimiters rateLimiters; 29 | 30 | private KeyResolver resolver; 31 | 32 | public SubscriptionHandlerGatewayFilterFactory(RateLimiters rateLimiters, KeyResolver resolver) { 33 | this.rateLimiters = rateLimiters; 34 | this.resolver = resolver; 35 | } 36 | 37 | @SuppressWarnings("unchecked") 38 | @Override 39 | public GatewayFilter apply(Object config) { 40 | return (exchange, chain) -> { 41 | 42 | String serviceId = getServiceInstanceId(exchange); 43 | 44 | return getUserRole(exchange).single().flatMap(role -> { 45 | log.info("User role: {}", role.getAuthority()); 46 | // TODO: If limiter is null (e.g. no premium plan was defined), default to trial? Currently line "limiter.isAllowed" below throws NullPointerException 47 | RedisRateLimiter limiter = rateLimiters.getLimiter(serviceId.concat(role.getAuthority().substring(4))); 48 | 49 | Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR); 50 | 51 | return resolver.resolve(exchange).flatMap(key -> 52 | { 53 | log.info("Key: {}", key); 54 | return limiter.isAllowed(route.getId(), key).flatMap(response -> { 55 | for (Map.Entry header : response.getHeaders().entrySet()) { 56 | exchange.getResponse().getHeaders().add(header.getKey(), header.getValue()); 57 | } 58 | 59 | if (response.isAllowed()) { 60 | return chain.filter(exchange); 61 | } 62 | 63 | exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); 64 | return exchange.getResponse().setComplete(); 65 | }); 66 | }); 67 | }); 68 | }; 69 | } 70 | 71 | private String getServiceInstanceId(ServerWebExchange exchange) { 72 | PathMatchInfo uriVariablesAttr = exchange.getAttribute(URI_TEMPLATE_VARIABLES_ATTRIBUTE); 73 | Map uriVariables = uriVariablesAttr.getUriVariables(); 74 | return uriVariables.get("instanceId"); 75 | } 76 | 77 | private Flux getUserRole(ServerWebExchange exchange) { 78 | return exchange.getPrincipal().cast(Authentication.class).flatMapIterable(a -> a.getAuthorities()); 79 | } 80 | 81 | 82 | } 83 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/servicebroker/RateLimiters.java: -------------------------------------------------------------------------------- 1 | package org.springframework.cloud.sample.routeservice.servicebroker; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.BeansException; 6 | import org.springframework.beans.factory.InitializingBean; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; 9 | import org.springframework.cloud.sample.routeservice.servicebroker.ServiceCatalogConfig.Plan; 10 | import org.springframework.context.ApplicationContext; 11 | import org.springframework.context.ApplicationContextAware; 12 | import org.springframework.stereotype.Component; 13 | 14 | import java.util.HashMap; 15 | import java.util.List; 16 | import java.util.Map; 17 | 18 | @Component 19 | public class RateLimiters implements ApplicationContextAware, InitializingBean { 20 | private final Logger log = LoggerFactory.getLogger(RateLimiters.class); 21 | 22 | public Map redisRateLimiterMap; 23 | 24 | private ApplicationContext applicationContext; 25 | 26 | @Autowired 27 | private ServiceInstanceRepository serviceInstanceRepository; 28 | 29 | @Autowired 30 | ServiceCatalogConfig serviceCatalogConfig; 31 | 32 | public RateLimiters() { 33 | redisRateLimiterMap = new HashMap(); 34 | } 35 | 36 | public RedisRateLimiter getLimiter(String instanceId) { 37 | return redisRateLimiterMap.get(instanceId); 38 | } 39 | 40 | public void addLimiter(String serviceInstanceId, String serviceDefinitionId, String planId) { 41 | 42 | List plans = serviceCatalogConfig.getServices().stream() 43 | .filter(s -> s.getId().equals(serviceDefinitionId)) 44 | .findFirst().get() 45 | .getPlans(); 46 | 47 | Plan plan = plans.stream() 48 | .filter(p -> p.getId().equals(planId)) 49 | .findFirst().get(); 50 | 51 | plan.getConfigs().forEach(config -> { 52 | String name = config.getName().name(); 53 | int replenishRate = config.getReplenishRate(); 54 | int burstCapacity = config.getBurstCapacity(); 55 | RedisRateLimiter rrl = new RedisRateLimiter(replenishRate, burstCapacity); 56 | rrl.setApplicationContext(applicationContext); 57 | redisRateLimiterMap.put(serviceInstanceId.concat("_" + name.toUpperCase()), rrl); 58 | log.info("RateLimiters size = {}", redisRateLimiterMap.size()); 59 | 60 | }); 61 | } 62 | 63 | public void removeLimiter(String instanceId) { 64 | redisRateLimiterMap.remove(instanceId); 65 | log.info("RateLimiters size = {}", redisRateLimiterMap.size()); 66 | } 67 | 68 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException 69 | { 70 | this.applicationContext = applicationContext; 71 | } 72 | 73 | @Override 74 | public void afterPropertiesSet() { 75 | // load map from repo 76 | serviceInstanceRepository.findAll().forEach(e -> addLimiter(e.getServiceInstanceId(), e.getServiceDefinitionId(), e.getPlanId())); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/servicebroker/RouteLoggingServiceBindingService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.sample.routeservice.servicebroker; 18 | 19 | import org.springframework.beans.factory.annotation.Value; 20 | import org.springframework.cloud.servicebroker.model.binding.*; 21 | import org.springframework.cloud.servicebroker.service.ServiceInstanceBindingService; 22 | import org.springframework.stereotype.Service; 23 | import org.springframework.web.util.DefaultUriBuilderFactory; 24 | import reactor.core.publisher.Mono; 25 | 26 | import java.net.URI; 27 | 28 | @Service 29 | public class RouteLoggingServiceBindingService implements ServiceInstanceBindingService { 30 | @Value("${vcap.application.uris[0]:localhost}") 31 | private String appRoute; 32 | 33 | @Override 34 | public Mono createServiceInstanceBinding(CreateServiceInstanceBindingRequest request) { 35 | URI uri = new DefaultUriBuilderFactory().builder() 36 | .scheme("https") 37 | .host(appRoute) 38 | .pathSegment("instanceId", request.getServiceInstanceId()) 39 | .build(); 40 | 41 | return Mono.just(CreateServiceInstanceRouteBindingResponse.builder() 42 | .routeServiceUrl(uri.toString()) 43 | .build()); 44 | } 45 | 46 | @Override 47 | public Mono deleteServiceInstanceBinding(DeleteServiceInstanceBindingRequest request) { 48 | return Mono.just(DeleteServiceInstanceBindingResponse.builder().build()); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/servicebroker/RouteLoggingServiceInstanceService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.sample.routeservice.servicebroker; 18 | 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | import org.springframework.cloud.servicebroker.model.instance.CreateServiceInstanceRequest; 22 | import org.springframework.cloud.servicebroker.model.instance.CreateServiceInstanceResponse; 23 | import org.springframework.cloud.servicebroker.model.instance.DeleteServiceInstanceRequest; 24 | import org.springframework.cloud.servicebroker.model.instance.DeleteServiceInstanceResponse; 25 | import org.springframework.cloud.servicebroker.service.ServiceInstanceService; 26 | import org.springframework.stereotype.Service; 27 | import reactor.core.publisher.Mono; 28 | 29 | @Service 30 | public class RouteLoggingServiceInstanceService implements ServiceInstanceService { 31 | private final Logger log = LoggerFactory.getLogger(ServiceInstanceService.class); 32 | 33 | ServiceInstanceRepository serviceInstanceRepository; 34 | 35 | RateLimiters rateLimiters; 36 | 37 | public RouteLoggingServiceInstanceService(ServiceInstanceRepository serviceInstanceRepository, RateLimiters rateLimiters ) { 38 | this.serviceInstanceRepository = serviceInstanceRepository; 39 | this.rateLimiters = rateLimiters; 40 | } 41 | 42 | @Override 43 | public Mono createServiceInstance(CreateServiceInstanceRequest request) { 44 | 45 | ServiceInstance serviceInstance = ServiceInstance.builder() 46 | .serviceInstanceId(request.getServiceInstanceId()) 47 | .serviceDefinitionId(request.getServiceDefinitionId()) 48 | .planId(request.getPlanId()) 49 | // .logLevel((String)request.getParameters().get("log-level")) 50 | .build(); 51 | 52 | log.info("Received create-service request: {}", serviceInstance.toString()); 53 | 54 | serviceInstanceRepository.save(serviceInstance); 55 | 56 | log.info("Saved new service instance info [serviceInstanceId={}].", serviceInstance.getServiceInstanceId()); 57 | log.info("Service instance count: {}", serviceInstanceRepository.count()); 58 | if (log.isInfoEnabled()) { 59 | serviceInstanceRepository.findAll().forEach(System.out::println); 60 | } 61 | 62 | rateLimiters.addLimiter(serviceInstance.getServiceInstanceId(), serviceInstance.getServiceDefinitionId(), serviceInstance.getPlanId()); 63 | 64 | return Mono.just(CreateServiceInstanceResponse.builder() 65 | .instanceExisted(false) 66 | .build()); 67 | } 68 | 69 | 70 | @Override 71 | public Mono deleteServiceInstance(DeleteServiceInstanceRequest request) { 72 | 73 | String serviceInstanceId = request.getServiceInstanceId(); 74 | 75 | log.info("Received delete-service request: {}", serviceInstanceId); 76 | 77 | serviceInstanceRepository.deleteById(serviceInstanceId); 78 | 79 | log.info("Deleted service instance info [serviceInstanceId={}].", serviceInstanceId); 80 | log.info("Service instance count: {}", serviceInstanceRepository.count()); 81 | 82 | rateLimiters.removeLimiter(serviceInstanceId); 83 | 84 | return Mono.just(DeleteServiceInstanceResponse.builder() 85 | .build()); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/servicebroker/ServiceCatalogConfig.java: -------------------------------------------------------------------------------- 1 | package org.springframework.cloud.sample.routeservice.servicebroker; 2 | 3 | import lombok.Getter; 4 | import lombok.NoArgsConstructor; 5 | import lombok.Setter; 6 | import org.springframework.boot.context.properties.ConfigurationProperties; 7 | import org.springframework.data.annotation.Id; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | @ConfigurationProperties(prefix = "servicecatalogconfig") 13 | public class ServiceCatalogConfig { 14 | 15 | @Getter 16 | private List services; 17 | 18 | public enum Type { 19 | TRIAL, 20 | BASIC, 21 | PREMIUM; 22 | } 23 | 24 | ServiceCatalogConfig() { 25 | this.services = new ArrayList<>(); 26 | } 27 | 28 | @NoArgsConstructor 29 | static class Service { 30 | @Id 31 | @Getter 32 | @Setter 33 | private String id; 34 | @Getter 35 | @Setter 36 | private List plans; 37 | } 38 | 39 | @NoArgsConstructor 40 | static class Plan { 41 | @Id 42 | @Getter 43 | @Setter 44 | private String id; 45 | @Getter 46 | @Setter 47 | private List configs; 48 | } 49 | 50 | @NoArgsConstructor 51 | static class Config { 52 | @Id 53 | @Getter 54 | @Setter 55 | private Type name; 56 | @Getter 57 | @Setter 58 | private int replenishRate; 59 | @Getter 60 | @Setter 61 | private int burstCapacity; 62 | } 63 | 64 | } 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/servicebroker/ServiceInstance.java: -------------------------------------------------------------------------------- 1 | package org.springframework.cloud.sample.routeservice.servicebroker; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import org.springframework.data.annotation.Id; 7 | import org.springframework.data.mongodb.core.mapping.Document; 8 | 9 | @Document 10 | @AllArgsConstructor 11 | @NoArgsConstructor 12 | public class ServiceInstance { 13 | 14 | @Id 15 | @Getter 16 | private String serviceInstanceId; 17 | @Getter 18 | private String serviceDefinitionId; 19 | @Getter 20 | private String planId = null; 21 | // @Getter 22 | // private String logLevel = "INFO"; 23 | 24 | public static ServiceInstanceBuilder builder() { 25 | return new ServiceInstanceBuilder(); 26 | } 27 | 28 | @Override 29 | public String toString() { 30 | return "ServiceInstance{" + 31 | "serviceInstanceId='" + serviceInstanceId + '\'' + 32 | "serviceDefinitionId='" + serviceDefinitionId + '\'' + 33 | "planId='" + planId + '\'' + 34 | // ", logLevel='" + logLevel + '\'' + 35 | '}'; 36 | } 37 | 38 | @NoArgsConstructor 39 | static class ServiceInstanceBuilder { 40 | 41 | private String serviceInstanceId; 42 | private String serviceDefinitionId; 43 | private String planId; 44 | // private String logLevel; 45 | 46 | ServiceInstanceBuilder serviceInstanceId(String serviceInstanceId) { 47 | this.serviceInstanceId = serviceInstanceId; 48 | return this; 49 | } 50 | 51 | ServiceInstanceBuilder serviceDefinitionId(String serviceDefinitionId) { 52 | this.serviceDefinitionId = serviceDefinitionId; 53 | return this; 54 | } 55 | 56 | ServiceInstanceBuilder planId(String planId) { 57 | this.planId = planId; 58 | return this; 59 | } 60 | 61 | // ServiceInstanceBuilder logLevel(String logLevel) { 62 | // this.logLevel = logLevel; 63 | // return this; 64 | // } 65 | 66 | ServiceInstance build() { 67 | return new ServiceInstance(serviceInstanceId, serviceDefinitionId, planId); 68 | } 69 | 70 | } 71 | 72 | } 73 | 74 | -------------------------------------------------------------------------------- /route-service-broker/src/main/java/org/springframework/cloud/sample/routeservice/servicebroker/ServiceInstanceRepository.java: -------------------------------------------------------------------------------- 1 | package org.springframework.cloud.sample.routeservice.servicebroker; 2 | 3 | import org.springframework.data.mongodb.repository.MongoRepository; 4 | 5 | public interface ServiceInstanceRepository extends MongoRepository { 6 | } 7 | -------------------------------------------------------------------------------- /route-service-broker/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | cloud: 3 | openservicebroker: 4 | catalog: 5 | services: 6 | - id: d897c845-e15e-467e-9c34-71632e8807e1 7 | name: route-service 8 | description: Rate-limiting route service based on user role 9 | bindable: true 10 | requires: ["route_forwarding"] 11 | tags: 12 | - route-service 13 | - logging 14 | metadata: # optional 15 | imageUrl: https://${vcap.application.uris[0]}/images/service-broker-icon.png 16 | displayName: A S1P Demo Gateway Service 17 | longDescription: Spring Cloud Gateway service, intended to be bound as a route service. 18 | documentationUrl: https://docs.cloudfoundry.org/devguide/services/route-binding.html 19 | providerDisplayName: Pivotal 20 | plans: 21 | - id: 3944a61c-ed68-45c5-b649-a99d1f301c69 22 | name: standard 23 | description: standard plan 24 | free: true 25 | bindable: true 26 | metadata: 27 | displayName: Rate Limiter (Trial, Basic, and Premium) 28 | 29 | management: 30 | endpoints: 31 | web: 32 | exposure: 33 | include: "*" 34 | 35 | servicecatalogconfig: 36 | services: 37 | - id: d897c845-e15e-467e-9c34-71632e8807e1 38 | plans: 39 | - id: 3944a61c-ed68-45c5-b649-a99d1f301c69 40 | configs: 41 | - name: trial 42 | replenishRate: 5 43 | burstCapacity: 5 44 | - name: basic 45 | replenishRate: 10 46 | burstCapacity: 15 47 | - name: premium 48 | replenishRate: 50 49 | burstCapacity: 100 -------------------------------------------------------------------------------- /route-service-broker/src/main/resources/static/images/face-with-monocle-and-arrows.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ryanjbaxter/gateway-s1p-2018/68cc10b09823fbc0cfb90735e2df82f35a749fff/route-service-broker/src/main/resources/static/images/face-with-monocle-and-arrows.png -------------------------------------------------------------------------------- /route-service-broker/src/main/resources/static/images/face-with-monocle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ryanjbaxter/gateway-s1p-2018/68cc10b09823fbc0cfb90735e2df82f35a749fff/route-service-broker/src/main/resources/static/images/face-with-monocle.png -------------------------------------------------------------------------------- /route-service-broker/src/main/resources/static/images/service-broker-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ryanjbaxter/gateway-s1p-2018/68cc10b09823fbc0cfb90735e2df82f35a749fff/route-service-broker/src/main/resources/static/images/service-broker-icon.png -------------------------------------------------------------------------------- /route-service-broker/src/test/java/org/springframework/cloud/sample/routeservice/ServiceBrokerApplicationTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.sample.routeservice; 18 | 19 | import org.junit.Test; 20 | import org.junit.runner.RunWith; 21 | import org.springframework.boot.test.context.SpringBootTest; 22 | import org.springframework.test.context.junit4.SpringRunner; 23 | 24 | @RunWith(SpringRunner.class) 25 | @SpringBootTest 26 | public class ServiceBrokerApplicationTests { 27 | 28 | @Test 29 | public void contextLoads() { 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /route-service-broker/src/test/java/org/springframework/cloud/sample/routeservice/config/RoleTypeWebFilterTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-2018 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.springframework.cloud.sample.routeservice.config; 18 | 19 | import org.junit.Test; 20 | import org.springframework.http.HttpHeaders; 21 | import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter; 22 | import org.springframework.test.web.reactive.server.WebTestClient; 23 | import org.springframework.web.bind.annotation.GetMapping; 24 | import org.springframework.web.bind.annotation.RestController; 25 | import org.springframework.web.server.ServerWebExchange; 26 | 27 | import static org.assertj.core.api.Assertions.assertThat; 28 | import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockUser; 29 | import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; 30 | 31 | /** 32 | * @author Rob Winch 33 | */ 34 | public class RoleTypeWebFilterTests { 35 | 36 | private MockController controller = new MockController(); 37 | 38 | private RoleTypeWebFilter filter = new RoleTypeWebFilter(); 39 | 40 | private WebTestClient client = WebTestClient.bindToController(this.controller) 41 | .apply(springSecurity()) 42 | .webFilter(new SecurityContextServerWebExchangeWebFilter(), this.filter) 43 | .build(); 44 | 45 | @Test 46 | public void filterWhenMaliciousThenError() { 47 | this.client 48 | .get() 49 | .uri("/") 50 | .cookie("type", "premium") 51 | .exchange() 52 | .expectStatus().is5xxServerError(); 53 | 54 | assertThat(this.controller.exchange).isNull(); 55 | } 56 | 57 | @Test 58 | public void filterWhenNotAuthenticatedThenCookieValueIsNull() { 59 | this.client 60 | .mutateWith(mockUser("u")) 61 | .get() 62 | .uri("/") 63 | .exchange() 64 | .expectStatus().isOk(); 65 | 66 | assertThat(getCookieValue()).isNull(); 67 | } 68 | 69 | @Test 70 | public void filterWhenPremiumThenCookieValueIsPremium() { 71 | this.client 72 | .mutateWith(mockUser("u").roles("PREMIUM")) 73 | .get() 74 | .uri("/") 75 | .exchange() 76 | .expectStatus().isOk(); 77 | 78 | assertThat(getCookieValue()).isEqualTo("type=premium"); 79 | } 80 | 81 | @Test 82 | public void filterWhenPremiumAndExistingThenCookieValueAppendsPremium() { 83 | this.client 84 | .mutateWith(mockUser("u").roles("PREMIUM")) 85 | .get() 86 | .uri("/") 87 | .header(HttpHeaders.COOKIE, "a=b") 88 | .exchange() 89 | .expectStatus().isOk(); 90 | 91 | assertThat(getCookieValue()).isEqualTo("a=b ; type=premium"); 92 | } 93 | 94 | @Test 95 | public void filterWhenNotPremiumThenCookieValueIsNull() { 96 | this.client 97 | .mutateWith(mockUser("u").roles("NOT")) 98 | .get() 99 | .uri("/") 100 | .exchange() 101 | .expectStatus().isOk(); 102 | 103 | assertThat(getCookieValue()).isNull(); 104 | } 105 | 106 | private String getCookieValue() { 107 | return this.controller.exchange.getRequest().getHeaders().getFirst(HttpHeaders.COOKIE); 108 | } 109 | 110 | @RestController 111 | static class MockController { 112 | ServerWebExchange exchange; 113 | 114 | @GetMapping("/") 115 | String index(ServerWebExchange exchange) { 116 | this.exchange = exchange; 117 | return "mock"; 118 | } 119 | } 120 | 121 | } --------------------------------------------------------------------------------