diff --git a/README.md b/README.md index fbe9765..8a81382 100644 --- a/README.md +++ b/README.md @@ -51,8 +51,8 @@ dgate的主要特性: ## 开发指南 - git clone -- gradle shadowJar,生成dgate的fatjar -- gradle test,运行测试代码 +- ./gradlew shadowJar,生成dgate的fatjar +- ./gradlew test,运行测试代码 在发起Pull Request时,请同时提交测试代码,并保证现有测试代码【对于测试,我们推荐[Spock](http://spockframework.org/)】能全部通过,;)。 @@ -60,4 +60,4 @@ dgate的主要特性: 如果觉得我们的工具对您有帮助,可以考虑支持我们,;) -![情怀支持](docs/zanshang.jpg) \ No newline at end of file +![情怀支持](docs/zanshang.jpg) diff --git a/build.gradle b/build.gradle index 69df055..e44641b 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ buildscript { mavenCentral() } dependencies { - classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.0' + classpath 'com.github.jengelman.gradle.plugins:shadow:5.1.0' } } @@ -26,15 +26,15 @@ repositories { } dependencies { - compile "org.codehaus.groovy:groovy-all:${GROOVY_VER}" - compile "io.vertx:vertx-core:${VERTX_VER}" - compile "io.vertx:vertx-web:${VERTX_VER}" - compile "io.vertx:vertx-auth-jwt:${VERTX_VER}" - compile "io.vertx:vertx-circuit-breaker:${VERTX_VER}" - compile "io.vertx:vertx-ignite:${VERTX_VER}" - compile "ch.qos.logback:logback-classic:${LOGBACK_VER}" - - testCompile "org.spockframework:spock-core:${SPOCK_VER}" + implementation "org.codehaus.groovy:groovy:${GROOVY_VER}" + implementation "io.vertx:vertx-core:${VERTX_VER}" + implementation "io.vertx:vertx-web:${VERTX_VER}" + implementation "io.vertx:vertx-auth-jwt:${VERTX_VER}" + implementation "io.vertx:vertx-circuit-breaker:${VERTX_VER}" + implementation "io.vertx:vertx-ignite:${VERTX_VER}" + implementation "ch.qos.logback:logback-classic:${LOGBACK_VER}" + + testImplementation "org.spockframework:spock-core:${SPOCK_VER}" } version = '0.1.5' diff --git a/gradle.properties b/gradle.properties index 8648a6b..9ee8af4 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,4 +1,4 @@ -GROOVY_VER=2.4.12 -SPOCK_VER=1.1-groovy-2.4 -VERTX_VER=3.5.0 +GROOVY_VER=2.5.8 +SPOCK_VER=1.3-groovy-2.5 +VERTX_VER=3.8.4 LOGBACK_VER=1.2.3 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..5c2d1cf Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ef9a9e0 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.6-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..83f2acf --- /dev/null +++ b/gradlew @@ -0,0 +1,188 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..24467a1 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/groovy/top/dteam/dgate/config/LoginConfig.groovy b/src/main/groovy/top/dteam/dgate/config/LoginConfig.groovy index c06a356..c217915 100644 --- a/src/main/groovy/top/dteam/dgate/config/LoginConfig.groovy +++ b/src/main/groovy/top/dteam/dgate/config/LoginConfig.groovy @@ -6,7 +6,7 @@ import groovy.transform.CompileStatic class LoginConfig { static long DEFAULT_REFRESH_LIMIT = 30 * 60 - static long DEFAULT_REFRESH_EXPIRE = 30 * 60 + static int DEFAULT_REFRESH_EXPIRE = 30 * 60 private String url private Map config @@ -45,8 +45,8 @@ class LoginConfig { (long) (config?.refreshLimit ?: DEFAULT_REFRESH_LIMIT) } - long refreshExpire() { - (long) (config?.refreshExpire ?: DEFAULT_REFRESH_EXPIRE) + int refreshExpire() { + (int) (config?.refreshExpire ?: DEFAULT_REFRESH_EXPIRE) } } diff --git a/src/main/java/top/dteam/dgate/Launcher.java b/src/main/java/top/dteam/dgate/Launcher.java index 8a5837e..5a7f7a3 100644 --- a/src/main/java/top/dteam/dgate/Launcher.java +++ b/src/main/java/top/dteam/dgate/Launcher.java @@ -28,7 +28,7 @@ public static void main(String[] args) { public void beforeStartingVertx(VertxOptions options) { System.setProperty("IGNITE_NO_SHUTDOWN_HOOK", "true"); options.setClusterManager(new IgniteClusterManager(igniteConfiguration())); - options.setClustered(true); + options.getEventBusOptions().setClustered(true); } @Override diff --git a/src/main/java/top/dteam/dgate/gateway/ApiGateway.java b/src/main/java/top/dteam/dgate/gateway/ApiGateway.java index 5ba4f7a..cc81eb8 100644 --- a/src/main/java/top/dteam/dgate/gateway/ApiGateway.java +++ b/src/main/java/top/dteam/dgate/gateway/ApiGateway.java @@ -1,18 +1,18 @@ package top.dteam.dgate.gateway; import groovy.lang.Closure; +import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.EventBus; import io.vertx.core.eventbus.Message; +import io.vertx.core.http.HttpServer; import io.vertx.core.json.JsonObject; import io.vertx.ext.bridge.PermittedOptions; +import io.vertx.ext.web.Router; import io.vertx.ext.web.handler.sockjs.BridgeOptions; import io.vertx.ext.web.handler.sockjs.SockJSHandler; -import top.dteam.dgate.config.ApiGatewayConfig; -import io.vertx.core.AbstractVerticle; -import io.vertx.core.http.HttpServer; -import io.vertx.ext.web.Router; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import top.dteam.dgate.config.ApiGatewayConfig; import top.dteam.dgate.config.Consumer; import top.dteam.dgate.config.EventBusBridgeConfig; import top.dteam.dgate.config.Publisher; @@ -57,7 +57,7 @@ public void start() { private void buildEventBusBridge(String urlPattern, Router router) { SockJSHandler sockJSHandler = SockJSHandler.create(vertx); PermittedOptions allAllowed = new PermittedOptions().setAddressRegex(".*"); - router.route(urlPattern).handler(sockJSHandler.bridge(new BridgeOptions() + router.mountSubRouter(urlPattern, sockJSHandler.bridge(new BridgeOptions() .addInboundPermitted(allAllowed) .addOutboundPermitted(allAllowed))); } @@ -79,13 +79,14 @@ private void registerPublishers(EventBus eventBus, List publishers) { ); } + @SuppressWarnings("unchecked") private JsonObject transformIfNeeded(Object expected, Message message) { JsonObject result; if (expected instanceof Closure) { - result = (message == null) ? new JsonObject((Map) ((Closure) expected).call()) - : new JsonObject((Map) ((Closure) expected).call(message)); + result = (message == null) ? new JsonObject(((Closure>) expected).call()) + : new JsonObject(((Closure>) expected).call(message)); } else { - result = new JsonObject((Map) expected); + result = new JsonObject((Map) expected); } logger.debug("{}", result); diff --git a/src/main/java/top/dteam/dgate/gateway/RouterBuilder.java b/src/main/java/top/dteam/dgate/gateway/RouterBuilder.java index 339ca67..34beb70 100644 --- a/src/main/java/top/dteam/dgate/gateway/RouterBuilder.java +++ b/src/main/java/top/dteam/dgate/gateway/RouterBuilder.java @@ -107,7 +107,7 @@ private static JWTAuth createAuthIfNeeded(Vertx vertx, Router router, LoginConfi } else if (login.ignore().isEmpty()) { login.only().forEach(url -> router.route(url).handler(jwtAuthHandler)); } else if (login.only().isEmpty()) { - List allUrls = urlConfigs.stream().map(config -> config.getUrl()).collect(Collectors.toList()); + List allUrls = urlConfigs.stream().map(UrlConfig::getUrl).collect(Collectors.toList()); Utils.addHandlerExcept(allUrls, login.ignore(), router, jwtAuthHandler); } @@ -133,7 +133,7 @@ private static void addFailureHandler(Router router) { logger.error("Got [{}] during processing [{}], status code: {}. ", routingContext.response().getStatusMessage(), routingContext.request().absoluteURI(), statusCode, routingContext.failure()); - Map payload = new HashMap<>(); + Map payload = new HashMap<>(); payload.put("error", routingContext.response().getStatusMessage()); Utils.fireJsonResponse(routingContext.response(), statusCode, payload); }); diff --git a/src/main/java/top/dteam/dgate/handler/JWTTokenRefreshHandler.java b/src/main/java/top/dteam/dgate/handler/JWTTokenRefreshHandler.java index cb7218d..7a1d443 100644 --- a/src/main/java/top/dteam/dgate/handler/JWTTokenRefreshHandler.java +++ b/src/main/java/top/dteam/dgate/handler/JWTTokenRefreshHandler.java @@ -13,9 +13,9 @@ public class JWTTokenRefreshHandler implements Handler { private JWTTokenRefresher jwtTokenRefresher; private long refreshLimit; - private long refreshExpire; + private int refreshExpire; - public JWTTokenRefreshHandler(JWTTokenRefresher jwtTokenRefresher, long refreshLimit, long refreshExpire) { + public JWTTokenRefreshHandler(JWTTokenRefresher jwtTokenRefresher, long refreshLimit, int refreshExpire) { this.jwtTokenRefresher = jwtTokenRefresher; this.refreshLimit = refreshLimit; this.refreshExpire = refreshExpire; @@ -28,7 +28,7 @@ public void handle(RoutingContext routingContext) { if (payload != null) { jwtTokenRefresher.setPayload(payload); if (jwtTokenRefresher.lessThan(refreshLimit)) { - HashMap tokenMap = new HashMap<>(); + HashMap tokenMap = new HashMap<>(); tokenMap.put("token", jwtTokenRefresher.refresh(refreshExpire)); Utils.fireJsonResponse(routingContext.response(), 200, tokenMap); } else { diff --git a/src/main/java/top/dteam/dgate/handler/LoginHandler.java b/src/main/java/top/dteam/dgate/handler/LoginHandler.java index 4f8edbc..c80c53d 100644 --- a/src/main/java/top/dteam/dgate/handler/LoginHandler.java +++ b/src/main/java/top/dteam/dgate/handler/LoginHandler.java @@ -8,7 +8,6 @@ import java.util.HashMap; import java.util.Map; - public class LoginHandler extends ProxyHandler { private JWTTokenGenerator tokenGenerator; @@ -19,9 +18,10 @@ public LoginHandler(Vertx vertx, ProxyUrlConfig urlConfig, JWTAuth jwtAuth) { } @Override - protected Map createAfterContext() { - Map context = new HashMap<>(); + protected Map createAfterContext() { + Map context = new HashMap<>(); context.put("tokenGenerator", tokenGenerator); return context; } + } diff --git a/src/main/java/top/dteam/dgate/handler/ProxyHandler.java b/src/main/java/top/dteam/dgate/handler/ProxyHandler.java index a82960e..f1d7a2c 100644 --- a/src/main/java/top/dteam/dgate/handler/ProxyHandler.java +++ b/src/main/java/top/dteam/dgate/handler/ProxyHandler.java @@ -103,7 +103,7 @@ private void partialRequest(HttpServerRequest clientRequest, UpstreamURL upstrea CircuitBreaker circuitBreaker = circuitBreakers.get(upstreamURL.toString()); circuitBreaker.execute(future -> { - Map beforeContext = createBeforeContext(); + Map beforeContext = createBeforeContext(); if (upstreamURL.getBefore() != null && beforeContext != null) { upstreamURL.getBefore().setDelegate(beforeContext); } @@ -111,7 +111,7 @@ private void partialRequest(HttpServerRequest clientRequest, UpstreamURL upstrea upstreamURL.getHost(), upstreamURL.getPort(), requestURI, processParamsIfBeforeHandlerExists(upstreamURL.getBefore(), params), clientRequest, simpleResponse -> { - Map afterContext = createAfterContext(); + Map afterContext = createAfterContext(); if (upstreamURL.getAfter() != null && afterContext != null) { upstreamURL.getAfter().setDelegate(afterContext); } @@ -155,11 +155,11 @@ private void partialRequest(HttpServerRequest clientRequest, UpstreamURL upstrea } } - protected Map createBeforeContext() { + protected Map createBeforeContext() { return null; } - protected Map createAfterContext() { + protected Map createAfterContext() { return null; } @@ -169,7 +169,7 @@ private JsonObject processParamsIfBeforeHandlerExists(Closure before try { params = before.call(params); } catch (Exception e) { - logger.error("Before handler got exception: {}", e); + logger.error("Before handler got exception: ", e); throw e; } } @@ -182,7 +182,7 @@ private SimpleResponse processResponseIfAfterHandlerExists(Closure relay.end()); + request.endHandler(end -> relay.end()); pump.start(); }).setHandler(result -> { SimpleResponse simpleResponse; diff --git a/src/main/java/top/dteam/dgate/handler/RequestHandler.java b/src/main/java/top/dteam/dgate/handler/RequestHandler.java index 74a78c5..daa7550 100644 --- a/src/main/java/top/dteam/dgate/handler/RequestHandler.java +++ b/src/main/java/top/dteam/dgate/handler/RequestHandler.java @@ -60,10 +60,8 @@ public GatewayRequestHandler nameOfApiGateway(String nameOfApiGateway) { private void verifyMethodsAllowed(RoutingContext routingContext) { if (allowedMethods() != null && !allowedMethods().isEmpty()) { - if (allowedMethods().stream().anyMatch(method -> routingContext.request().method() == method)) { - return; - } else { - HashMap error = new HashMap(); + if (allowedMethods().stream().noneMatch(method -> routingContext.request().method() == method)) { + HashMap error = new HashMap<>(); error.put("error", "Unsupported HTTP Method."); Utils.fireJsonResponse(routingContext.response(), 400, error); throw new UnsupportedOperationException("Unsupported HTTP Method."); @@ -71,6 +69,7 @@ private void verifyMethodsAllowed(RoutingContext routingContext) { } } + @SuppressWarnings("unchecked") private void verifyRequiredExists(RoutingContext routingContext, JsonObject body) { if (requiredParams() == null) { return; @@ -78,16 +77,16 @@ private void verifyRequiredExists(RoutingContext routingContext, JsonObject body List params; if (requiredParams() instanceof List) { - params = (List) requiredParams(); + params = (List) requiredParams(); } else if (requiredParams() instanceof Map) { - params = (List) ((Map) requiredParams()).get(routingContext.request().method().toString().toLowerCase()); + params = ((Map>) requiredParams()).get(routingContext.request().method().toString().toLowerCase()); } else { throw new InvalidConfiguriationException("required must be List or Map:" + requiredParams().getClass().getName()); } if (params != null && !params.isEmpty()) { if (params.stream().anyMatch(param -> !body.containsKey(param))) { - HashMap error = new HashMap(); + HashMap error = new HashMap<>(); error.put("error", "required params not in request."); Utils.fireJsonResponse(routingContext.response(), 400, error); throw new IllegalArgumentException("required params not in request"); diff --git a/src/main/java/top/dteam/dgate/utils/JWTTokenGenerator.java b/src/main/java/top/dteam/dgate/utils/JWTTokenGenerator.java index 1ec99ad..86c84c4 100644 --- a/src/main/java/top/dteam/dgate/utils/JWTTokenGenerator.java +++ b/src/main/java/top/dteam/dgate/utils/JWTTokenGenerator.java @@ -2,7 +2,7 @@ import io.vertx.core.json.JsonObject; import io.vertx.ext.auth.jwt.JWTAuth; -import io.vertx.ext.auth.jwt.JWTOptions; +import io.vertx.ext.jwt.JWTOptions; import java.util.Map; @@ -14,7 +14,7 @@ public JWTTokenGenerator(JWTAuth jwtAuth) { this.jwtAuth = jwtAuth; } - public String token(Map payload, Long expiration) { + public String token(Map payload, int expiration) { JWTOptions options = new JWTOptions(); options.setExpiresInSeconds(expiration); return jwtAuth.generateToken(new JsonObject(payload), options); diff --git a/src/main/java/top/dteam/dgate/utils/JWTTokenRefresher.java b/src/main/java/top/dteam/dgate/utils/JWTTokenRefresher.java index 18a2043..53184ed 100644 --- a/src/main/java/top/dteam/dgate/utils/JWTTokenRefresher.java +++ b/src/main/java/top/dteam/dgate/utils/JWTTokenRefresher.java @@ -23,7 +23,7 @@ public boolean lessThan(long refreshLimit) { return ((System.currentTimeMillis() / 1000) - payload.getLong("exp")) <= refreshLimit; } - public String refresh(long refreshExpire) { + public String refresh(int refreshExpire) { payload.remove("exp"); payload.remove("iat"); payload.remove("nbf"); diff --git a/src/main/java/top/dteam/dgate/utils/RequestUtils.java b/src/main/java/top/dteam/dgate/utils/RequestUtils.java index 4ccc676..33fd56f 100644 --- a/src/main/java/top/dteam/dgate/utils/RequestUtils.java +++ b/src/main/java/top/dteam/dgate/utils/RequestUtils.java @@ -24,11 +24,9 @@ public class RequestUtils { private static final Logger logger = LoggerFactory.getLogger(RequestUtils.class); - private Vertx vertx; private HttpClient httpClient; public RequestUtils(Vertx vertx) { - this.vertx = vertx; httpClient = vertx.createHttpClient(); } @@ -53,6 +51,7 @@ public void request(HttpMethod method, String host, int port, String url , JsonObject data, HttpServerRequest clientRequest, Handler handler) { HttpClientRequest request = httpClient.request(method, port, host, url, defaultResponseHandler(handler)) .setChunked(true) + .setFollowRedirects(true) .putHeader("content-type", "application/json"); putProxyHeaders(request, clientRequest); @@ -72,6 +71,7 @@ public void requestWithJwtToken(HttpMethod method, String host, int port, String Handler handler) { httpClient.request(method, port, host, url, defaultResponseHandler(handler)) .setChunked(true) + .setFollowRedirects(true) .putHeader("content-type", "application/json") .putHeader("Authorization", String.format("Bearer %s", token)) .end(data.toString()); diff --git a/src/main/java/top/dteam/dgate/utils/Utils.java b/src/main/java/top/dteam/dgate/utils/Utils.java index 22e0c69..94d9792 100644 --- a/src/main/java/top/dteam/dgate/utils/Utils.java +++ b/src/main/java/top/dteam/dgate/utils/Utils.java @@ -8,10 +8,11 @@ import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.JsonObject; +import io.vertx.ext.auth.jwt.JWTAuth; import io.vertx.ext.auth.jwt.JWTAuthOptions; import io.vertx.ext.jwt.JWT; -import io.vertx.ext.auth.jwt.JWTAuth; import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,7 +41,7 @@ public static void fireSingleMessageResponse(HttpServerResponse response, int st response.setStatusCode(statusCode).end(message); } - public static void fireJsonResponse(HttpServerResponse response, int statusCode, Map payload) { + public static void fireJsonResponse(HttpServerResponse response, int statusCode, Map payload) { response.setStatusCode(statusCode); JsonObject jsonObject = new JsonObject(payload); response.putHeader("content-type", "application/json; charset=utf-8").end(jsonObject.toString()); @@ -110,7 +111,7 @@ public static String getTokenFromHeader(HttpServerRequest request) { return null; } - public static void addHandlerExcept(List all, List ignore, Router router, Handler handler) { + public static void addHandlerExcept(List all, List ignore, Router router, Handler handler) { all.removeAll(ignore); all.forEach(url -> router.route(url).handler(handler)); }