Skip to content

Commit

Permalink
Release 1.0.3
Browse files Browse the repository at this point in the history
* Remove default body when mapping is not found (404) #7

* Remove Server header #8

* Remove daemon mode parameter

* Refactoring. Handle bind exception.

* Log refactoring. Enable colors.
  • Loading branch information
Oleksandr Loushkin committed Jan 25, 2017
1 parent 55f20f9 commit 243d833
Show file tree
Hide file tree
Showing 16 changed files with 84 additions and 516 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ classes/
*.ear

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
hs_err_pid*
*.log
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
version=1.0.2
version=1.0.3
429 changes: 0 additions & 429 deletions logs/komock.log

This file was deleted.

1 change: 0 additions & 1 deletion mock_example.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
daemonMode: false
consul:
enabled: false
consulHost: 127.0.0.1
Expand Down
15 changes: 0 additions & 15 deletions src/main/kotlin/ua/com/lavi/komock/KomockRunner.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package ua.com.lavi.komock

import org.slf4j.LoggerFactory
import ua.com.lavi.komock.config.ApplicationConfiguration
import ua.com.lavi.komock.registrar.ConsulRegistrar
import ua.com.lavi.komock.registrar.ServerRegistrar
Expand All @@ -12,8 +11,6 @@ import ua.com.lavi.komock.registrar.SpringConfigRegistrar

