Skip to content

Commit

Permalink
Cleanup kotlin loader
Browse files Browse the repository at this point in the history
  • Loading branch information
lburgazzoli committed Mar 25, 2020
1 parent f6caf9a commit 108e4d2
Show file tree
Hide file tree
Showing 6 changed files with 106 additions and 40 deletions.
5 changes: 0 additions & 5 deletions camel-k-loader-kotlin/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,6 @@
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-script-util</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,21 @@
*/
package org.apache.camel.k.loader.kotlin

import org.apache.camel.RuntimeCamelException
import org.apache.camel.builder.endpoint.EndpointRouteBuilder
import org.apache.camel.k.Runtime
import org.apache.camel.k.Source
import org.apache.camel.k.SourceLoader
import org.apache.camel.k.loader.kotlin.dsl.IntegrationConfiguration
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.InputStream
import java.io.InputStreamReader
import kotlin.script.experimental.api.ResultValue
import kotlin.script.experimental.api.ScriptDiagnostic
import kotlin.script.experimental.api.ScriptEvaluationConfiguration
import kotlin.script.experimental.api.constructorArgs
import kotlin.script.experimental.api.valueOrNull
import kotlin.script.experimental.host.toScriptSource
import kotlin.script.experimental.jvm.BasicJvmScriptEvaluator
import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost
Expand All @@ -35,7 +39,51 @@ import kotlin.script.experimental.jvmhost.createJvmCompilationConfigurationFromT

