diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9243c63 --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +.gradle +/build/ +!gradle/wrapper/gradle-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..0a81069 --- /dev/null +++ b/build.gradle @@ -0,0 +1,48 @@ +buildscript { + ext { + springDependencyManagementPluginVersion = '1.0.7.BUILD-SNAPSHOT' + } + repositories { + mavenCentral() + maven { url "https://repo.spring.io/snapshot" } + maven { url "https://repo.spring.io/milestone" } + } + dependencies { + classpath "io.spring.gradle:dependency-management-plugin:$springDependencyManagementPluginVersion" + } +} + +allprojects { + + apply plugin: 'java' + apply plugin: 'eclipse' + apply plugin: 'io.spring.dependency-management' + + group = 'io.rsocket.spring.boot' + version = '0.0.1.RELEASE' + sourceCompatibility = 1.8 + + repositories { + mavenCentral() + maven { url "https://repo.spring.io/snapshot" } + maven { url "https://repo.spring.io/milestone" } + } + + ext { + springBootDependenciesVersion = "2.1.1.RELEASE" + rSocketVersion = "0.11.14" + } + + dependencyManagement { + imports { + mavenBom "org.springframework.boot:spring-boot-dependencies:$springBootDependenciesVersion" + } + + dependencies { + dependencySet (group: "io.rsocket", version: rSocketVersion) { + entry "rsocket-core" + entry "rsocket-transport-netty" + } + } + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..29953ea 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..e0b3fb8 --- /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-4.10.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..cccdd3d --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## 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="" + +# 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, switch paths to Windows format before running java +if $cygwin ; 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..e95643d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@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= + +@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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..9010685 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,5 @@ +rootProject.name = 'demo' + + +include 'spring-boot-autoconfigure-rsocket' +include 'spring-boot-starter-rsocket' \ No newline at end of file diff --git a/spring-boot-autoconfigure-rsocket/build.gradle b/spring-boot-autoconfigure-rsocket/build.gradle new file mode 100644 index 0000000..5fe2b24 --- /dev/null +++ b/spring-boot-autoconfigure-rsocket/build.gradle @@ -0,0 +1,13 @@ +dependencies { + + implementation('io.rsocket:rsocket-core') + implementation('io.rsocket:rsocket-transport-netty') + + annotationProcessor("org.springframework.boot:spring-boot-configuration-processor") + annotationProcessor("org.springframework.boot:spring-boot-autoconfigure-processor") + + compileClasspath('org.springframework.boot:spring-boot-starter-webflux') + + testImplementation('org.springframework.boot:spring-boot-starter-test') + testImplementation('io.projectreactor:reactor-test') +} diff --git a/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/CompressionCustomizer.java b/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/CompressionCustomizer.java new file mode 100644 index 0000000..46424a1 --- /dev/null +++ b/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/CompressionCustomizer.java @@ -0,0 +1,100 @@ +/* + * Copyright 2012-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.rsocket.spring.boot; + +import java.util.Arrays; +import java.util.function.BiPredicate; + +import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.HttpHeaders; +import reactor.netty.http.server.HttpServer; +import reactor.netty.http.server.HttpServerRequest; +import reactor.netty.http.server.HttpServerResponse; + +import org.springframework.boot.web.embedded.netty.NettyServerCustomizer; +import org.springframework.boot.web.server.Compression; +import org.springframework.util.MimeType; +import org.springframework.util.MimeTypeUtils; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +/** + * Configure the HTTP compression on a Reactor Netty request/response handler. + * + * @author Stephane Maldini + * @author Phillip Webb + * @author Brian Clozel + */ +final class CompressionCustomizer implements NettyServerCustomizer { + + private static final CompressionPredicate ALWAYS_COMPRESS = (request, + response) -> true; + + private final Compression compression; + + CompressionCustomizer(Compression compression) { + this.compression = compression; + } + + @Override + public HttpServer apply(HttpServer server) { + if (!this.compression.getMinResponseSize().isNegative()) { + server = server + .compress((int) this.compression.getMinResponseSize().toBytes()); + } + CompressionPredicate mimeTypes = getMimeTypesPredicate( + this.compression.getMimeTypes()); + CompressionPredicate excludedUserAgents = getExcludedUserAgentsPredicate( + this.compression.getExcludedUserAgents()); + server = server.compress(mimeTypes.and(excludedUserAgents)); + return server; + } + + private CompressionPredicate getMimeTypesPredicate(String[] mimeTypes) { + if (ObjectUtils.isEmpty(mimeTypes)) { + return ALWAYS_COMPRESS; + } + return (request, response) -> { + String contentType = response.responseHeaders() + .get(HttpHeaderNames.CONTENT_TYPE); + if (StringUtils.isEmpty(contentType)) { + return false; + } + MimeType contentMimeType = MimeTypeUtils.parseMimeType(contentType); + return Arrays.stream(mimeTypes).map(MimeTypeUtils::parseMimeType) + .anyMatch((candidate) -> candidate.isCompatibleWith(contentMimeType)); + }; + } + + private CompressionPredicate getExcludedUserAgentsPredicate( + String[] excludedUserAgents) { + if (ObjectUtils.isEmpty(excludedUserAgents)) { + return ALWAYS_COMPRESS; + } + return (request, response) -> { + HttpHeaders headers = request.requestHeaders(); + return Arrays.stream(excludedUserAgents).noneMatch((candidate) -> headers + .contains(HttpHeaderNames.USER_AGENT, candidate, true)); + }; + } + + private interface CompressionPredicate + extends BiPredicate { + + } + +} diff --git a/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/RSocketNettyReactiveWebServerFactory.java b/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/RSocketNettyReactiveWebServerFactory.java new file mode 100644 index 0000000..fab3dc8 --- /dev/null +++ b/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/RSocketNettyReactiveWebServerFactory.java @@ -0,0 +1,188 @@ +/* + * Copyright 2012-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.rsocket.spring.boot; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import io.rsocket.SocketAcceptor; +import reactor.netty.http.HttpProtocol; +import reactor.netty.http.server.HttpServer; +import reactor.netty.resources.LoopResources; + +import org.springframework.boot.web.embedded.netty.NettyServerCustomizer; +import org.springframework.boot.web.embedded.netty.NettyWebServer; +import org.springframework.boot.web.embedded.netty.SslServerCustomizer; +import org.springframework.boot.web.reactive.server.AbstractReactiveWebServerFactory; +import org.springframework.boot.web.reactive.server.ReactiveWebServerFactory; +import org.springframework.boot.web.server.WebServer; +import org.springframework.http.client.reactive.ReactorResourceFactory; +import org.springframework.http.server.reactive.HttpHandler; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.util.Assert; + +/** + * {@link ReactiveWebServerFactory} that can be used to create {@link NettyWebServer}s. + * + * @author Oleh Dokuka + */ +public class RSocketNettyReactiveWebServerFactory extends AbstractReactiveWebServerFactory { + + private List serverCustomizers = new ArrayList<>(); + + private boolean useForwardHeaders; + + private ReactorResourceFactory resourceFactory; + + private String path = "/rs"; + + private SocketAcceptor socketAcceptor; + + public RSocketNettyReactiveWebServerFactory() { + } + + public RSocketNettyReactiveWebServerFactory(int port) { + super(port); + } + + @Override + public WebServer getWebServer(HttpHandler httpHandler) { + HttpServer httpServer = createHttpServer(); + ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter(httpHandler); + return new RSocketWebServer(httpServer, handlerAdapter, socketAcceptor, path); + } + + /** + * Returns a mutable collection of the {@link NettyServerCustomizer}s that will be + * applied to the Netty server builder. + * @return the customizers that will be applied + */ + public Collection getServerCustomizers() { + return this.serverCustomizers; + } + + /** + * Set {@link NettyServerCustomizer}s that should be applied to the Netty server + * builder. Calling this method will replace any existing customizers. + * @param serverCustomizers the customizers to set + */ + public void setServerCustomizers( + Collection serverCustomizers) { + Assert.notNull(serverCustomizers, "ServerCustomizers must not be null"); + this.serverCustomizers = new ArrayList<>(serverCustomizers); + } + + /** + * Add {@link NettyServerCustomizer}s that should applied while building the server. + * @param serverCustomizers the customizers to add + */ + public void addServerCustomizers(NettyServerCustomizer... serverCustomizers) { + Assert.notNull(serverCustomizers, "ServerCustomizer must not be null"); + this.serverCustomizers.addAll(Arrays.asList(serverCustomizers)); + } + + /** + * Set if x-forward-* headers should be processed. + * @param useForwardHeaders if x-forward headers should be used + * @since 2.1.0 + */ + public void setUseForwardHeaders(boolean useForwardHeaders) { + this.useForwardHeaders = useForwardHeaders; + } + + /** + * Add {@link SocketAcceptor}s that should handle incoming RSocket clients. + * @param socketAcceptor the socket acceptor + */ + public void setSocketAcceptor(SocketAcceptor socketAcceptor) { + Assert.notNull(socketAcceptor, "SocketAcceptor must not be null"); + this.socketAcceptor = socketAcceptor; + } + + /** + * Set path on which RSocket server can observe incoming connections + */ + public void setPath(String path) { + this.path = path; + } + + /** + * Set the {@link ReactorResourceFactory} to get the shared resources from. + * @param resourceFactory the server resources + * @since 2.1.0 + */ + public void setResourceFactory(ReactorResourceFactory resourceFactory) { + this.resourceFactory = resourceFactory; + } + + private HttpServer createHttpServer() { + HttpServer server = HttpServer.create(); + if (this.resourceFactory != null) { + LoopResources resources = this.resourceFactory.getLoopResources(); + Assert.notNull(resources, + "No LoopResources: is ReactorResourceFactory not initialized yet?"); + server = server.tcpConfiguration((tcpServer) -> tcpServer.runOn(resources) + .addressSupplier(this::getListenAddress)); + } + else { + server = server.tcpConfiguration( + (tcpServer) -> tcpServer.addressSupplier(this::getListenAddress)); + } + if (getSsl() != null && getSsl().isEnabled()) { + SslServerCustomizer sslServerCustomizer = new SslServerCustomizer(getSsl(), + getHttp2(), getSslStoreProvider()); + server = sslServerCustomizer.apply(server); + } + if (getCompression() != null && getCompression().getEnabled()) { + CompressionCustomizer compressionCustomizer = new CompressionCustomizer( + getCompression()); + server = compressionCustomizer.apply(server); + } + server = server.protocol(listProtocols()).forwarded(this.useForwardHeaders); + return applyCustomizers(server); + } + + private HttpProtocol[] listProtocols() { + if (getHttp2() != null && getHttp2().isEnabled()) { + if (getSsl() != null && getSsl().isEnabled()) { + return new HttpProtocol[] { HttpProtocol.H2, HttpProtocol.HTTP11 }; + } + else { + return new HttpProtocol[] { HttpProtocol.H2C, HttpProtocol.HTTP11 }; + } + } + return new HttpProtocol[] { HttpProtocol.HTTP11 }; + } + + private InetSocketAddress getListenAddress() { + if (getAddress() != null) { + return new InetSocketAddress(getAddress().getHostAddress(), getPort()); + } + return new InetSocketAddress(getPort()); + } + + private HttpServer applyCustomizers(HttpServer server) { + for (NettyServerCustomizer customizer : this.serverCustomizers) { + server = customizer.apply(server); + } + return server; + } + +} diff --git a/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/RSocketServerProperties.java b/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/RSocketServerProperties.java new file mode 100644 index 0000000..8fe47af --- /dev/null +++ b/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/RSocketServerProperties.java @@ -0,0 +1,16 @@ +package io.rsocket.spring.boot; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "rsocket.server", ignoreUnknownFields = true) +public class RSocketServerProperties { + private String path; + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } +} diff --git a/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/RSocketWebServer.java b/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/RSocketWebServer.java new file mode 100644 index 0000000..53edbe4 --- /dev/null +++ b/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/RSocketWebServer.java @@ -0,0 +1,116 @@ +package io.rsocket.spring.boot; + +import io.rsocket.Closeable; +import io.rsocket.RSocketFactory; +import io.rsocket.SocketAcceptor; +import io.rsocket.transport.netty.server.CloseableChannel; +import io.rsocket.transport.netty.server.WebsocketRouteTransport; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import reactor.netty.ChannelBindException; +import reactor.netty.http.server.HttpServer; + +import org.springframework.boot.web.embedded.netty.NettyWebServer; +import org.springframework.boot.web.server.PortInUseException; +import org.springframework.boot.web.server.WebServer; +import org.springframework.boot.web.server.WebServerException; +import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; +import org.springframework.util.Assert; + +public class RSocketWebServer implements WebServer { + private static final Log logger = LogFactory.getLog(NettyWebServer.class); + + private final SocketAcceptor acceptor; + + private final String path; + + private final HttpServer httpServer; + + private final ReactorHttpHandlerAdapter handlerAdapter; + + private CloseableChannel disposableServer; + + public RSocketWebServer(HttpServer httpServer, + ReactorHttpHandlerAdapter handlerAdapter, + SocketAcceptor socketAcceptor, + String path) { + acceptor = socketAcceptor; + this.path = path; + Assert.notNull(httpServer, "HttpServer must not be null"); + Assert.notNull(handlerAdapter, "HandlerAdapter must not be null"); + this.httpServer = httpServer; + this.handlerAdapter = handlerAdapter; + } + + @Override + public void start() throws WebServerException { + if (this.disposableServer == null) { + try { + this.disposableServer = startHttpServer(); + } + catch (Exception ex) { + ChannelBindException bindException = findBindException(ex); + if (bindException != null) { + throw new PortInUseException(bindException.localPort()); + } + throw new WebServerException("Unable to start Netty", ex); + } + logger.info("Netty started on port(s): " + getPort()); + startDaemonAwaitThread(this.disposableServer); + } + } + + private CloseableChannel startHttpServer() { + return RSocketFactory.receive() + .acceptor(acceptor) + .transport(new WebsocketRouteTransport( + this.httpServer, + r -> r.route(hsr -> !("/" + hsr.path()).equals(path), handlerAdapter), + path + )) + .start() + .cast(CloseableChannel.class) + .block(); + } + + private ChannelBindException findBindException(Exception ex) { + Throwable candidate = ex; + while (candidate != null) { + if (candidate instanceof ChannelBindException) { + return (ChannelBindException) candidate; + } + candidate = candidate.getCause(); + } + return null; + } + + private void startDaemonAwaitThread(Closeable disposableServer) { + Thread awaitThread = new Thread("server") { + + @Override + public void run() { + disposableServer.onClose().block(); + } + + }; + awaitThread.setContextClassLoader(getClass().getClassLoader()); + awaitThread.setDaemon(false); + awaitThread.start(); + } + + @Override + public void stop() throws WebServerException { + if (this.disposableServer != null) { + this.disposableServer.dispose(); + this.disposableServer = null; + } + } + + @Override + public int getPort() { + if (this.disposableServer != null) { + return this.disposableServer.address().getPort(); + } + return 0; + } +} diff --git a/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/RSocketWebServerFactoryAutoConfiguration.java b/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/RSocketWebServerFactoryAutoConfiguration.java new file mode 100644 index 0000000..b1ecd91 --- /dev/null +++ b/spring-boot-autoconfigure-rsocket/src/main/java/io/rsocket/spring/boot/RSocketWebServerFactoryAutoConfiguration.java @@ -0,0 +1,75 @@ +/* + * Copyright 2012-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.rsocket.spring.boot; + +import io.rsocket.SocketAcceptor; +import reactor.netty.http.server.HttpServer; + +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.AutoConfigureOrder; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.boot.autoconfigure.web.ServerProperties; +import org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.web.reactive.server.ReactiveWebServerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.core.Ordered; +import org.springframework.http.ReactiveHttpInputMessage; +import org.springframework.http.client.reactive.ReactorResourceFactory; + +/** + * {@link EnableAutoConfiguration Auto-configuration} for a RSocket web server. + * + * @author Oleh Dokuka + */ +@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) +@AutoConfigureBefore(ReactiveWebServerFactoryAutoConfiguration.class) +@Configuration +@ConditionalOnClass(ReactiveHttpInputMessage.class) +@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) +@EnableConfigurationProperties(RSocketServerProperties.class) +@Import({ RSocketWebServerFactoryAutoConfiguration.EmbeddedRSocket.class,}) +public class RSocketWebServerFactoryAutoConfiguration { + + @Configuration + @ConditionalOnMissingBean({ReactiveWebServerFactory.class}) + @ConditionalOnClass({HttpServer.class}) + static class EmbeddedRSocket { + + @Bean + @ConditionalOnMissingBean + public ReactorResourceFactory reactorServerResourceFactory() { + return new ReactorResourceFactory(); + } + + @Bean + public RSocketNettyReactiveWebServerFactory nettyReactiveWebServerFactory( + ReactorResourceFactory resourceFactory, + SocketAcceptor socketAcceptor + ) { + RSocketNettyReactiveWebServerFactory serverFactory = new RSocketNettyReactiveWebServerFactory(); + serverFactory.setResourceFactory(resourceFactory); + serverFactory.setSocketAcceptor(socketAcceptor); + return serverFactory; + } + } +} diff --git a/spring-boot-starter-rsocket/build.gradle b/spring-boot-starter-rsocket/build.gradle new file mode 100644 index 0000000..de0eb30 --- /dev/null +++ b/spring-boot-starter-rsocket/build.gradle @@ -0,0 +1,5 @@ +dependencies { + compile project(':spring-boot-autoconfigure-rsocket') + + compile 'org.springframework.boot:spring-boot-starter-webflux' +}