class KomockRunner {

private val log = LoggerFactory.getLogger(this.javaClass)

fun run(applicationConfiguration: ApplicationConfiguration) {

//Server instances
Expand All @@ -33,17 +30,5 @@ class KomockRunner {
if (consulServerProperties.enabled) {
consulRegistrar.register(consulServerProperties)
}

if (applicationConfiguration.daemonMode) {
daemonMode()
}
}

private fun daemonMode() {
try {
Thread.currentThread().join()
} catch (e: InterruptedException) {
log.warn("Error: {}", e)
}
}
}
4 changes: 2 additions & 2 deletions src/main/kotlin/ua/com/lavi/komock/engine/HttpHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import javax.servlet.http.HttpServletRequestWrapper
* Created by Oleksandr Loushkin
*/

internal class HttpHandler(private val requestMatcherFilter: Filter) : SessionHandler() {
internal class HttpHandler(private val routingFilter: Filter) : SessionHandler() {

@Throws(IOException::class, ServletException::class)
override fun doHandle(
Expand All @@ -28,7 +28,7 @@ internal class HttpHandler(private val requestMatcherFilter: Filter) : SessionHa
request: HttpServletRequest,
response: HttpServletResponse) {

requestMatcherFilter.doFilter(HttpRequestWrapper(request), response, null)
routingFilter.doFilter(HttpRequestWrapper(request), response, null)
}

class HttpRequestWrapper(request: HttpServletRequest) : HttpServletRequestWrapper(request) {
Expand Down
26 changes: 11 additions & 15 deletions src/main/kotlin/ua/com/lavi/komock/engine/JettyServer.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package ua.com.lavi.komock.engine


import org.eclipse.jetty.server.Handler
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.ServerConnector
import org.eclipse.jetty.server.*
import org.eclipse.jetty.server.handler.ContextHandler
import org.eclipse.jetty.server.handler.HandlerList
import org.eclipse.jetty.util.ssl.SslContextFactory
Expand Down Expand Up @@ -44,35 +42,33 @@ internal class JettyServer(val serverId: String, val virtualHosts: ArrayList<Str
handlerList.handlers = arrayOf(contextHandler)
jettyServer.handler = handlerList

try {
jettyServer.start()
jettyServer.join()
log.info("$serverId - listening on $host:$port")
} catch (e: Exception) {
log.error("$serverId - start failed", e)
System.exit(100)
}
jettyServer.start()
log.debug("$serverId - listening on $host:$port")

}

fun stop() {
log.info("Stopping $serverId")
log.debug("Stopping $serverId")
jettyServer.stop()
log.info("$serverId is stopped")
log.debug("$serverId is stopped")
}

fun buildSocketConnector(server: Server,
host: String,
port: Int,
sslKeyStore: SslKeyStore?): ServerConnector {

val httpConfig = HttpConfiguration()
httpConfig.sendServerVersion = false
val httpFactory = HttpConnectionFactory(httpConfig)

val connector: ServerConnector?
if (sslKeyStore == null) {
connector = ServerConnector(server)
connector = ServerConnector(server, httpFactory)
} else {
val sslContextFactory = SslContextFactory(sslKeyStore.keystoreFile)
sslContextFactory.setKeyStorePassword(sslKeyStore.keystorePassword)
connector = ServerConnector(server, sslContextFactory)
connector = ServerConnector(server, sslContextFactory, httpFactory)
}
connector.idleTimeout = TimeUnit.HOURS.toMillis(1)
connector.soLingerTime = -1
Expand Down
50 changes: 25 additions & 25 deletions src/main/kotlin/ua/com/lavi/komock/engine/Router.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,14 @@ class Router(val serverId: String,
val port: Int,
var minThreads: Int,
var maxThreads: Int,
var threadIdleTimeoutMillis: Int,
var sslKeyStore: SslKeyStore?, virtualHosts: ArrayList<String>) {
var idleTimeout: Int,
var sslKeyStore: SslKeyStore?,
var virtualHosts: ArrayList<String>) {

private var isStarted: Boolean = false
private val log = LoggerFactory.getLogger(this.javaClass)
private var server: JettyServer
private var routingTable = RoutingTable()

companion object {

Expand All @@ -40,40 +44,36 @@ class Router(val serverId: String,
}
}


private val log = LoggerFactory.getLogger(this.javaClass)
private var server: JettyServer
private var routingTable = RoutingTable()


init {
server = JettyServer(serverId, virtualHosts, HttpHandler(RoutingFilter(routingTable)))
val httpHandler = HttpHandler(RoutingFilter(routingTable))
server = JettyServer(serverId, virtualHosts, httpHandler)
routers.add(this)
}

@Synchronized fun stop() {
fun stop() {
if (isStarted) {
Thread {
routingTable.clearRoutes()
server.stop()
}.start()
server.stop()
isStarted = false
} else {
log.info("Server is not started!")
}
}


@Synchronized fun start() {
fun start() {
if (!isStarted) {
Thread {
server.start(
ipAddress,
port,
sslKeyStore,
maxThreads,
minThreads,
threadIdleTimeoutMillis)
}.start()
server.start(
ipAddress,
port,
sslKeyStore,
maxThreads,
minThreads,
idleTimeout)

isStarted = true
log.info("Started server: $serverId on port: $port, virtualHosts: ${virtualHosts.joinToString(",")}. " +
"maxThreads: $maxThreads, minThreads: $minThreads, idle timeout: $idleTimeout ms")
} else {
log.info("Server is already started!")
}
}

Expand Down
24 changes: 10 additions & 14 deletions src/main/kotlin/ua/com/lavi/komock/engine/RoutingFilter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -44,26 +44,22 @@ internal class RoutingFilter(val routingTable: RoutingTable) : Filter {
route.beforeRouteHandler.handle(request, response)
route.routeHandler.handle(request, response)
route.afterRouteHandler.handle(request, response)
serializeContentToResponse(httpServletRequest, httpServletResponse, response.content)
}

serializeContentToResponse(httpServletRequest, httpServletResponse, response.content)

chain?.doFilter(httpServletRequest, httpServletResponse)
}

fun serializeContentToResponse(httpServletRequest: HttpServletRequest, httpServletResponse: HttpServletResponse, content: String?) {

if (content != null) {
if (!httpServletResponse.isCommitted) {
val responseStream = gzip(httpServletRequest, httpServletResponse)
try {
responseStream.write(content.toByteArray())
} catch (e: UnsupportedEncodingException) {
throw IOException(e)
}
responseStream.flush()
responseStream.close()
fun serializeContentToResponse(httpServletRequest: HttpServletRequest, httpServletResponse: HttpServletResponse, content: String) {
if (!httpServletResponse.isCommitted) {
val responseStream = gzip(httpServletRequest, httpServletResponse)
try {
responseStream.write(content.toByteArray())
} catch (e: UnsupportedEncodingException) {
throw IOException(e)
}
responseStream.flush()
responseStream.close()
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/ua/com/lavi/komock/engine/RoutingTable.kt
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ internal class RoutingTable {
routeMap.clear()
}

fun getRouteMap(): Map<String, MutableMap<HttpMethod, Route>> {
fun getFullRouteMap(): Map<String, MutableMap<HttpMethod, Route>> {
return routeMap
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import javax.servlet.http.HttpServletResponse

class Response(private val servletResponse: HttpServletResponse) {

var content: String? = null
var content: String = ""

fun statusCode(statusCode: Int) {
servletResponse.status = statusCode
Expand Down
11 changes: 11 additions & 0 deletions src/main/kotlin/ua/com/lavi/komock/registrar/ConsulRegistrar.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,16 @@ class ConsulRegistrar {
clientRegistrar.agentServiceRegister(newService)
log.info("Registered consul service: ${consulService.serviceId} - ${consulService.serviceAddress}:${consulService.servicePort}")
}
daemonMode()
}

private fun daemonMode() {
try {
log.info("Consul registration is running in daemon mode")
Thread.currentThread().join()
} catch (e: InterruptedException) {
log.warn("Error: {}", e)
}
}

}
11 changes: 7 additions & 4 deletions src/main/kotlin/ua/com/lavi/komock/registrar/ServerRegistrar.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import org.slf4j.LoggerFactory
import ua.com.lavi.komock.engine.Router
import ua.com.lavi.komock.config.property.http.ServerProperties
import ua.com.lavi.komock.engine.model.SslKeyStore
import java.net.BindException

/**
* Created by Oleksandr Loushkin
Expand All @@ -24,10 +25,12 @@ class ServerRegistrar {
serverProp.minThreads, serverProp.maxThreads,
serverProp.idleTimeout, sslKeyStore, serverProp.virtualHosts)

router.start()

log.info("Started server: ${serverProp.id} on port: ${serverProp.port}. virtualHosts: ${serverProp.virtualHosts.joinToString(",")}")
log.info("maxThreads: ${serverProp.maxThreads}. minThreads: ${serverProp.minThreads}. idle timeout: ${serverProp.idleTimeout} ms")
try {
router.start()
} catch (e: BindException) {
log.warn(e.message + ": ${serverProp.ipAddress}, port: ${serverProp.port}", e)
return
}

//register routeHolders
if (!serverProp.routes.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import ua.com.lavi.komock.config.property.spring.SpringConfigProperties
import ua.com.lavi.komock.engine.Router
import ua.com.lavi.komock.engine.model.SslKeyStore
import java.io.IOException
import java.net.BindException
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Path
Expand Down Expand Up @@ -42,7 +43,12 @@ class SpringConfigRegistrar {
serverProp.minThreads, serverProp.maxThreads,
serverProp.idleTimeout, sslKeyStore, serverProp.virtualHosts)

router.start()
try {
router.start()
} catch (e: BindException) {
log.warn(e.message + ": ${serverProp.ipAddress}, port: ${serverProp.port}", e)
return
}

log.info("Started server: ${serverProp.id} on port: ${serverProp.port}. virtualHosts: ${serverProp.virtualHosts.joinToString(",")}")

Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/logback.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<configuration>
<statusListener class="ch.qos.logback.core.status.NopStatusListener" />

<property name="FULL_LOG_PATTERN" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"/>
<property name="FULL_LOG_PATTERN" value="%d{HH:mm:ss.SSS} %yellow([%thread]) %highlight(%-5level) %cyan(%logger{36}) - %msg%n"/>
<property name="SHORT_LOG_PATTERN" value="%d{HH:mm:ss.SSS} - %msg%n"/>
<property name="LOG_DIRECTORY" value="${LOG_DIRECTORY:-./logs}"/>
<property name="LOG_FILENAME" value="komock"/>
Expand Down
10 changes: 5 additions & 5 deletions src/test/kotlin/ua/com/lavi/komock/RoutingTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ class RoutingTest {

val routingTable: RoutingTable = RoutingTable()

assertTrue(routingTable.getRouteMap().isEmpty())
assertTrue(routingTable.getFullRouteMap().isEmpty())

val beforeRouteHandler = object : BeforeRouteHandler {
override fun handle(request: Request, response: Response) {}
Expand All @@ -262,20 +262,20 @@ class RoutingTest {
routingTable.find(HttpMethod.PUT, "/someRoute") ?: fail("It should not be null")
routingTable.find(HttpMethod.DELETE, "/mask/sdfsdf/newroute") ?: fail("It should not be null")
routingTable.find(HttpMethod.POST, "/newmask/ololo/routeagain/trololo/maskagain") ?: fail("It should not be null")
assertTrue(routingTable.getRouteMap().size == 3)
assertTrue(routingTable.getFullRouteMap().size == 3)

routingTable.deleteRoute("/someRoute", HttpMethod.PUT)
routingTable.deleteRoute("/someRoute/*", HttpMethod.PUT)
routingTable.deleteRoute("/someRoute*", HttpMethod.PUT)
routingTable.deleteRoute("someRoute*", HttpMethod.PUT)
routingTable.deleteRoute("/someRoute", HttpMethod.GET)
assertTrue(routingTable.getRouteMap().size == 2)
assertTrue(routingTable.getFullRouteMap().size == 2)

routingTable.deleteRoute("/mask/*/newroute", HttpMethod.DELETE)
assertTrue(routingTable.getRouteMap().size == 1)
assertTrue(routingTable.getFullRouteMap().size == 1)

routingTable.clearRoutes()
assertTrue(routingTable.getRouteMap().isEmpty())
assertTrue(routingTable.getFullRouteMap().isEmpty())

}

Expand Down

0 comments on commit 243d833

Please sign in to comment.