├── .gitignore ├── README.md ├── avian.gradle ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── Main.kt ├── embedded-jar-main.cpp ├── http ├── HttpHandler.kt ├── NioHttpServer.kt └── PooledHandler.kt └── util ├── BlockingQueue.java └── ThreadPool.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | *.ipr 3 | .idea 4 | .gradle 5 | build 6 | out -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [Avian](https://github.com/ReadyTalk/avian) example usage in gradle build 2 | 3 | Kotlin+java.nio hello world http server example 4 | 5 | ## Requirements 6 | 7 | You will need the following environment to build the project: 8 | 9 | * OpenJDK >= 1.7 (`jar`,`javac` in PATH) 10 | * Ensure JAVA_HOME is pointing to the OpenJDK 11 | * Build tools (`make`,`gcc`,`g++` in PATH) 12 | * Git (`git` in PATH) 13 | * Bash (`bash` in PATH) 14 | 15 | ## How to build 16 | 17 | ```bash 18 | $ ./gradlew clean standalone 19 | ``` 20 | 21 | This will download Avian to `build/avian` directory and then will launch the build of your project into a single 22 | self-contained application file less than 4Mb in size. 23 | 24 | ## Drawbacks 25 | 26 | * There is a `src/util` directory containing the primitive thread pool and blocking queue implementations, that 27 | should be easily found within the java standard library. The reason for this is that Avian does not implement 28 | many parts of jdk and we have to "reinvent a wheel" for some features. 29 | * Performance is worse than with Oracle JDK. I believe this is because Oracle JDK is highly optimized in many 30 | ways. 31 | 32 | ## Advanced settings 33 | 34 | Avian is a very lightweight JDK implementation. As such, it misses lots of great JDK standard library things. 35 | Fortunately there is a way of building your project with the alternative JDK implementations (e.g. OpenJDK). 36 | 37 | ### Build with OpenJDK 38 | 39 | You can build the project in more advanced way with the full JDK class library support. To do so, you will need to 40 | have the source code and a distribution of OpenJDK. As soon as you get ones, just indicate the path to each of them 41 | in the respective properties within `gradle.properties` file: 42 | 43 | ```properties 44 | OPEN_JDK_PATH=/absolute/path/to/openjdk/distribution 45 | OPEN_JDK_SRC_PATH=/absolute/path/to/openjdk/source/code 46 | ``` 47 | 48 | ## Drawbacks 49 | 50 | * The proven compatible version of OpenJDK is openjdk-7u111 (as of November 2016). Not sure if others will work as well. 51 | * The resulting size of a self-contained file will be tens of megabytes instead of a few. 52 | -------------------------------------------------------------------------------- /avian.gradle: -------------------------------------------------------------------------------- 1 | static platform() { 2 | if (org.gradle.internal.os.OperatingSystem.current().isLinux()) { 3 | 'linux' 4 | } else if (org.gradle.internal.os.OperatingSystem.current().isWindows()) { 5 | 'windows' 6 | } else if (org.gradle.internal.os.OperatingSystem.current().isMacOsX()) { 7 | 'macosx' 8 | } 9 | } 10 | 11 | static arch() { 12 | final s = System.getProperty("os.arch") 13 | s == "amd64" ? "x86_64" : s 14 | } 15 | 16 | static java_home() { 17 | System.properties.'java.home' 18 | } 19 | 20 | def avianBuildDir(File buildDir) { 21 | if (OPEN_JDK_SRC_PATH) { 22 | "${buildDir}/avian/build/${platform()}-${arch()}-tails-openjdk-src" 23 | } else { 24 | "${buildDir}/avian/build/${platform()}-${arch()}-tails${OPEN_JDK_PATH ? '-openjdk' : ''}" 25 | } 26 | } 27 | 28 | task standalone(dependsOn: 'shadowJar') { 29 | doLast { 30 | if (!file("${buildDir}/avian").exists()) { 31 | exec { 32 | commandLine 'git', 'clone', 'https://github.com/ReadyTalk/avian.git', "${buildDir}/avian" 33 | } 34 | } 35 | GFileUtils.deleteQuietly(file("${buildDir}/all")) 36 | exec { 37 | workingDir "${buildDir}/avian" 38 | commandLine(*(['make', 'tails=true', "platform=${platform()}"] + 39 | (OPEN_JDK_PATH ? ["openjdk=${OPEN_JDK_PATH}"] : []) + 40 | (OPEN_JDK_SRC_PATH ? ["openjdk-src=${OPEN_JDK_SRC_PATH}"] : []))) 41 | } 42 | copy { 43 | from zipTree(file("${buildDir}/libs/${project.name}-all.jar")) 44 | into "${buildDir}/all" 45 | } 46 | exec { 47 | workingDir "${buildDir}/all" 48 | commandLine 'ar', 'x', "${avianBuildDir(buildDir)}/libavian.a" 49 | } 50 | copy { 51 | from "${avianBuildDir(buildDir)}/classpath.jar" 52 | into "${buildDir}/all" 53 | } 54 | GFileUtils.moveFile(file("${buildDir}/all/classpath.jar"), file("${buildDir}/all/boot.jar")) 55 | file("${buildDir}/all").listFiles() 56 | .findAll { it.name != 'boot.jar' && !it.name.endsWith('.o') }.each { f -> 57 | exec { 58 | workingDir "${buildDir}/all" 59 | commandLine 'jar', 'u0f', 'boot.jar', f.name 60 | } 61 | } 62 | exec { 63 | workingDir "${buildDir}/all" 64 | commandLine "${avianBuildDir(buildDir)}/binaryToObject/binaryToObject", 'boot.jar', 'boot-jar.o', '_binary_boot_jar_start', '_binary_boot_jar_end', platform(), arch() 65 | } 66 | copy { 67 | from "${rootDir}/src/embedded-jar-main.cpp" 68 | into "${buildDir}/all" 69 | } 70 | exec { 71 | workingDir "${buildDir}/all" 72 | commandLine 'g++', "-I${java_home()}/../include", "-I${java_home()}/../include/darwin", '-D_JNI_IMPLEMENTATION_', '-c', 'embedded-jar-main.cpp', '-o', 'main.o' 73 | } 74 | exec { 75 | workingDir "${buildDir}/all" 76 | commandLine '/bin/bash', '-c', "g++ -rdynamic *.o -ldl -lpthread -lz -o ${project.name} ${platform() == "macosx" ? '-framework CoreFoundation' : ''}" 77 | } 78 | exec { 79 | workingDir "${buildDir}/all" 80 | commandLine 'strip', '-S', '-x', project.name 81 | } 82 | copy { 83 | from "${buildDir}/all/${project.name}" 84 | into "${buildDir}" 85 | } 86 | } 87 | } 88 | 89 | 90 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'kotlin' 2 | apply plugin: 'com.github.johnrengelman.shadow' 3 | 4 | buildscript { 5 | ext.kotlin_version = '1.0.5' 6 | repositories { 7 | mavenCentral() 8 | jcenter() 9 | } 10 | dependencies { 11 | classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.4' 12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 13 | } 14 | } 15 | repositories { 16 | mavenCentral() 17 | maven { 18 | url 'https://repository.jboss.org' 19 | } 20 | } 21 | dependencies { 22 | testCompile 'junit:junit:4.12' 23 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 24 | } 25 | sourceSets { 26 | main.java.srcDirs += 'src' 27 | } 28 | 29 | apply from: "${rootDir.path}/avian.gradle" 30 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | #OPEN_JDK_PATH=/Users/isadykov/Library/Java/JavaVirtualMachines/jdk1.7.0.jdk/Contents/Home/ 2 | #OPEN_JDK_SRC_PATH=/Users/isadykov/dist/java/openjdk-1.7-src/jdk/src 3 | #OPEN_JDK_PATH=/usr/lib/jvm/java-7-openjdk-amd64 4 | #OPEN_JDK_SRC_PATH=/home/smecsia/dist/jdk/obuildfactory/sources/openjdk7/jdk/src 5 | OPEN_JDK_PATH= 6 | OPEN_JDK_SRC_PATH= 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smecsia/kotlin-standalone/2403a6b684f013d27af57834213f16fa614d22f0/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Nov 18 11:50:45 AEDT 2016 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-2.13-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 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 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /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 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /src/Main.kt: -------------------------------------------------------------------------------- 1 | 2 | import http.HttpHandler.Companion.httpHandler 3 | import http.NioHttpServer 4 | 5 | /** 6 | * @author Ilya Sadykov 7 | */ 8 | val BODY = "Hello, World!" 9 | val RESPONSE = "HTTP/1.1 200 OK\r\n" + 10 | "Content-Type: text/plain\r\n" + 11 | "Content-Length: 12\r\n\r\n$BODY" 12 | 13 | fun main(args: Array) { 14 | NioHttpServer( 15 | port = 5555, 16 | threadsCount = 2, 17 | httpHandler = httpHandler { req, writer -> writer.write(RESPONSE) } 18 | ).run() 19 | } -------------------------------------------------------------------------------- /src/embedded-jar-main.cpp: -------------------------------------------------------------------------------- 1 | #include "jni.h" 2 | #include 3 | #include "stdlib.h" 4 | 5 | #if (defined __MINGW32__) || (defined _MSC_VER) 6 | # define EXPORT __declspec(dllexport) 7 | #else 8 | # define EXPORT __attribute__ ((visibility("default"))) \ 9 | __attribute__ ((used)) 10 | #endif 11 | 12 | #if (! defined __x86_64__) && ((defined __MINGW32__) || (defined _MSC_VER)) 13 | # define SYMBOL(x) binary_boot_jar_##x 14 | #else 15 | # define SYMBOL(x) _binary_boot_jar_##x 16 | #endif 17 | 18 | extern "C" { 19 | 20 | extern const uint8_t SYMBOL(start)[]; 21 | extern const uint8_t SYMBOL(end)[]; 22 | 23 | EXPORT const uint8_t* 24 | bootJar(unsigned* size) 25 | { 26 | *size = SYMBOL(end) - SYMBOL(start); 27 | return SYMBOL(start); 28 | } 29 | 30 | } // extern "C" 31 | 32 | extern "C" void __cxa_pure_virtual(void) { abort(); } 33 | 34 | int 35 | main(int ac, const char** av) 36 | { 37 | JavaVMInitArgs vmArgs; 38 | vmArgs.version = JNI_VERSION_1_2; 39 | vmArgs.nOptions = 1; 40 | vmArgs.ignoreUnrecognized = JNI_TRUE; 41 | 42 | JavaVMOption options[vmArgs.nOptions]; 43 | vmArgs.options = options; 44 | 45 | options[0].optionString = const_cast("-Xbootclasspath:[bootJar]"); 46 | 47 | JavaVM* vm; 48 | void* env; 49 | JNI_CreateJavaVM(&vm, &env, &vmArgs); 50 | JNIEnv* e = static_cast(env); 51 | 52 | jclass c = e->FindClass("MainKt"); 53 | if (not e->ExceptionCheck()) { 54 | jmethodID m = e->GetStaticMethodID(c, "main", "([Ljava/lang/String;)V"); 55 | if (not e->ExceptionCheck()) { 56 | jclass stringClass = e->FindClass("java/lang/String"); 57 | if (not e->ExceptionCheck()) { 58 | jobjectArray a = e->NewObjectArray(ac-1, stringClass, 0); 59 | if (not e->ExceptionCheck()) { 60 | for (int i = 1; i < ac; ++i) { 61 | e->SetObjectArrayElement(a, i-1, e->NewStringUTF(av[i])); 62 | } 63 | 64 | e->CallStaticVoidMethod(c, m, a); 65 | } 66 | } 67 | } 68 | } 69 | 70 | int exitCode = 0; 71 | if (e->ExceptionCheck()) { 72 | exitCode = -1; 73 | e->ExceptionDescribe(); 74 | } 75 | 76 | vm->DestroyJavaVM(); 77 | 78 | return exitCode; 79 | } 80 | -------------------------------------------------------------------------------- /src/http/HttpHandler.kt: -------------------------------------------------------------------------------- 1 | package http 2 | 3 | import java.io.Writer 4 | 5 | /** 6 | * @author Ilya Sadykov 7 | */ 8 | interface HttpHandler { 9 | fun handle(req: ByteArray, response: Writer) 10 | 11 | companion object { 12 | fun httpHandler(handler: (ByteArray, Writer) -> Unit): HttpHandler { 13 | return object : HttpHandler { 14 | override fun handle(req: ByteArray, response: Writer) { 15 | handler(req, response) 16 | } 17 | } 18 | } 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /src/http/NioHttpServer.kt: -------------------------------------------------------------------------------- 1 | package http 2 | 3 | import util.ThreadPool 4 | import java.lang.Thread.interrupted 5 | import java.net.InetSocketAddress 6 | import java.nio.channels.SelectionKey 7 | import java.nio.channels.SelectionKey.OP_ACCEPT 8 | import java.nio.channels.Selector 9 | import java.nio.channels.ServerSocketChannel 10 | import java.nio.channels.SocketChannel 11 | 12 | /** 13 | * @author Ilya Sadykov 14 | */ 15 | class NioHttpServer 16 | constructor(host: String = "0.0.0.0", port: Int = 8080, 17 | threadsCount: Int = 4, private val httpHandler: HttpHandler) : Runnable { 18 | private val selector: Selector 19 | private val threadPool: ThreadPool 20 | private val serverSocketChannel: ServerSocketChannel 21 | 22 | init { 23 | threadPool = ThreadPool(threadsCount) 24 | selector = Selector.open() 25 | serverSocketChannel = ServerSocketChannel.open() 26 | serverSocketChannel.socket().bind(InetSocketAddress(host, port)) 27 | serverSocketChannel.configureBlocking(false) 28 | serverSocketChannel.register(selector, OP_ACCEPT, Acceptor()) 29 | } 30 | 31 | override fun run() { 32 | while (!interrupted()) { 33 | try { 34 | if (selector.select() == 0) continue 35 | val it = selector.selectedKeys().iterator() 36 | while (it.hasNext()) { 37 | val key = it.next() 38 | dispatch(key) 39 | it.remove() 40 | } 41 | } catch (e: Exception) { 42 | e.printStackTrace() 43 | } 44 | } 45 | } 46 | 47 | private fun dispatch(key: SelectionKey) { 48 | when (key.attachment()) { 49 | is Acceptor -> { 50 | if (key.isAcceptable) { 51 | (key.attachment() as Acceptor).run() 52 | } 53 | } 54 | else -> (key.attachment() as Runnable).run() 55 | } 56 | } 57 | 58 | private inner class Acceptor : Runnable { 59 | override fun run() { 60 | var socketChannel: SocketChannel? = null 61 | try { 62 | socketChannel = serverSocketChannel.accept() 63 | if (socketChannel != null) { 64 | PooledHandler(threadPool, httpHandler, selector, socketChannel) 65 | } 66 | } catch (ex: Exception) { 67 | ex.printStackTrace() 68 | } finally { 69 | socketChannel?.finishConnect() 70 | } 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /src/http/PooledHandler.kt: -------------------------------------------------------------------------------- 1 | package http 2 | 3 | import util.ThreadPool 4 | import java.io.StringWriter 5 | import java.nio.ByteBuffer.allocate 6 | import java.nio.ByteBuffer.wrap 7 | import java.nio.channels.SelectionKey 8 | import java.nio.channels.SelectionKey.OP_READ 9 | import java.nio.channels.Selector 10 | import java.nio.channels.SocketChannel 11 | 12 | /** 13 | * @author Ilya Sadykov 14 | */ 15 | internal class PooledHandler 16 | constructor(private val pool: ThreadPool, 17 | private val handler: HttpHandler, 18 | selector: Selector, 19 | private val socketChannel: SocketChannel) : Runnable { 20 | private val selectionKey: SelectionKey 21 | 22 | init { 23 | this.socketChannel.configureBlocking(false) 24 | selectionKey = this.socketChannel.register(selector, OP_READ, this) 25 | selectionKey.interestOps(OP_READ) 26 | selector.wakeup() 27 | } 28 | 29 | override fun run() { 30 | val requestBuffer = allocate(REQ_BUFFER_SIZE) 31 | val readCount = socketChannel.read(requestBuffer) 32 | if (readCount > 0) { 33 | pool.execute { 34 | selectionKey.interestOps(SelectionKey.OP_WRITE) 35 | val sw = StringWriter() 36 | handler.handle(requestBuffer.array(), sw) 37 | socketChannel.write(wrap((sw.toString() as java.lang.String).bytes)) 38 | } 39 | } else if(readCount < 0) { 40 | socketChannel.close() 41 | } 42 | } 43 | 44 | companion object { 45 | private val REQ_BUFFER_SIZE = 100 46 | } 47 | } -------------------------------------------------------------------------------- /src/util/BlockingQueue.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | public class BlockingQueue { 7 | 8 | private List queue = new LinkedList<>(); 9 | private int limit = 1000; 10 | 11 | public BlockingQueue(int limit) { 12 | this.limit = limit; 13 | } 14 | 15 | public synchronized void offer(T item) 16 | throws InterruptedException { 17 | while (this.queue.size() == this.limit) { 18 | wait(); 19 | } 20 | if (this.queue.size() == 0) { 21 | notifyAll(); 22 | } 23 | this.queue.add(item); 24 | } 25 | 26 | 27 | public synchronized T take() 28 | throws InterruptedException { 29 | while (this.queue.size() == 0) { 30 | wait(); 31 | } 32 | if (this.queue.size() == this.limit) { 33 | notifyAll(); 34 | } 35 | 36 | return this.queue.remove(0); 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /src/util/ThreadPool.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | /** 4 | * Primitive fixed size thread pool 5 | */ 6 | public class ThreadPool { 7 | 8 | private final BlockingQueue queue; 9 | private final PooledThread[] threads; 10 | 11 | public ThreadPool(int poolSize) { 12 | threads = new PooledThread[poolSize]; 13 | queue = new BlockingQueue<>(1000); 14 | for (int i = 0; i < poolSize; ++i) { 15 | threads[i] = new PooledThread(); 16 | threads[i].start(); 17 | } 18 | } 19 | 20 | synchronized public void execute(Runnable job) { 21 | try { 22 | queue.offer(job); 23 | } catch (InterruptedException e) { 24 | e.printStackTrace(); 25 | } 26 | } 27 | 28 | private class PooledThread extends Thread { 29 | public void run() { 30 | while (true) { 31 | try { 32 | final Runnable job = queue.take(); 33 | if (job == null) { 34 | continue; 35 | } 36 | job.run(); 37 | } catch (Throwable t) { 38 | // ignore 39 | } 40 | } 41 | } 42 | } 43 | 44 | public void join() { 45 | for (PooledThread thread : threads) { 46 | try { 47 | thread.join(); 48 | } catch (InterruptedException e) { 49 | e.printStackTrace(); 50 | } 51 | } 52 | } 53 | 54 | } --------------------------------------------------------------------------------