2 * Copyright © 2017-2018 AT&T Intellectual Property.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.onap.ccsdk.apps.controllerblueprints.core.script
19 import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException
21 import java.io.InputStream
23 import javax.script.ScriptEngineManager
24 import kotlin.script.experimental.api.ResultValue
25 import kotlin.script.experimental.api.ResultWithDiagnostics
26 import kotlin.script.experimental.api.resultOrNull
27 import kotlin.script.experimental.host.toScriptSource
28 import kotlin.script.experimental.jvmhost.createJvmCompilationConfigurationFromTemplate
31 open class BluePrintScriptService(classLoader: ClassLoader? = Thread.currentThread().contextClassLoader) {
34 * Get the Script Class instance
36 inline fun <reified T> scriptClassNewInstance(scriptFile: File, scriptClassName: String): T {
38 val compilationConfiguration = createJvmCompilationConfigurationFromTemplate<ComponentScript>()
40 val scriptEvaluator = BluePrintScriptEvaluator(scriptClassName)
42 val evalResponse = BlueprintScriptingHost(scriptEvaluator).eval(scriptFile.toScriptSource(), compilationConfiguration,
46 is ResultWithDiagnostics.Success -> {
47 val returnValue = evalResponse.resultOrNull()?.returnValue as ResultValue.Value
48 return returnValue.value.castOrError()
50 is ResultWithDiagnostics.Failure -> {
51 throw BluePrintProcessorException(evalResponse.reports.joinToString("\n"))
54 throw BluePrintProcessorException("Failed to process script ${scriptFile.absolutePath}")
60 val engine = ScriptEngineManager(classLoader).getEngineByExtension("kts")
62 inline fun <R> safeEval(evaluation: () -> R?) = try {
64 } catch (e: Exception) {
65 throw BluePrintProcessorException("Cannot load script", e)
68 inline fun <reified T> Any?.castOrError() = takeIf { it is T }?.let { it as T }
69 ?: throw IllegalArgumentException("Cannot cast $this to expected type ${T::class}")
71 inline fun <reified T> load(script: String): T = safeEval { engine.eval(script) }.castOrError()
73 inline fun <reified T> load(reader: Reader): T = safeEval { engine.eval(reader) }.castOrError()
75 inline fun <reified T> load(inputStream: InputStream): T = load(inputStream.reader())
77 inline fun <reified T> loadAll(vararg inputStream: InputStream): List<T> = inputStream.map(::load)