class KotlinSourceLoader : SourceLoader {
companion object {
val LOGGER : Logger = LoggerFactory.getLogger(KotlinSourceLoader::class.java)
private val LOGGER : Logger = LoggerFactory.getLogger(KotlinSourceLoader::class.java)

@JvmStatic
fun load(inputStream: InputStream): EndpointRouteBuilder {
return object : EndpointRouteBuilder() {
@Throws(Exception::class)
override fun configure() {
load(inputStream, this)
}
}
}

@JvmStatic
fun load(inputStream: InputStream, builder: EndpointRouteBuilder) {
val compiler = JvmScriptCompiler()
val evaluator = BasicJvmScriptEvaluator()
val host = BasicJvmScriptingHost(compiler = compiler, evaluator = evaluator)
val config = createJvmCompilationConfigurationFromTemplate<IntegrationConfiguration>()

val result = host.eval(
InputStreamReader(inputStream).readText().toScriptSource(),
config,
ScriptEvaluationConfiguration {
//
// Arguments used to initialize the script base class
//
constructorArgs(builder)
}
)

// ensure that evaluation errors propagation
when(val rv = result.valueOrNull()?.returnValue) {
is ResultValue.Error -> throw RuntimeCamelException(rv.error)
}

for (report in result.reports) {
when (report.severity) {
ScriptDiagnostic.Severity.FATAL -> LOGGER.error("{}", report.message, report.exception)
ScriptDiagnostic.Severity.ERROR -> LOGGER.error("{}", report.message, report.exception)
ScriptDiagnostic.Severity.WARNING -> LOGGER.warn("{}", report.message, report.exception)
ScriptDiagnostic.Severity.INFO -> LOGGER.info("{}", report.message)
ScriptDiagnostic.Severity.DEBUG -> LOGGER.debug("{}", report.message)
}
}
}
}

override fun getSupportedLanguages(): List<String> {
Expand All @@ -44,39 +92,13 @@ class KotlinSourceLoader : SourceLoader {

@Throws(Exception::class)
override fun load(runtime: Runtime, source: Source): SourceLoader.Result {
var builder = object : EndpointRouteBuilder() {
return SourceLoader.Result.on(object : EndpointRouteBuilder() {
@Throws(Exception::class)
override fun configure() {
val builder = this
val compiler = JvmScriptCompiler()
val evaluator = BasicJvmScriptEvaluator()
val host = BasicJvmScriptingHost(compiler = compiler, evaluator = evaluator)
val config = createJvmCompilationConfigurationFromTemplate<IntegrationConfiguration>()
val camelContext = runtime.camelContext

source.resolveAsInputStream(camelContext).use { `is` ->
val result = host.eval(
InputStreamReader(`is`).readText().toScriptSource(),
config,
ScriptEvaluationConfiguration {
//
// Arguments used to initialize the script base class
//
constructorArgs(builder)
}
)

for (report in result.reports) {
when (report.severity) {
ScriptDiagnostic.Severity.ERROR -> LOGGER.error("{}", report.message, report.exception)
ScriptDiagnostic.Severity.WARNING -> LOGGER.warn("{}", report.message, report.exception)
else -> LOGGER.info("{}", report.message)
}
}
source.resolveAsInputStream(runtime.camelContext).use {
load(it, this)
}
}
}

return SourceLoader.Result.on(builder)
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,12 @@ import org.apache.camel.Exchange
import org.apache.camel.Predicate
import org.apache.camel.Processor
import org.apache.camel.builder.endpoint.EndpointBuilderFactory
import kotlin.reflect.full.createInstance

class BeansConfiguration(
val context: CamelContext) : EndpointBuilderFactory {

inline fun <reified T : Any> bean(name: String, block: T.() -> Unit) {
var bean = T::class.createInstance()
val bean = context.injector.newInstance(T::class.java)
bean.block()

context.registry.bind(name, T::class.java, bean)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,20 @@ package org.apache.camel.k.loader.kotlin.dsl

import org.apache.camel.CamelContext
import org.apache.camel.Component
import org.slf4j.Logger
import org.slf4j.LoggerFactory

class ComponentsConfiguration(val context: CamelContext) {
companion object {
val LOGGER: Logger = LoggerFactory.getLogger(ComponentsConfiguration::class.java)
}

inline fun <reified T : Component> component(name: String, block: T.() -> Unit) : T {
var target = context.getComponent(name, true, false)
var bind = false

if (target != null && target !is T) {
throw IllegalArgumentException("Type mismatch, expected: " + T::class.java + ", got: " + target.javaClass)
if (target != null && !T::class.java.isInstance(target)) {
throw IllegalArgumentException("Type mismatch, expected: ${T::class.java}, got: ${target.javaClass}")
}

// if the component is not found, let's create a new one. This is
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package org.apache.camel.k.loader.kotlin.dsl

import org.apache.camel.Predicate
import org.apache.camel.Processor
import org.apache.camel.RuntimeCamelException
import org.apache.camel.component.jackson.JacksonDataFormat
import org.apache.camel.component.log.LogComponent
import org.apache.camel.component.seda.SedaComponent
Expand All @@ -31,7 +32,12 @@ import org.apache.camel.model.rest.PostVerbDefinition
import org.apache.camel.processor.FatalFallbackErrorHandler
import org.apache.camel.support.DefaultHeaderFilterStrategy
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.lang.IllegalArgumentException
import java.lang.RuntimeException
import javax.sql.DataSource

class IntegrationTest {
Expand Down Expand Up @@ -104,6 +110,17 @@ class IntegrationTest {
assertThat(log.exchangeFormatter).isNotNull
}

@Test
fun `load integration with components configuration error`() {
val context = DefaultCamelContext()
val runtime = Runtime.on(context)

assertThatExceptionOfType(RuntimeCamelException::class.java)
.isThrownBy { forRoutes("classpath:routes-with-components-configuration-error.kts").accept(Runtime.Phase.ConfigureRoutes, runtime) }
.withCauseInstanceOf(IllegalArgumentException::class.java)
.withMessageContaining("Type mismatch, expected: class org.apache.camel.component.log.LogComponent, got: class org.apache.camel.component.seda.SedaComponent");
}

@Test
fun `load integration with languages configuration`() {
val context = DefaultCamelContext()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
import org.apache.camel.Exchange

camel {
components {
component<org.apache.camel.component.log.LogComponent>("seda") {
setExchangeFormatter {
e: Exchange -> "" + e.getIn().body
}
}
}
}

0 comments on commit 108e4d2

Please sign in to comment.