diff options
42 files changed, 1352 insertions, 732 deletions
diff --git a/components/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/script/BluePrintScriptConfiguration.kt b/components/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/script/BluePrintScriptConfiguration.kt deleted file mode 100644 index f7bfb857..00000000 --- a/components/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/script/BluePrintScriptConfiguration.kt +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * 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 org.onap.ccsdk.apps.controllerblueprints.core.script - -import org.jetbrains.kotlin.script.util.LocalFilesResolver -import java.io.File -import kotlin.script.dependencies.ScriptContents -import kotlin.script.dependencies.ScriptDependenciesResolver -import kotlin.script.experimental.annotations.KotlinScript -import kotlin.script.experimental.api.* -import kotlin.script.experimental.jvm.JvmDependency -import kotlin.script.experimental.jvm.dependenciesFromCurrentContext -import kotlin.script.experimental.jvm.jvm - - -@KotlinScript(fileExtension = "kts", - compilationConfiguration = ComponentScriptConfiguration::class) -abstract class ComponentScript { - -} - -object ComponentScriptConfiguration : ScriptCompilationConfiguration( - { - // defaultImports(DependsOn::class, Repository::class) - jvm { - dependenciesFromCurrentContext( - wholeClasspath = true - ) - } -// refineConfiguration { -// onAnnotations(DependsOn::class, Repository::class, handler = ::configureLocalFileDepsOnAnnotations) -// } - } -) - - -private val resolver = LocalFilesResolver() - -fun configureLocalFileDepsOnAnnotations(context: ScriptConfigurationRefinementContext): - ResultWithDiagnostics<ScriptCompilationConfiguration> { - - val annotations = context.collectedData?.get(ScriptCollectedData.foundAnnotations)?.takeIf { it.isNotEmpty() } - ?: return context.compilationConfiguration.asSuccess() - - val scriptContents = object : ScriptContents { - override val annotations: Iterable<Annotation> = annotations - override val file: File? = null - override val text: CharSequence? = null - } - - val diagnostics = arrayListOf<ScriptDiagnostic>() - - fun report(severity: ScriptDependenciesResolver.ReportSeverity, message: String, position: ScriptContents.Position?) { - //TODO - } - - return try { - val newDepsFromResolver = resolver.resolve(scriptContents, emptyMap(), ::report, null).get() - ?: return context.compilationConfiguration.asSuccess(diagnostics) - - val resolvedClasspath = newDepsFromResolver.classpath.toList().takeIf { it.isNotEmpty() } - ?: return context.compilationConfiguration.asSuccess(diagnostics) - - ScriptCompilationConfiguration(context.compilationConfiguration) { - dependencies.append(JvmDependency(resolvedClasspath)) - - }.asSuccess(diagnostics) - - } catch (e: Throwable) { - ResultWithDiagnostics.Failure(*diagnostics.toTypedArray(), e.asDiagnostics()) - } -}
\ No newline at end of file diff --git a/components/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/script/BluePrintScriptService.kt b/components/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/script/BluePrintScriptService.kt deleted file mode 100644 index 8ae09151..00000000 --- a/components/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/script/BluePrintScriptService.kt +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * 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 org.onap.ccsdk.apps.controllerblueprints.core.script - -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import java.io.File -import java.io.InputStream -import java.io.Reader -import javax.script.ScriptEngineManager -import kotlin.script.experimental.api.ResultValue -import kotlin.script.experimental.api.ResultWithDiagnostics -import kotlin.script.experimental.api.resultOrNull -import kotlin.script.experimental.host.toScriptSource -import kotlin.script.experimental.jvmhost.createJvmCompilationConfigurationFromTemplate - - -open class BluePrintScriptService(classLoader: ClassLoader? = Thread.currentThread().contextClassLoader) { - - /** - * Get the Script Class instance - */ - inline fun <reified T> scriptClassNewInstance(scriptFile: File, scriptClassName: String): T { - - val compilationConfiguration = createJvmCompilationConfigurationFromTemplate<ComponentScript>() - - val scriptEvaluator = BluePrintScriptEvaluator(scriptClassName) - - val evalResponse = BlueprintScriptingHost(scriptEvaluator).eval(scriptFile.toScriptSource(), compilationConfiguration, - null) - - when (evalResponse) { - is ResultWithDiagnostics.Success -> { - val returnValue = evalResponse.resultOrNull()?.returnValue as ResultValue.Value - return returnValue.value.castOrError() - } - is ResultWithDiagnostics.Failure -> { - throw BluePrintProcessorException(evalResponse.reports.joinToString("\n")) - } - else -> { - throw BluePrintProcessorException("Failed to process script ${scriptFile.absolutePath}") - } - } - - } - - val engine = ScriptEngineManager(classLoader).getEngineByExtension("kts") - - inline fun <R> safeEval(evaluation: () -> R?) = try { - evaluation() - } catch (e: Exception) { - throw BluePrintProcessorException("Cannot load script", e) - } - - inline fun <reified T> Any?.castOrError() = takeIf { it is T }?.let { it as T } - ?: throw IllegalArgumentException("Cannot cast $this to expected type ${T::class}") - - inline fun <reified T> load(script: String): T = safeEval { engine.eval(script) }.castOrError() - - inline fun <reified T> load(reader: Reader): T = safeEval { engine.eval(reader) }.castOrError() - - inline fun <reified T> load(inputStream: InputStream): T = load(inputStream.reader()) - - inline fun <reified T> loadAll(vararg inputStream: InputStream): List<T> = inputStream.map(::load) -} diff --git a/components/core/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/script/BluePrintScriptServiceTest.kt b/components/core/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/script/BluePrintScriptServiceTest.kt deleted file mode 100644 index 5c5ad3ba..00000000 --- a/components/core/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/script/BluePrintScriptServiceTest.kt +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * 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 org.onap.ccsdk.apps.controllerblueprints.core.script - -import org.junit.Ignore -import org.junit.Test -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BlueprintFunctionNode -import java.io.File -import kotlin.test.assertEquals -import kotlin.test.assertNotNull - -class BluePrintScriptServiceTest { - - @Test - fun `invoke script`() { - val scriptContent = "11 + 11" - val value = BluePrintScriptService() - .load<Int>(scriptContent) - assertEquals(22, value, "failed to execute command") - } - - @Test - @Ignore - fun `invoke script component node`() { - - //println(classpathFromClasspathProperty()?.joinToString("\n")) - - val scriptFile = File("src/test/resources/scripts/SampleBlueprintFunctionNode.kts") - - val functionNode = BluePrintScriptService() - .scriptClassNewInstance<BlueprintFunctionNode<String, String>>(scriptFile, - "SampleBlueprintFunctionNode") - assertNotNull(functionNode, "failed to get instance from script") - } -}
\ No newline at end of file diff --git a/components/parent/pom.xml b/components/parent/pom.xml index b53f9f11..6d5c2c14 100644 --- a/components/parent/pom.xml +++ b/components/parent/pom.xml @@ -29,11 +29,11 @@ <name>Components Parent</name> <packaging>pom</packaging> <properties> - <spring.boot.version>2.1.1.RELEASE</spring.boot.version> - <spring.version>5.1.3.RELEASE</spring.version> - <kotlin.version>1.3.11</kotlin.version> - <kotlin.maven.version>1.3.11</kotlin.maven.version> - <kotlin.couroutines.version>1.1.0</kotlin.couroutines.version> + <spring.boot.version>2.1.2.RELEASE</spring.boot.version> + <spring.version>5.1.4.RELEASE</spring.version> + <kotlin.version>1.3.20</kotlin.version> + <kotlin.maven.version>1.3.20</kotlin.maven.version> + <kotlin.couroutines.version>1.1.1</kotlin.couroutines.version> <grpc.version>1.18.0</grpc.version> <protobuff.java.utils.version>3.6.1</protobuff.java.utils.version> <eelf.version>1.0.0</eelf.version> @@ -307,22 +307,6 @@ <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-kotlin</artifactId> </dependency> - <dependency> - <groupId>org.jetbrains.kotlin</groupId> - <artifactId>kotlin-compiler-embeddable</artifactId> - </dependency> - <dependency> - <groupId>org.jetbrains.kotlin</groupId> - <artifactId>kotlin-scripting-jvm-host</artifactId> - <!--Use kotlin-compiler-embeddable as koltin-compiler wrap--> - <!--guava dependency creating classpath issues at runtime--> - <exclusions> - <exclusion> - <groupId>org.jetbrains.kotlin</groupId> - <artifactId>kotlin-compiler</artifactId> - </exclusion> - </exclusions> - </dependency> <!-- GRPC Dependencies --> <dependency> <groupId>io.grpc</groupId> diff --git a/docs/index.rst b/docs/index.rst index 16f86845..2c7d9ab9 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,13 +1,50 @@ .. This work is licensed under a Creative Commons Attribution 4.0 International License. +.. http://creativecommons.org/licenses/by/4.0 +.. Copyright (C) 2019 IBM. CCSDK APPS DOCUMENTATION REPOSITORY ------------------------------------------------ .. toctree:: :maxdepth: 1 - Architecture - Installation - Configuration - Development - Logging - Release Notes +Introduction: +============= +APPS repository which contains all micro services for CCSDK module. +Also these are application that are intended to run outside of OpenDaylight +container.Modular feature implementation that is reusable across all controllers. + +Microservices: +============= + +Controller BluePrints Studio Processor +Blueprints processor +NetworkElementNameGen (NENG) +Vlan Tag API + + +Installation: +============= + +Steps +----- +To compile this code: + +1. Make sure your local Maven settings file ($HOME/.m2/settings.xml) contains +references to the ONAP repositories and OpenDaylight repositories. + +2. To compile all of CCSDK apps code + - git clone https://(LFID)@gerrit.onap.org/r/a/ccsdk/apps + - cd apps ; mvn clean install ; cd .. + + + +Logging: +============= +CCSDK uses slf4j to log messages to the standard OpenDaylight karaf.log +log file. + +Where to Access Information +--------------------------- +Logs are found within the SDNC docker container, in the directory +/opt/opendaylight/current/data/logs. +Release Notes diff --git a/docs/microservices/bluePrintsProcessor.rst b/docs/microservices/bluePrintsProcessor.rst new file mode 100644 index 00000000..adde1107 --- /dev/null +++ b/docs/microservices/bluePrintsProcessor.rst @@ -0,0 +1,10 @@ +.. This work is licensed under a Creative Commons Attribution 4.0 International License. +.. http://creativecommons. +.. Copyright (C) 2019 IBM. + +Blueprints Processor +==================== + +.. toctree:: + :maxdepth: 1 + :titlesonly:
\ No newline at end of file diff --git a/docs/microservices/controllerBlueprintStudioProcessor.rst b/docs/microservices/controllerBlueprintStudioProcessor.rst new file mode 100644 index 00000000..fc911229 --- /dev/null +++ b/docs/microservices/controllerBlueprintStudioProcessor.rst @@ -0,0 +1,10 @@ +.. This work is licensed under a Creative Commons Attribution 4.0 International License. +.. http://creativecommons. +.. Copyright (C) 2019 IBM. + +Controller Blueprints Studio Processor +====================================== + +.. toctree:: + :maxdepth: 1 + :titlesonly:
\ No newline at end of file diff --git a/docs/microservices/neng.rst b/docs/microservices/neng.rst new file mode 100644 index 00000000..b5461988 --- /dev/null +++ b/docs/microservices/neng.rst @@ -0,0 +1,10 @@ +.. This work is licensed under a Creative Commons Attribution 4.0 International License. +.. http://creativecommons. +.. Copyright (C) 2019 IBM. + +NetworkElementNameGen (NENG) +============================ + +.. toctree:: + :maxdepth: 1 + :titlesonly:
\ No newline at end of file diff --git a/docs/microservices/vlanTag.rst b/docs/microservices/vlanTag.rst new file mode 100644 index 00000000..c1d2fbef --- /dev/null +++ b/docs/microservices/vlanTag.rst @@ -0,0 +1,10 @@ +.. This work is licensed under a Creative Commons Attribution 4.0 International License. +.. http://creativecommons. +.. Copyright (C) 2019 IBM. + +Vlan Tag API +============ + +.. toctree:: + :maxdepth: 1 + :titlesonly:
\ No newline at end of file diff --git a/docs/release-notes.rst b/docs/release-notes.rst new file mode 100644 index 00000000..174c4422 --- /dev/null +++ b/docs/release-notes.rst @@ -0,0 +1,14 @@ +.. This work is licensed under a Creative Commons Attribution 4.0 International License. +.. Copyright (C) 2019 IBM. + +Release Notes +############# + +Version: 0.4.1 +************** + +:Release Date: 2018-11-30 + +Quick Links: + + Wiki Release note<https://wiki.onap.org/display/DW/CCSDK+%3A+Dublin%3A+Release+Planning+Template>
\ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/PrimaryDataResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/PrimaryDataResourceAssignmentProcessor.kt index 94271830..5552e75e 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/PrimaryDataResourceAssignmentProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/PrimaryDataResourceAssignmentProcessor.kt @@ -19,7 +19,7 @@ package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.pr import com.fasterxml.jackson.databind.node.JsonNodeFactory import com.fasterxml.jackson.databind.node.NullNode -import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.service.PrimaryDBLibGenericService +import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.PrimaryDBLibGenericService import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils import org.onap.ccsdk.apps.controllerblueprints.core.* diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt index 574d235b..b6fb5faa 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt @@ -24,7 +24,7 @@ import org.onap.ccsdk.apps.blueprintsprocessor.core.BlueprintPropertyConfigurati import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.apps.blueprintsprocessor.core.utils.PayloadUtils import org.onap.ccsdk.apps.blueprintsprocessor.db.BluePrintDBLibConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.service.PrimaryDBLibGenericService +import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.PrimaryDBLibGenericService import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor.* import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.apps.controllerblueprints.core.asJsonNode diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt index ef69eb51..3dd12e51 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt @@ -24,7 +24,7 @@ import org.onap.ccsdk.apps.blueprintsprocessor.core.BlueprintPropertyConfigurati import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.apps.blueprintsprocessor.core.utils.PayloadUtils import org.onap.ccsdk.apps.blueprintsprocessor.db.BluePrintDBLibConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.service.PrimaryDBLibGenericService +import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.PrimaryDBLibGenericService import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor.* import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibGenericService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibGenericService.kt index 86420f9a..aee74d3f 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibGenericService.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibGenericService.kt @@ -25,4 +25,20 @@ interface BluePrintDBLibGenericService { fun query(sql: String, params: Map<String, Any>): List<Map<String, Any>> fun update(sql: String, params: Map<String, Any>): Int +} + +abstract class AbstractDBLibGenericService(private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate) + : BluePrintDBLibGenericService { + + override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate { + return namedParameterJdbcTemplate + } + + override fun query(sql: String, params: Map<String, Any>): List<Map<String, Any>> { + return namedParameterJdbcTemplate.queryForList(sql, params) + } + + override fun update(sql: String, params: Map<String, Any>): Int { + return namedParameterJdbcTemplate.update(sql, params) + } }
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/service/PrimaryDBLibGenericService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDBLibGenericService.kt index 87f32ef2..0e0f1e9c 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/service/PrimaryDBLibGenericService.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDBLibGenericService.kt @@ -14,25 +14,15 @@ * limitations under the License. */ -package org.onap.ccsdk.apps.blueprintsprocessor.db.primary.service +package org.onap.ccsdk.apps.blueprintsprocessor.db.primary +import org.onap.ccsdk.apps.blueprintsprocessor.db.AbstractDBLibGenericService import org.onap.ccsdk.apps.blueprintsprocessor.db.BluePrintDBLibGenericService import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.stereotype.Service @Service -class PrimaryDBLibGenericService(private val primaryNamedParameterJdbcTemplate: NamedParameterJdbcTemplate) - : BluePrintDBLibGenericService { +open class PrimaryDBLibGenericService(private val primaryNamedParameterJdbcTemplate: NamedParameterJdbcTemplate) + : AbstractDBLibGenericService(primaryNamedParameterJdbcTemplate) { - override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate { - return primaryNamedParameterJdbcTemplate - } - - override fun query(sql: String, params: Map<String, Any>): List<Map<String, Any>> { - return primaryNamedParameterJdbcTemplate.queryForList(sql, params) - } - - override fun update(sql: String, params: Map<String, Any>): Int { - return primaryNamedParameterJdbcTemplate.update(sql, params) - } }
\ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt index b80f9909..fb0bc567 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt @@ -19,7 +19,6 @@ package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api import io.grpc.StatusException import io.grpc.stub.StreamObserver -import org.apache.commons.io.FileUtils import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils.currentTimestamp import org.onap.ccsdk.apps.controllerblueprints.common.api.CommonHeader @@ -82,9 +81,11 @@ class BluePrintManagementGRPCHandler(private val bluePrintCoreConfiguration: Blu log.info("request(${request.commonHeader.requestId}): Writing CBA File under :${blueprintDir.absolutePath}") if (blueprintDir.exists()) { log.info("request(${request.commonHeader.requestId}): Re-creating blueprint directory(${blueprintDir.absolutePath})") - FileUtils.deleteDirectory(blueprintDir.parentFile) + //FileUtils.deleteDirectory(blueprintDir.parentFile) + blueprintDir.parentFile.deleteRecursively() } - FileUtils.forceMkdir(blueprintDir.parentFile) + blueprintDir.parentFile.mkdirs() + //FileUtils.forceMkdir(blueprintDir.parentFile) blueprintDir.writeBytes(request.fileChunk.chunk.toByteArray()).apply { log.info("request(${request.commonHeader.requestId}): CBA file(${blueprintDir.absolutePath} written successfully") } diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt index 4da3b745..264e2aea 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt @@ -19,7 +19,6 @@ package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api import com.google.protobuf.ByteString import io.grpc.testing.GrpcServerRule -import org.apache.commons.io.FileUtils import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -34,7 +33,6 @@ import org.springframework.test.annotation.DirtiesContext import org.springframework.test.context.TestPropertySource import org.springframework.test.context.junit4.SpringRunner import java.io.File -import java.nio.file.Paths import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.assertEquals @@ -59,12 +57,12 @@ class BluePrintManagementGRPCHandlerTest { grpcServerRule.serviceRegistry.addService(bluePrintManagementGRPCHandler) } - //@AfterTest + @AfterTest fun cleanDir() { //TODO It's giving fluctuating results, need to look for another way to cleanup // works sometimes otherwise results IO Exception // Most probably bufferReader stream is not getting closed when cleanDir is getting invoked - FileUtils.deleteDirectory(File("./target/blueprints")) + File("./target/blueprints").deleteRecursively() } @Test @@ -95,7 +93,7 @@ class BluePrintManagementGRPCHandlerTest { } private fun createInputRequest(id: String): BluePrintManagementInput { - val file = Paths.get("./src/test/resources/test-cba.zip").toFile() + val file = File("./src/test/resources/test-cba.zip") assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") val commonHeader = CommonHeader diff --git a/ms/blueprintsprocessor/parent/pom.xml b/ms/blueprintsprocessor/parent/pom.xml index be187726..472b466b 100755 --- a/ms/blueprintsprocessor/parent/pom.xml +++ b/ms/blueprintsprocessor/parent/pom.xml @@ -31,11 +31,11 @@ <name>Blueprints Processor Parent</name> <description>Blueprints Processor Parent</description> <properties> - <spring.boot.version>2.1.1.RELEASE</spring.boot.version> - <spring.version>5.1.3.RELEASE</spring.version> - <kotlin.version>1.3.11</kotlin.version> - <kotlin.maven.version>1.3.11</kotlin.maven.version> - <kotlin.couroutines.version>1.1.0</kotlin.couroutines.version> + <spring.boot.version>2.1.2.RELEASE</spring.boot.version> + <spring.version>5.1.4.RELEASE</spring.version> + <kotlin.version>1.3.20</kotlin.version> + <kotlin.maven.version>1.3.20</kotlin.maven.version> + <kotlin.couroutines.version>1.1.1</kotlin.couroutines.version> <grpc.version>1.18.0</grpc.version> <protobuff.java.utils.version>3.6.1</protobuff.java.utils.version> <eelf.version>1.0.0</eelf.version> @@ -130,16 +130,23 @@ <artifactId>kotlin-stdlib-common</artifactId> <version>${kotlin.version}</version> </dependency> + <!--Use kotlin-compiler-embeddable instead koltin-compiler wrap--> + <!--guava dependency inside kotlin-compiler creating classpath issues at runtime--> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-scripting-jvm-host</artifactId> <version>${kotlin.version}</version> + <exclusions> + <exclusion> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-compile</artifactId> + </exclusion> + </exclusions> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-compiler-embeddable</artifactId> <version>${kotlin.version}</version> - <scope>runtime</scope> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> diff --git a/ms/controllerblueprints/application/src/main/resources/application.properties b/ms/controllerblueprints/application/src/main/resources/application.properties index b6d509ce..ec61be48 100755 --- a/ms/controllerblueprints/application/src/main/resources/application.properties +++ b/ms/controllerblueprints/application/src/main/resources/application.properties @@ -41,7 +41,7 @@ spring.jpa.properties.hibernate.use_sql_comments=true spring.jpa.properties.hibernate.format_sql=true # spring.datasource.url, spring.datasource.username,spring.datasource.password may be overridden by ENV variables -spring.datasource.url=jdbc:mysql://db:3306/sdnctl +spring.datasource.url=jdbc:mysql://localhost:3306/sdnctl spring.datasource.username=sdnctl spring.datasource.password=sdnctl spring.datasource.driver-class-name=org.mariadb.jdbc.Driver diff --git a/ms/controllerblueprints/modules/blueprint-scripts/pom.xml b/ms/controllerblueprints/modules/blueprint-scripts/pom.xml new file mode 100644 index 00000000..46c88b4c --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/pom.xml @@ -0,0 +1,59 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ Copyright © 2017-2018 AT&T Intellectual Property. + ~ + ~ 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. + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <parent> + <artifactId>modules</artifactId> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <version>0.4.1-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>blueprint-scripts</artifactId> + <name>Controller Blueprints Scripts</name> + + <dependencies> + <dependency> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <artifactId>resource-dict</artifactId> + </dependency> + <dependency> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-compiler-embeddable</artifactId> + </dependency> + <dependency> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-scripting-jvm-host</artifactId> + <exclusions> + <exclusion> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-compiler</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-script-util</artifactId> + </dependency> + <dependency> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-script-runtime</artifactId> + </dependency> + </dependencies> + +</project>
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintCompiledScript.kt b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintCompiledScript.kt new file mode 100644 index 00000000..8ac915bd --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintCompiledScript.kt @@ -0,0 +1,56 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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 org.onap.ccsdk.apps.controllerblueprints.scripts + +import java.io.File +import java.io.Serializable +import java.net.URL +import java.net.URLClassLoader +import kotlin.reflect.KClass +import kotlin.script.experimental.api.* + +open class BluePrintCompiledScript<out JarFile : File>( + private val scriptCompilationConfiguration: ScriptCompilationConfiguration, + private val compiledJar: File) : + CompiledScript<JarFile>, Serializable { + + lateinit var scriptClassFQName: String + + override val compilationConfiguration: ScriptCompilationConfiguration + get() = scriptCompilationConfiguration + + override suspend fun getClass(scriptEvaluationConfiguration: ScriptEvaluationConfiguration?): ResultWithDiagnostics<KClass<*>> = try { + + val baseClassLoader = Thread.currentThread().contextClassLoader + + val urls = arrayListOf<URL>() + urls.add(compiledJar.toURI().toURL()) + val classLoaderWithDependencies = URLClassLoader(urls.toTypedArray(), baseClassLoader) + + val clazz = classLoaderWithDependencies.loadClass(scriptClassFQName).kotlin + clazz.asSuccess() + } catch (e: Throwable) { + ResultWithDiagnostics.Failure( + ScriptDiagnostic( + "Unable to instantiate class $scriptClassFQName", + exception = e + ) + ) + } + +} + diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintCompilerProxy.kt b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintCompilerProxy.kt new file mode 100644 index 00000000..7e9e8688 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintCompilerProxy.kt @@ -0,0 +1,150 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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 org.onap.ccsdk.apps.controllerblueprints.scripts + +import org.jetbrains.kotlin.com.intellij.openapi.util.Disposer +import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys +import org.jetbrains.kotlin.cli.common.config.addKotlinSourceRoots +import org.jetbrains.kotlin.cli.common.environment.setIdeaIoUseFallback +import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport +import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation +import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity +import org.jetbrains.kotlin.cli.common.messages.MessageCollector +import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles +import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment +import org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler +import org.jetbrains.kotlin.cli.jvm.config.JvmClasspathRoot +import org.jetbrains.kotlin.config.* +import org.slf4j.LoggerFactory +import java.io.File +import kotlin.script.experimental.api.* +import kotlin.script.experimental.host.ScriptingHostConfiguration +import kotlin.script.experimental.jvm.util.classpathFromClasspathProperty +import kotlin.script.experimental.jvmhost.KJvmCompilerProxy + +open class BluePrintsCompilerProxy(private val hostConfiguration: ScriptingHostConfiguration) : KJvmCompilerProxy { + + private val log = LoggerFactory.getLogger(BluePrintsCompilerProxy::class.java)!! + + override fun compile(script: SourceCode, scriptCompilationConfiguration: ScriptCompilationConfiguration) + : ResultWithDiagnostics<CompiledScript<*>> { + + val messageCollector = ScriptDiagnosticsMessageCollector() + + fun failure(vararg diagnostics: ScriptDiagnostic): ResultWithDiagnostics.Failure = + ResultWithDiagnostics.Failure(*messageCollector.diagnostics.toTypedArray(), *diagnostics) + + // Compile the Code + try { + + log.trace("Scripting Host Configuration : $hostConfiguration") + + setIdeaIoUseFallback() + + val blueprintSourceCode = script as BluePrintSourceCode + + val compiledJarFile = blueprintSourceCode.targetJarFile + + if (!compiledJarFile.exists() || blueprintSourceCode.regenerate) { + + var environment: KotlinCoreEnvironment? = null + + val rootDisposable = Disposer.newDisposable() + + val compilerConfiguration = CompilerConfiguration().apply { + + put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, messageCollector) + put(CommonConfigurationKeys.MODULE_NAME, blueprintSourceCode.moduleName) + put(JVMConfigurationKeys.OUTPUT_JAR, compiledJarFile) + put(JVMConfigurationKeys.RETAIN_OUTPUT_IN_MEMORY, false) + + // Load Current Class loader to Compilation Class loader + val currentClassLoader = classpathFromClasspathProperty() + currentClassLoader?.forEach { + add(CLIConfigurationKeys.CONTENT_ROOTS, JvmClasspathRoot(it)) + } + + // Add all Kotlin Sources + addKotlinSourceRoots(blueprintSourceCode.blueprintKotlinSources) + + languageVersionSettings = LanguageVersionSettingsImpl( + LanguageVersion.LATEST_STABLE, ApiVersion.LATEST_STABLE, mapOf(AnalysisFlags.skipMetadataVersionCheck to true) + ) + } + + //log.info("Executing with compiler configuration : $compilerConfiguration") + + environment = KotlinCoreEnvironment.createForProduction(rootDisposable, compilerConfiguration, + EnvironmentConfigFiles.JVM_CONFIG_FILES) + + // Compile Kotlin Sources + val compiled = KotlinToJVMBytecodeCompiler.compileBunchOfSources(environment) + + log.info("Generated jar(${compiledJarFile.absolutePath}) status : $compiled}") + + val analyzerWithCompilerReport = AnalyzerWithCompilerReport(messageCollector, + environment.configuration.languageVersionSettings) + + if (analyzerWithCompilerReport.hasErrors()) { + return failure() + } + } + + val res = BluePrintCompiledScript<File>(scriptCompilationConfiguration, compiledJarFile) + + return ResultWithDiagnostics.Success(res, messageCollector.diagnostics) + + } catch (ex: Throwable) { + return failure(ex.asDiagnostics()) + } + } +} + +class ScriptDiagnosticsMessageCollector : MessageCollector { + + private val _diagnostics = arrayListOf<ScriptDiagnostic>() + + val diagnostics: List<ScriptDiagnostic> get() = _diagnostics + + override fun clear() { + _diagnostics.clear() + } + + override fun hasErrors(): Boolean = + _diagnostics.any { it.severity == ScriptDiagnostic.Severity.ERROR } + + + override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) { + val mappedSeverity = when (severity) { + CompilerMessageSeverity.EXCEPTION, + CompilerMessageSeverity.ERROR -> ScriptDiagnostic.Severity.ERROR + CompilerMessageSeverity.STRONG_WARNING, + CompilerMessageSeverity.WARNING -> ScriptDiagnostic.Severity.WARNING + CompilerMessageSeverity.INFO -> ScriptDiagnostic.Severity.INFO + CompilerMessageSeverity.LOGGING -> ScriptDiagnostic.Severity.DEBUG + else -> null + } + if (mappedSeverity != null) { + val mappedLocation = location?.let { + if (it.line < 0 && it.column < 0) null // special location created by CompilerMessageLocation.create + else SourceCode.Location(SourceCode.Position(it.line, it.column)) + } + _diagnostics.add(ScriptDiagnostic(message, mappedSeverity, location?.path, mappedLocation)) + } + } +} + diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintScriptConfiguration.kt b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintScriptConfiguration.kt new file mode 100644 index 00000000..3b3a5907 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BluePrintScriptConfiguration.kt @@ -0,0 +1,61 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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 org.onap.ccsdk.apps.controllerblueprints.scripts + +import java.io.File +import kotlin.script.experimental.annotations.KotlinScript +import kotlin.script.experimental.api.ScriptCompilationConfiguration +import kotlin.script.experimental.api.SourceCode +import kotlin.script.experimental.api.defaultImports +import kotlin.script.experimental.jvm.jvm +import kotlin.script.experimental.jvm.util.classpathFromClassloader + +@KotlinScript( + fileExtension = "cba.kts", + compilationConfiguration = BluePrintScripCompilationConfiguration::class, + displayName = "Controller Blueprint Archive Kotlin Scripts" +) +abstract class BluePrintKotlinScript + +object BluePrintScripCompilationConfiguration : ScriptCompilationConfiguration( + { + defaultImports( + "org.onap.ccsdk.apps.controllerblueprints.core.*", + "org.onap.ccsdk.apps.controllerblueprints.core.data.*", + "org.onap.ccsdk.apps.controllerblueprints.core.interfaces.*", + "org.onap.ccsdk.apps.controllerblueprints.core.services.*", + "org.onap.ccsdk.apps.controllerblueprints.core.utils.*") + jvm { + classpathFromClassloader(BluePrintScripCompilationConfiguration::class.java.classLoader) + } + } +) + +open class BluePrintSourceCode : SourceCode { + lateinit var blueprintKotlinSources: MutableList<String> + lateinit var moduleName: String + lateinit var targetJarFile: File + var regenerate: Boolean = false + + override val text: String + get() = "" + + override val locationId: String? = null + + override val name: String? + get() = moduleName +} diff --git a/components/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/script/BlueprintScriptingHost.kt b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BlueprintScriptingHost.kt index bda20a44..59ce4abb 100644 --- a/components/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/script/BlueprintScriptingHost.kt +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BlueprintScriptingHost.kt @@ -14,19 +14,21 @@ * limitations under the License. */ -package org.onap.ccsdk.apps.controllerblueprints.core.script +package org.onap.ccsdk.apps.controllerblueprints.scripts import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException import org.slf4j.LoggerFactory +import java.util.* import kotlin.script.experimental.api.* import kotlin.script.experimental.host.BasicScriptingHost import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration import kotlin.script.experimental.jvmhost.JvmScriptCompiler +import kotlin.script.experimental.jvmhost.impl.withDefaults -val defaultBlueprintScriptCompiler = JvmScriptCompiler(defaultJvmScriptingHostConfiguration) +val blueprintScriptCompiler = JvmScriptCompiler(defaultJvmScriptingHostConfiguration, + BluePrintsCompilerProxy(defaultJvmScriptingHostConfiguration.withDefaults())) -open class BlueprintScriptingHost(evaluator: ScriptEvaluator -) : BasicScriptingHost(defaultBlueprintScriptCompiler, evaluator) { +open class BlueprintScriptingHost(evaluator: ScriptEvaluator) : BasicScriptingHost(blueprintScriptCompiler, evaluator) { override fun eval( script: SourceCode, @@ -44,19 +46,24 @@ open class BlueprintScriptingHost(evaluator: ScriptEvaluator } -open class BluePrintScriptEvaluator(private val scriptClassName: String) : ScriptEvaluator { +open class BluePrintScriptEvaluator<T>(private val scriptClassName: String) : ScriptEvaluator { - val log = LoggerFactory.getLogger(BluePrintScriptEvaluator::class.java)!! + private val log = LoggerFactory.getLogger(BluePrintScriptEvaluator::class.java)!! override suspend operator fun invoke( compiledScript: CompiledScript<*>, scriptEvaluationConfiguration: ScriptEvaluationConfiguration? ): ResultWithDiagnostics<EvaluationResult> = try { + log.info("Getting class name($scriptClassName) of type() from the compiled sources ") + val bluePrintCompiledScript = compiledScript as BluePrintCompiledScript + bluePrintCompiledScript.scriptClassFQName = scriptClassName + val res = compiledScript.getClass(scriptEvaluationConfiguration) when (res) { is ResultWithDiagnostics.Failure -> res is ResultWithDiagnostics.Success -> { + val scriptClass = res.value val args = ArrayList<Any?>() scriptEvaluationConfiguration?.get(ScriptEvaluationConfiguration.providedProperties)?.forEach { @@ -69,21 +76,13 @@ open class BluePrintScriptEvaluator(private val scriptClassName: String) : Scrip args.addAll(it) } - val completeScriptClass = "Script\$$scriptClassName" - log.info("Searching for class type($completeScriptClass)") - /** - * Search for Class Name - */ - val instanceClass = scriptClass.java.classes - .single { it.name == completeScriptClass } - //.single { it.name == "Script\$SampleBlueprintsFunctionNode" } - - - val instance = instanceClass.newInstance() + val instance = scriptClass.java.newInstance() as? T ?: throw BluePrintProcessorException("failed to create instance from the script") - ResultWithDiagnostics.Success(EvaluationResult(ResultValue.Value(completeScriptClass, - instance, instance.javaClass.typeName), + log.info("Created script instance successfully....") + + ResultWithDiagnostics.Success(EvaluationResult(ResultValue.Value(scriptClass.qualifiedName!!, + instance, "", instance), scriptEvaluationConfiguration)) } } diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BlueprintScriptingHostTest.kt b/ms/controllerblueprints/modules/blueprint-scripts/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BlueprintScriptingHostTest.kt new file mode 100644 index 00000000..4b6f2a47 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/scripts/BlueprintScriptingHostTest.kt @@ -0,0 +1,88 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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 org.onap.ccsdk.apps.controllerblueprints.scripts + + +import org.apache.commons.io.FileUtils +import org.junit.Ignore +import org.junit.Test +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BlueprintFunctionNode +import java.io.File +import kotlin.script.experimental.jvm.util.classpathFromClass +import kotlin.script.experimental.jvm.util.classpathFromClassloader +import kotlin.script.experimental.jvm.util.classpathFromClasspathProperty +import kotlin.script.experimental.jvmhost.createJvmCompilationConfigurationFromTemplate + +class BlueprintScriptingHostTest { + + @Test + @Ignore + fun `test classpaths`() { + + println(" *********** classpathFromClass *********** ") + classpathFromClass(BlueprintScriptingHostTest::class.java.classLoader, + BlueprintScriptingHostTest::class)!! + .forEach(::println) + + println(" *********** classpathFromClassloader *********** ") + classpathFromClassloader(BlueprintScriptingHostTest::class.java.classLoader)!! + .forEach(::println) + + println(" *********** classpathFromClasspathProperty *********** ") + classpathFromClasspathProperty()!! + .forEach(::println) + } + + @Test + fun `test same script two folders`() { + + FileUtils.forceMkdir(File("target/scripts1/")) + FileUtils.forceMkdir(File("target/scripts2/")) + + val scriptSource1 = BluePrintSourceCode() + scriptSource1.moduleName = "blueprint-test-script" + + scriptSource1.targetJarFile = File("target/scripts1/blueprint-script-generated.jar") + val sources1: MutableList<String> = arrayListOf() + sources1.add("src/test/resources/scripts1") + scriptSource1.blueprintKotlinSources = sources1 + + val scriptClassName = "Simple_cba\$SampleComponentFunction" + + val compilationConfiguration = createJvmCompilationConfigurationFromTemplate<BluePrintKotlinScript>() + + val scriptEvaluator = BluePrintScriptEvaluator<BlueprintFunctionNode<String, String>>(scriptClassName) + + val scriptSource2 = BluePrintSourceCode() + scriptSource2.moduleName = "blueprint-test-script" + + scriptSource2.targetJarFile = File("target/scripts2/blueprint-script-generated.jar") + val sources2: MutableList<String> = arrayListOf() + sources2.add("src/test/resources/scripts2") + scriptSource2.blueprintKotlinSources = sources2 + + for (i in 1..2) { + val evalResponse = BlueprintScriptingHost(scriptEvaluator).eval(scriptSource1, compilationConfiguration, + null) + } + + for (i in 1..2) { + val evalResponse = BlueprintScriptingHost(scriptEvaluator).eval(scriptSource2, compilationConfiguration, + null) + } + } +}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/test/resources/scripts1/simple.cba.kts b/ms/controllerblueprints/modules/blueprint-scripts/src/test/resources/scripts1/simple.cba.kts new file mode 100644 index 00000000..9f61c649 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/test/resources/scripts1/simple.cba.kts @@ -0,0 +1,55 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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. + */ + +import org.onap.ccsdk.apps.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.apps.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BlueprintFunctionNode +import org.springframework.stereotype.Service + +@Service +open class SampleComponentFunction : BlueprintFunctionNode<String, String> { + + override fun getName(): String { + println("Printing Name....." + "sample".asJsonPrimitive()) + return "my Name" + } + + override fun prepareRequest(executionRequest: String): String { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun process(executionRequest: String) { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun recover(runtimeException: RuntimeException, executionRequest: String) { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun prepareResponse(): String { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun apply(t: String): String { + return "Script 1 response - $t" + } +} + +val blueprintFunction = SampleComponentFunction() + +val serviceTemplate = ServiceTemplate() + +println("Simple script printing....") diff --git a/ms/controllerblueprints/modules/blueprint-scripts/src/test/resources/scripts2/simple.cba.kts b/ms/controllerblueprints/modules/blueprint-scripts/src/test/resources/scripts2/simple.cba.kts new file mode 100644 index 00000000..84517254 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-scripts/src/test/resources/scripts2/simple.cba.kts @@ -0,0 +1,55 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * 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. + */ + +import org.onap.ccsdk.apps.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.apps.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BlueprintFunctionNode +import org.springframework.stereotype.Service + +@Service +open class SampleComponentFunction : BlueprintFunctionNode<String, String> { + + override fun getName(): String { + println("Printing Name....." + "sample".asJsonPrimitive()) + return "my Name" + } + + override fun prepareRequest(executionRequest: String): String { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun process(executionRequest: String) { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun recover(runtimeException: RuntimeException, executionRequest: String) { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun prepareResponse(): String { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun apply(t: String): String { + return "Script 2 response - $t" + } +} + +val blueprintFunction = SampleComponentFunction() + +val serviceTemplate = ServiceTemplate() + +println("Simple script printing....") diff --git a/ms/controllerblueprints/modules/pom.xml b/ms/controllerblueprints/modules/pom.xml index 3857ef5d..834db24e 100644 --- a/ms/controllerblueprints/modules/pom.xml +++ b/ms/controllerblueprints/modules/pom.xml @@ -30,6 +30,7 @@ <module>service</module> <module>blueprint-validation</module> <module>db-resources</module> + <module>blueprint-scripts</module> </modules> <build> diff --git a/ms/controllerblueprints/modules/service/pom.xml b/ms/controllerblueprints/modules/service/pom.xml index 9868b17b..73fe0739 100644 --- a/ms/controllerblueprints/modules/service/pom.xml +++ b/ms/controllerblueprints/modules/service/pom.xml @@ -32,10 +32,6 @@ <dependencies> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>core</artifactId> - </dependency> - <dependency> - <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> <artifactId>db-resources</artifactId> </dependency> <dependency> @@ -44,7 +40,7 @@ </dependency> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>resource-dict</artifactId> + <artifactId>blueprint-scripts</artifactId> </dependency> <dependency> <groupId>org.apache.velocity</groupId> diff --git a/ms/controllerblueprints/modules/service/src/main/java/org/onap/ccsdk/apps/controllerblueprints/service/BlueprintModelService.java b/ms/controllerblueprints/modules/service/src/main/java/org/onap/ccsdk/apps/controllerblueprints/service/BlueprintModelService.java deleted file mode 100644 index 3cf144f1..00000000 --- a/ms/controllerblueprints/modules/service/src/main/java/org/onap/ccsdk/apps/controllerblueprints/service/BlueprintModelService.java +++ /dev/null @@ -1,293 +0,0 @@ -/*
- * Copyright © 2017-2018 AT&T Intellectual Property.
- * Modifications Copyright © 2019 Bell Canada.
- *
- * 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 org.onap.ccsdk.apps.controllerblueprints.service;
-
-import java.io.IOException; -import java.nio.file.Path; -import java.util.List; -import java.util.Optional; -import org.jetbrains.annotations.NotNull;
-import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException;
-import org.onap.ccsdk.apps.controllerblueprints.core.common.ApplicationConstants;
-import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration;
-import org.onap.ccsdk.apps.controllerblueprints.core.data.ErrorCode;
-import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService;
-import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintFileUtils;
-import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModel;
-import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModelSearch;
-import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelContentRepository;
-import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelRepository;
-import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelSearchRepository;
-import org.onap.ccsdk.apps.controllerblueprints.service.utils.BluePrintEnhancerUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.io.ByteArrayResource;
-import org.springframework.core.io.Resource;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.http.codec.multipart.FilePart;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-import reactor.core.publisher.Mono;
-
-/**
- * BlueprintModelService.java Purpose: Provide Service Template Service processing BlueprintModelService
- *
- * @author Brinda Santh
- * @version 1.0
- */
-
-@Service
-public class BlueprintModelService {
-
- @Autowired
- private BluePrintLoadConfiguration bluePrintLoadConfiguration;
-
- @Autowired
- private BluePrintCatalogService bluePrintCatalogService;
-
- @Autowired
- private ControllerBlueprintModelSearchRepository blueprintModelSearchRepository;
-
- @Autowired
- private ControllerBlueprintModelRepository blueprintModelRepository;
-
- @Autowired
- private ControllerBlueprintModelContentRepository blueprintModelContentRepository;
-
- private static final String BLUEPRINT_MODEL_ID_FAILURE_MSG = "failed to get blueprint model id(%s) from repo";
- private static final String BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG = "failed to get blueprint model by name(%s)" +
- " and version(%s) from repo"; -
- /**
- * This is a saveBlueprintModel method
- *
- * @param filePart filePart
- * @return Mono<BlueprintModelSearch>
- * @throws BluePrintException BluePrintException
- */
- public Mono<BlueprintModelSearch> saveBlueprintModel(FilePart filePart) throws BluePrintException {
- try {
- Path cbaLocation = BluePrintFileUtils.Companion
- .getCbaStorageDirectory(bluePrintLoadConfiguration.blueprintArchivePath); - return BluePrintEnhancerUtils.Companion.saveCBAFile(filePart, cbaLocation).map(fileName -> {
- String blueprintId = null; - try { - blueprintId = bluePrintCatalogService - .saveToDatabase(cbaLocation.toFile(), false); - } catch (BluePrintException e) { - // FIXME handle expection - } - return blueprintModelSearchRepository.findById(blueprintId).get();
- });
- } catch (IOException e) {
- throw new BluePrintException(ErrorCode.IO_FILE_INTERRUPT.getValue(),
- String.format("I/O Error while uploading the CBA file: %s", e.getMessage()), e); - }
- }
-
- /**
- * This is a publishBlueprintModel method to change the status published to YES
- *
- * @param id id
- * @return BlueprintModelSearch
- * @throws BluePrintException BluePrintException
- */
- public BlueprintModelSearch publishBlueprintModel(String id) throws BluePrintException {
- BlueprintModelSearch blueprintModelSearch;
- Optional<BlueprintModelSearch> dbBlueprintModel = blueprintModelSearchRepository.findById(id);
- if (dbBlueprintModel.isPresent()) {
- blueprintModelSearch = dbBlueprintModel.get();
- } else {
- String msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id);
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), msg);
- }
- blueprintModelSearch.setPublished(ApplicationConstants.ACTIVE_Y);
- return blueprintModelSearchRepository.saveAndFlush(blueprintModelSearch);
- }
-
- /**
- * This is a searchBlueprintModels method
- *
- * @param tags tags
- * @return List<BlueprintModelSearch>
- */
- public List<BlueprintModelSearch> searchBlueprintModels(String tags) {
- return blueprintModelSearchRepository.findByTagsContainingIgnoreCase(tags);
- }
-
- /**
- * This is a getBlueprintModelSearchByNameAndVersion method
- *
- * @param name name
- * @param version version
- * @return BlueprintModelSearch
- * @throws BluePrintException BluePrintException
- */
- public BlueprintModelSearch getBlueprintModelSearchByNameAndVersion(@NotNull String name, @NotNull String version)
- throws BluePrintException { - BlueprintModelSearch blueprintModelSearch;
- Optional<BlueprintModelSearch> dbBlueprintModel = blueprintModelSearchRepository
- .findByArtifactNameAndArtifactVersion(name, version); - if (dbBlueprintModel.isPresent()) {
- blueprintModelSearch = dbBlueprintModel.get();
- } else {
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(),
- String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version)); - }
- return blueprintModelSearch;
- }
-
- /**
- * This is a downloadBlueprintModelFileByNameAndVersion method to download a Blueprint by Name and Version
- *
- * @param name name - * @param version version
- * @return ResponseEntity<Resource>
- * @throws BluePrintException BluePrintException
- */
- public ResponseEntity<Resource> downloadBlueprintModelFileByNameAndVersion(@NotNull String name, - @NotNull String version) - throws BluePrintException { - BlueprintModel blueprintModel;
- try {
- blueprintModel = getBlueprintModelByNameAndVersion(name, version);
- } catch (BluePrintException e) {
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), String.format("Error while " +
- "downloading the CBA file: %s", e.getMessage()), e); - }
- String fileName = blueprintModel.getId() + ".zip";
- byte[] file = blueprintModel.getBlueprintModelContent().getContent();
- return prepareResourceEntity(fileName, file);
- }
-
- /**
- * This is a downloadBlueprintModelFile method to find the target file to download and return a file resource
- *
- * @return ResponseEntity<Resource>
- * @throws BluePrintException BluePrintException
- */
- public ResponseEntity<Resource> downloadBlueprintModelFile(@NotNull String id) throws BluePrintException {
- BlueprintModel blueprintModel;
- try {
- blueprintModel = getBlueprintModel(id);
- } catch (BluePrintException e) {
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), String.format("Error while " +
- "downloading the CBA file: %s", e.getMessage()), e); - }
- String fileName = blueprintModel.getId() + ".zip";
- byte[] file = blueprintModel.getBlueprintModelContent().getContent();
- return prepareResourceEntity(fileName, file);
- }
-
- /**
- * @return ResponseEntity<Resource>
- */
- private ResponseEntity<Resource> prepareResourceEntity(String fileName, byte[] file) {
- return ResponseEntity.ok()
- .contentType(MediaType.parseMediaType("text/plain")) - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"") - .body(new ByteArrayResource(file)); - }
-
- /**
- * This is a getBlueprintModel method
- *
- * @param id id
- * @return BlueprintModel
- * @throws BluePrintException BluePrintException
- */
- private BlueprintModel getBlueprintModel(@NotNull String id) throws BluePrintException {
- BlueprintModel blueprintModel;
- Optional<BlueprintModel> dbBlueprintModel = blueprintModelRepository.findById(id);
- if (dbBlueprintModel.isPresent()) {
- blueprintModel = dbBlueprintModel.get();
- } else {
- String msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id);
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), msg);
- }
- return blueprintModel;
- }
-
- /**
- * This is a getBlueprintModelByNameAndVersion method
- *
- * @param name name - * @param version version
- * @return BlueprintModel
- * @throws BluePrintException BluePrintException
- */
- private BlueprintModel getBlueprintModelByNameAndVersion(@NotNull String name, @NotNull String version)
- throws BluePrintException { - BlueprintModel blueprintModel = blueprintModelRepository - .findByArtifactNameAndArtifactVersion(name, version); - if (blueprintModel != null) { - return blueprintModel; - } else {
- String msg = String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version);
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), msg);
- }
- }
-
- /**
- * This is a getBlueprintModelSearch method
- *
- * @param id id
- * @return BlueprintModelSearch
- * @throws BluePrintException BluePrintException
- */
- public BlueprintModelSearch getBlueprintModelSearch(@NotNull String id) throws BluePrintException {
- BlueprintModelSearch blueprintModelSearch;
- Optional<BlueprintModelSearch> dbBlueprintModel = blueprintModelSearchRepository.findById(id);
- if (dbBlueprintModel.isPresent()) {
- blueprintModelSearch = dbBlueprintModel.get();
- } else {
- String msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id);
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), msg);
- }
-
- return blueprintModelSearch;
- }
-
- /**
- * This is a deleteBlueprintModel method
- *
- * @param id id
- * @throws BluePrintException BluePrintException
- */
- @Transactional
- public void deleteBlueprintModel(@NotNull String id) throws BluePrintException {
- Optional<BlueprintModel> dbBlueprintModel = blueprintModelRepository.findById(id);
- if (dbBlueprintModel.isPresent()) {
- blueprintModelContentRepository.deleteByBlueprintModel(dbBlueprintModel.get());
- blueprintModelRepository.delete(dbBlueprintModel.get());
- } else {
- String msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id);
- throw new BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.getValue(), msg);
- }
- }
-
- /**
- * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database
- *
- * @return List<BlueprintModelSearch> list of the controller blueprint archives
- */
- public List<BlueprintModelSearch> getAllBlueprintModel() {
- return blueprintModelSearchRepository.findAll();
- }
-}
diff --git a/ms/controllerblueprints/modules/service/src/main/java/org/onap/ccsdk/apps/controllerblueprints/service/rs/BlueprintModelRest.java b/ms/controllerblueprints/modules/service/src/main/java/org/onap/ccsdk/apps/controllerblueprints/service/rs/BlueprintModelRest.java deleted file mode 100644 index 255137bf..00000000 --- a/ms/controllerblueprints/modules/service/src/main/java/org/onap/ccsdk/apps/controllerblueprints/service/rs/BlueprintModelRest.java +++ /dev/null @@ -1,97 +0,0 @@ -/*
- * Copyright © 2017-2018 AT&T Intellectual Property.
- * Modifications Copyright © 2019 Bell Canada.
- *
- * 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 org.onap.ccsdk.apps.controllerblueprints.service.rs;
-
-import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException;
-import org.onap.ccsdk.apps.controllerblueprints.service.BlueprintModelService;
-import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModelSearch;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.io.Resource;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.http.codec.multipart.FilePart;
-import org.springframework.web.bind.annotation.*;
-import reactor.core.publisher.Mono;
-
-import java.util.List;
-
-/**
- * {@inheritDoc}
- */
-@RestController
-@RequestMapping(value = "/api/v1/blueprint-model")
-public class BlueprintModelRest {
-
- @Autowired
- private BlueprintModelService blueprintModelService;
-
- @PostMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- public @ResponseBody
- Mono<BlueprintModelSearch> saveBlueprint(@RequestPart("file") FilePart file) throws BluePrintException{
- return blueprintModelService.saveBlueprintModel(file);
- }
-
- @DeleteMapping(path = "/{id}")
- public void deleteBlueprint(@PathVariable(value = "id") String id) throws BluePrintException {
- this.blueprintModelService.deleteBlueprintModel(id);
- }
-
- @GetMapping(path = "/by-name/{name}/version/{version}", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- BlueprintModelSearch getBlueprintByNameAndVersion(@PathVariable(value = "name") String name,
- @PathVariable(value = "version") String version) throws BluePrintException {
- return this.blueprintModelService.getBlueprintModelSearchByNameAndVersion(name, version);
- }
-
- @GetMapping(path = "/download/by-name/{name}/version/{version}", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- ResponseEntity<Resource> downloadBlueprintByNameAndVersion(@PathVariable(value = "name") String name,
- @PathVariable(value = "version") String version) throws BluePrintException {
- return this.blueprintModelService.downloadBlueprintModelFileByNameAndVersion(name, version);
- }
-
- @GetMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- BlueprintModelSearch getBlueprintModel(@PathVariable(value = "id") String id) throws BluePrintException {
- return this.blueprintModelService.getBlueprintModelSearch(id);
- }
-
- @GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- List<BlueprintModelSearch> getAllBlueprintModel() {
- return this.blueprintModelService.getAllBlueprintModel();
- }
-
- @GetMapping(path = "/download/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- ResponseEntity<Resource> downloadBluePrint(@PathVariable(value = "id") String id) throws BluePrintException {
- return this.blueprintModelService.downloadBlueprintModelFile(id);
- }
-
- @PutMapping(path = "/publish/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- BlueprintModelSearch publishBlueprintModel(@PathVariable(value = "id") String id) throws BluePrintException {
- return this.blueprintModelService.publishBlueprintModel(id);
- }
-
- @GetMapping(path = "/search/{tags}", produces = MediaType.APPLICATION_JSON_VALUE)
- public @ResponseBody
- List<BlueprintModelSearch> searchBlueprintModels(@PathVariable(value = "tags") String tags) {
- return this.blueprintModelService.searchBlueprintModels(tags);
- }
-}
diff --git a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/BlueprintModelRest.kt b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/BlueprintModelRest.kt new file mode 100644 index 00000000..0fca07b0 --- /dev/null +++ b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/BlueprintModelRest.kt @@ -0,0 +1,100 @@ +/* + * Copyright © 2019 Bell Canada Intellectual Property. + * + * 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 org.onap.ccsdk.apps.controllerblueprints.service.controller + +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModelSearch +import org.onap.ccsdk.apps.controllerblueprints.service.handler.BluePrintModelHandler +import org.springframework.core.io.Resource +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.http.codec.multipart.FilePart +import org.springframework.web.bind.annotation.* +import reactor.core.publisher.Mono + +/** + * BlueprintModelRest Purpose: Handle controllerBlueprint API request + * + * @author Vinal Patel + * @version 1.0 + */ +@RestController +@RequestMapping("/api/v1/blueprint-model") +open class BlueprintModelRest(private val bluePrintModelHandler: BluePrintModelHandler) { + + @PostMapping("", produces = [MediaType.APPLICATION_JSON_VALUE], consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) + @ResponseBody + @Throws(BluePrintException::class) + fun saveBlueprint(@RequestPart("file") file: FilePart): Mono<BlueprintModelSearch> { + return bluePrintModelHandler.saveBlueprintModel(file) + } + + @GetMapping("", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + fun allBlueprintModel(): List<BlueprintModelSearch> { + return this.bluePrintModelHandler.allBlueprintModel() + } + + @DeleteMapping("/{id}") + @Throws(BluePrintException::class) + fun deleteBlueprint(@PathVariable(value = "id") id: String) { + this.bluePrintModelHandler.deleteBlueprintModel(id) + } + + @GetMapping("/by-name/{name}/version/{version}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + @Throws(BluePrintException::class) + fun getBlueprintByNameAndVersion(@PathVariable(value = "name") name: String, + @PathVariable(value = "version") version: String): BlueprintModelSearch { + return this.bluePrintModelHandler.getBlueprintModelSearchByNameAndVersion(name, version) + } + + @GetMapping("/download/by-name/{name}/version/{version}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + @Throws(BluePrintException::class) + fun downloadBlueprintByNameAndVersion(@PathVariable(value = "name") name: String, + @PathVariable(value = "version") version: String): ResponseEntity<Resource> { + return this.bluePrintModelHandler.downloadBlueprintModelFileByNameAndVersion(name, version) + } + + @GetMapping("/{id}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + @Throws(BluePrintException::class) + fun getBlueprintModel(@PathVariable(value = "id") id: String): BlueprintModelSearch { + return this.bluePrintModelHandler.getBlueprintModelSearch(id) + } + + @GetMapping("/download/{id}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + @Throws(BluePrintException::class) + fun downloadBluePrint(@PathVariable(value = "id") id: String): ResponseEntity<Resource> { + return this.bluePrintModelHandler.downloadBlueprintModelFile(id) + } + + @PutMapping("/publish/{id}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + @Throws(BluePrintException::class) + fun publishBlueprintModel(@PathVariable(value = "id") id: String): BlueprintModelSearch { + return this.bluePrintModelHandler.publishBlueprintModel(id) + } + + @GetMapping("/search/{tags}", produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + fun searchBlueprintModels(@PathVariable(value = "tags") tags: String): List<BlueprintModelSearch> { + return this.bluePrintModelHandler.searchBlueprintModels(tags) + } +} diff --git a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/ControllerBlueprintExeptionHandler.kt b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/ControllerBlueprintExeptionHandler.kt index a0e47d72..04753391 100644 --- a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/ControllerBlueprintExeptionHandler.kt +++ b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/ControllerBlueprintExeptionHandler.kt @@ -25,7 +25,7 @@ import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.ExceptionHandler /** - * ControllerBlueprintExceptionHandler.java Purpose: Handle exceptions in controllerBlueprint API and provide the wright + * ControllerBlueprintExceptionHandler Purpose: Handle exceptions in controllerBlueprint API and provide the right * HTTP code status * * @author Vinal Patel diff --git a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/handler/BluePrintModelHandler.kt b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/handler/BluePrintModelHandler.kt new file mode 100644 index 00000000..907566c3 --- /dev/null +++ b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/handler/BluePrintModelHandler.kt @@ -0,0 +1,283 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * + * 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 org.onap.ccsdk.apps.controllerblueprints.service.handler + +import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.apps.controllerblueprints.core.common.ApplicationConstants +import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.apps.controllerblueprints.core.data.ErrorCode +import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintFileUtils +import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModel +import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModelSearch +import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelContentRepository +import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelRepository +import org.onap.ccsdk.apps.controllerblueprints.service.repository.ControllerBlueprintModelSearchRepository +import org.onap.ccsdk.apps.controllerblueprints.service.utils.BluePrintEnhancerUtils +import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource +import org.springframework.http.HttpHeaders +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.http.codec.multipart.FilePart +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import reactor.core.publisher.Mono +import java.io.IOException + +/** + * BlueprintModelHandler Purpose: Handler service to handle the request from BlurPrintModelRest + * + * @author Brinda Santh + * @version 1.0 + */ + +@Service +open class BluePrintModelHandler(private val bluePrintCatalogService: BluePrintCatalogService, private val bluePrintLoadConfiguration: BluePrintLoadConfiguration, + private val blueprintModelSearchRepository: ControllerBlueprintModelSearchRepository, + private val blueprintModelRepository: ControllerBlueprintModelRepository, + private val blueprintModelContentRepository: ControllerBlueprintModelContentRepository) { + + /** + * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database + * + * @return List<BlueprintModelSearch> list of the controller blueprint archives + </BlueprintModelSearch> */ + open fun allBlueprintModel(): List<BlueprintModelSearch> { + return blueprintModelSearchRepository.findAll() + } + + /** + * This is a saveBlueprintModel method + * + * @param filePart filePart + * @return Mono<BlueprintModelSearch> + * @throws BluePrintException BluePrintException + </BlueprintModelSearch> */ + @Throws(BluePrintException::class) + open fun saveBlueprintModel(filePart: FilePart): Mono<BlueprintModelSearch> { + try { + val cbaLocation = BluePrintFileUtils.getCbaStorageDirectory(bluePrintLoadConfiguration.blueprintArchivePath) + return BluePrintEnhancerUtils.saveCBAFile(filePart, cbaLocation).map { fileName -> + var blueprintId: String? = null + try { + blueprintId = bluePrintCatalogService.saveToDatabase(cbaLocation.resolve(fileName).toFile(), false) + } catch (e: BluePrintException) { + // FIXME handle expection + } + blueprintModelSearchRepository.findById(blueprintId!!).get() + } + } catch (e: IOException) { + throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value, + String.format("I/O Error while uploading the CBA file: %s", e.message), e) + } + + } + + /** + * This is a publishBlueprintModel method to change the status published to YES + * + * @param id id + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun publishBlueprintModel(id: String): BlueprintModelSearch { + val blueprintModelSearch: BlueprintModelSearch + val dbBlueprintModel = blueprintModelSearchRepository.findById(id) + if (dbBlueprintModel.isPresent) { + blueprintModelSearch = dbBlueprintModel.get() + } else { + val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg) + } + blueprintModelSearch.published = ApplicationConstants.ACTIVE_Y + return blueprintModelSearchRepository.saveAndFlush(blueprintModelSearch) + } + + /** + * This is a searchBlueprintModels method + * + * @param tags tags + * @return List<BlueprintModelSearch> + </BlueprintModelSearch> */ + open fun searchBlueprintModels(tags: String): List<BlueprintModelSearch> { + return blueprintModelSearchRepository.findByTagsContainingIgnoreCase(tags) + } + + /** + * This is a getBlueprintModelSearchByNameAndVersion method + * + * @param name name + * @param version version + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModelSearchByNameAndVersion(name: String, version: String): BlueprintModelSearch { + val blueprintModelSearch: BlueprintModelSearch + val dbBlueprintModel = blueprintModelSearchRepository + .findByArtifactNameAndArtifactVersion(name, version) + if (dbBlueprintModel.isPresent) { + blueprintModelSearch = dbBlueprintModel.get() + } else { + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, + String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version)) + } + return blueprintModelSearch + } + + /** + * This is a downloadBlueprintModelFileByNameAndVersion method to download a Blueprint by Name and Version + * + * @param name name + * @param version version + * @return ResponseEntity<Resource> + * @throws BluePrintException BluePrintException + </Resource> */ + @Throws(BluePrintException::class) + open fun downloadBlueprintModelFileByNameAndVersion(name: String, + version: String): ResponseEntity<Resource> { + val blueprintModel: BlueprintModel + try { + blueprintModel = getBlueprintModelByNameAndVersion(name, version) + } catch (e: BluePrintException) { + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, String.format("Error while " + "downloading the CBA file: %s", e.message), e) + } + + val fileName = blueprintModel.id + ".zip" + val file = blueprintModel.blueprintModelContent.content + return prepareResourceEntity(fileName, file) + } + + /** + * This is a downloadBlueprintModelFile method to find the target file to download and return a file resource + * + * @return ResponseEntity<Resource> + * @throws BluePrintException BluePrintException + </Resource> */ + @Throws(BluePrintException::class) + open fun downloadBlueprintModelFile(id: String): ResponseEntity<Resource> { + val blueprintModel: BlueprintModel + try { + blueprintModel = getBlueprintModel(id) + } catch (e: BluePrintException) { + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, String.format("Error while " + "downloading the CBA file: %s", e.message), e) + } + + val fileName = blueprintModel.id + ".zip" + val file = blueprintModel.blueprintModelContent.content + return prepareResourceEntity(fileName, file) + } + + /** + * @return ResponseEntity<Resource> + </Resource> */ + private fun prepareResourceEntity(fileName: String, file: ByteArray): ResponseEntity<Resource> { + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType("text/plain")) + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"") + .body(ByteArrayResource(file)) + } + + /** + * This is a getBlueprintModel method + * + * @param id id + * @return BlueprintModel + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModel(id: String): BlueprintModel { + val blueprintModel: BlueprintModel + val dbBlueprintModel = blueprintModelRepository.findById(id) + if (dbBlueprintModel.isPresent) { + blueprintModel = dbBlueprintModel.get() + } else { + val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg) + } + return blueprintModel + } + + /** + * This is a getBlueprintModelByNameAndVersion method + * + * @param name name + * @param version version + * @return BlueprintModel + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModelByNameAndVersion(name: String, version: String): BlueprintModel { + val blueprintModel = blueprintModelRepository + .findByArtifactNameAndArtifactVersion(name, version) + if (blueprintModel != null) { + return blueprintModel + } else { + val msg = String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version) + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg) + } + } + + /** + * This is a getBlueprintModelSearch method + * + * @param id id + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModelSearch(id: String): BlueprintModelSearch { + val blueprintModelSearch: BlueprintModelSearch + val dbBlueprintModel = blueprintModelSearchRepository.findById(id) + if (dbBlueprintModel.isPresent) { + blueprintModelSearch = dbBlueprintModel.get() + } else { + val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg) + } + + return blueprintModelSearch + } + + /** + * This is a deleteBlueprintModel method + * + * @param id id + * @throws BluePrintException BluePrintException + */ + @Transactional + @Throws(BluePrintException::class) + open fun deleteBlueprintModel(id: String) { + val dbBlueprintModel = blueprintModelRepository.findById(id) + if (dbBlueprintModel.isPresent) { + blueprintModelContentRepository.deleteByBlueprintModel(dbBlueprintModel.get()) + blueprintModelRepository.delete(dbBlueprintModel.get()) + } else { + val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg) + } + } + + companion object { + + private const val BLUEPRINT_MODEL_ID_FAILURE_MSG = "failed to get blueprint model id(%s) from repo" + private const val BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG = "failed to get blueprint model by name(%s)" + " and version(%s) from repo" + } +} diff --git a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/load/ControllerBlueprintCatalogServiceImpl.kt b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/load/ControllerBlueprintCatalogServiceImpl.kt index 04071dd2..779be65d 100755 --- a/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/load/ControllerBlueprintCatalogServiceImpl.kt +++ b/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/load/ControllerBlueprintCatalogServiceImpl.kt @@ -97,6 +97,8 @@ class ControllerBlueprintCatalogServiceImpl(bluePrintValidatorService: BluePrint blueprintModelContent.description = "$artifactName:$artifactVersion CBA Zip Content" blueprintModelContent.content = Files.readAllBytes(archiveFile.toPath()) blueprintModelContent.blueprintModel = blueprintModel + // Set the Blueprint Model Content into blueprintModel + blueprintModel.blueprintModelContent = blueprintModelContent try { blueprintModelRepository.saveAndFlush(blueprintModel) diff --git a/ms/controllerblueprints/modules/service/src/test/java/org/onap/ccsdk/apps/controllerblueprints/service/BlueprintModelServiceTest.java b/ms/controllerblueprints/modules/service/src/test/java/org/onap/ccsdk/apps/controllerblueprints/service/BlueprintModelServiceTest.java deleted file mode 100644 index 0ce93b18..00000000 --- a/ms/controllerblueprints/modules/service/src/test/java/org/onap/ccsdk/apps/controllerblueprints/service/BlueprintModelServiceTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright © 2018 IBM. - * - * 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 org.onap.ccsdk.apps.controllerblueprints.service; - -import org.junit.Test; -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException; -import org.springframework.beans.factory.annotation.Autowired; - -public class BlueprintModelServiceTest { - @Autowired - private BlueprintModelService blueprintModelService; - - @Test - public void testGetInitialConfigModel() throws BluePrintException { - } -} diff --git a/ms/controllerblueprints/modules/service/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/BlueprintModelRestTest.kt b/ms/controllerblueprints/modules/service/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/BlueprintModelRestTest.kt new file mode 100644 index 00000000..f82aace4 --- /dev/null +++ b/ms/controllerblueprints/modules/service/src/test/kotlin/org/onap/ccsdk/apps/controllerblueprints/service/controller/BlueprintModelRestTest.kt @@ -0,0 +1,192 @@ +/* + * Copyright © 2019 Bell Canada Intellectual Property. + * + * 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 org.onap.ccsdk.apps.controllerblueprints.service.controller + +import com.google.gson.Gson +import org.json.JSONException +import org.json.JSONObject +import org.junit.After +import org.junit.Before +import org.junit.FixMethodOrder +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.MethodSorters +import org.onap.ccsdk.apps.controllerblueprints.TestApplication +import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintArchiveUtils +import org.onap.ccsdk.apps.controllerblueprints.service.domain.BlueprintModelSearch +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.beans.factory.annotation.Value +import org.springframework.boot.autoconfigure.EnableAutoConfiguration +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.context.annotation.ComponentScan +import org.springframework.core.io.ByteArrayResource +import org.springframework.http.HttpMethod +import org.springframework.http.HttpStatus +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.junit4.SpringRunner +import org.springframework.test.web.reactive.server.WebTestClient +import org.springframework.util.Base64Utils +import org.springframework.web.reactive.function.BodyInserters +import java.io.File +import java.io.IOException +import java.nio.charset.StandardCharsets.UTF_8 +import java.nio.file.Files +import java.nio.file.Paths + +/** + * BlueprintModelRestTest Purpose: Integration test at API level + * + * @author Vinal Patel + * @version 1.0 + */ + +@RunWith(SpringRunner::class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ContextConfiguration(classes = [TestApplication::class]) +@ComponentScan(basePackages = ["org.onap.ccsdk.apps.controllerblueprints"]) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@EnableAutoConfiguration +class BlueprintModelRestTest { + + companion object { + + private var id: String? = null + private var name: String? = null + private var version: String? = null + private var tag: String? = null + private var result: String? = null + } + + @Value("\${controllerblueprints.loadBluePrintPaths}") + private val loadBluePrintPaths: String? = null + + @Autowired + private val webTestClient: WebTestClient? = null + + @Value("\${controllerblueprints.loadBlueprintsExamplesPath}") + private val blueprintArchivePath: String? = null + + private val filename = "test.zip" + private var blueprintFile: File? = null + private var zipBlueprintFile: File? = null + + @Before + @Throws(Exception::class) + fun setUp() { + blueprintFile = File(loadBluePrintPaths+"/baseconfiguration") + if (blueprintFile!!.isDirectory) { + zipBlueprintFile = File(Paths.get(blueprintArchivePath).resolve(filename).toString()) + BluePrintArchiveUtils.compress(blueprintFile!!, zipBlueprintFile!!, true) + } + } + + @After + @Throws(Exception::class) + fun tearDown() { + zipBlueprintFile!!.delete() + } + + @Test + @Throws(IOException::class, JSONException::class) + fun test1_saveBluePrint() { + webTestClient(HttpMethod.POST, + BodyInserters.fromMultipartData("file", object : ByteArrayResource(Files.readAllBytes(zipBlueprintFile!!.toPath())) { + override fun getFilename(): String? { + return "test.zip" + } + }), + "/api/v1/blueprint-model", + HttpStatus.OK, true) + } + + @Test + @Throws(JSONException::class) + fun test2_getBluePrintByNameAndVersion() { + webTestClient(HttpMethod.GET, null, "/api/v1/blueprint-model/by-name/$name/version/$version", HttpStatus.OK, false) + } + + + @Test + @Throws(JSONException::class) + fun test3_getBlueprintModel() { + webTestClient(HttpMethod.GET, null, "/api/v1/blueprint-model/$id", HttpStatus.OK, false) + } + + @Test + @Throws(JSONException::class) + fun test4_getAllBlueprintModel() { + webTestClient(HttpMethod.GET, null, "/api/v1/blueprint-model", HttpStatus.OK, false) + } + + @Test + @Throws(JSONException::class) + fun test5_downloadBluePrint() { + webTestClient(HttpMethod.GET, null, "/api/v1/blueprint-model/download/$id", HttpStatus.OK, false) + } + + @Test + fun test6_publishBlueprintModel() { + } + + @Test + @Throws(JSONException::class) + fun test7_searchBlueprintModels() { + webTestClient(HttpMethod.GET, null, "/api/v1/blueprint-model/search/$name", HttpStatus.OK, false) + } + + @Test + @Throws(JSONException::class) + fun test8_downloadBlueprintByNameAndVersion() { + webTestClient(HttpMethod.GET, null, "/api/v1/blueprint-model/download/by-name/$name/version/$version", HttpStatus.OK, false) + } + + @Test + fun test9_deleteBluePrint() { + //TODO: Use webTestClient function + //webTestClient(HttpMethod.DELETE, null, "/api/v1/blueprint-model/" + id, HttpStatus.OK, false); + webTestClient!!.delete().uri("/api/v1/blueprint-model/$id") + .header("Authorization", "Basic " + Base64Utils + .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8))) + .exchange() + .expectStatus().is2xxSuccessful + } + + @Throws(JSONException::class) + private fun webTestClient(requestMethod: HttpMethod, body: BodyInserters.MultipartInserter?, uri: String, expectedResponceStatus: HttpStatus, setParam: Boolean) { + + result = String(webTestClient!!.method(requestMethod).uri(uri) + .header("Authorization", "Basic " + Base64Utils + .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8))) + .body(body) + .exchange() + .expectStatus().isEqualTo(expectedResponceStatus) + .expectBody() + .returnResult().responseBody!!) + + if (setParam) { + val jsonResponse = JSONObject(result) + val blueprintModelSearchJSON = jsonResponse.getJSONObject("blueprintModel") + val gson = Gson() + val blueprintModelSearch = gson.fromJson(blueprintModelSearchJSON.toString(), BlueprintModelSearch::class.java) + id = blueprintModelSearch.id + name = blueprintModelSearch.artifactName + version = blueprintModelSearch.artifactVersion + tag = blueprintModelSearch.tags + } + } + +}
\ No newline at end of file diff --git a/ms/controllerblueprints/parent/pom.xml b/ms/controllerblueprints/parent/pom.xml index 578a0c7e..8cbc98e0 100644 --- a/ms/controllerblueprints/parent/pom.xml +++ b/ms/controllerblueprints/parent/pom.xml @@ -28,11 +28,11 @@ <name>Controller Blueprints Parent</name> <packaging>pom</packaging> <properties> - <spring.boot.version>2.1.1.RELEASE</spring.boot.version> - <spring.version>5.1.3.RELEASE</spring.version> - <kotlin.version>1.3.11</kotlin.version> - <kotlin.maven.version>1.3.11</kotlin.maven.version> - <kotlin.couroutines.version>1.1.0</kotlin.couroutines.version> + <spring.boot.version>2.1.2.RELEASE</spring.boot.version> + <spring.version>5.1.4.RELEASE</spring.version> + <kotlin.version>1.3.20</kotlin.version> + <kotlin.maven.version>1.3.20</kotlin.maven.version> + <kotlin.couroutines.version>1.1.1</kotlin.couroutines.version> <grpc.version>1.18.0</grpc.version> <protobuff.java.utils.version>3.6.1</protobuff.java.utils.version> <eelf.version>1.0.0</eelf.version> @@ -113,16 +113,23 @@ <artifactId>kotlin-stdlib-common</artifactId> <version>${kotlin.version}</version> </dependency> + <!--Use kotlin-compiler-embeddable instead koltin-compiler wrap--> + <!--guava dependency inside kotlin-compiler creating classpath issues at runtime--> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-scripting-jvm-host</artifactId> <version>${kotlin.version}</version> + <exclusions> + <exclusion> + <groupId>org.jetbrains.kotlin</groupId> + <artifactId>kotlin-compile</artifactId> + </exclusion> + </exclusions> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-compiler-embeddable</artifactId> <version>${kotlin.version}</version> - <scope>runtime</scope> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> @@ -203,27 +210,32 @@ </dependency> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>service</artifactId> + <artifactId>resource-dict</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>application</artifactId> + <artifactId>db-resources</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>resource-dict</artifactId> + <artifactId>blueprint-validation</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>db-resources</artifactId> + <artifactId>blueprint-scripts</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> - <artifactId>blueprint-validation</artifactId> + <artifactId>service</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.ccsdk.apps.controllerblueprints</groupId> + <artifactId>application</artifactId> <version>${project.version}</version> </dependency> @@ -275,6 +287,10 @@ <artifactId>json-path</artifactId> </dependency> <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + </dependency> + <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> </dependency> diff --git a/ms/neng/src/test/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/AaiServiceImplTest.java b/ms/neng/src/test/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/AaiServiceImplTest.java index 8507bf65..f7d0bc28 100644 --- a/ms/neng/src/test/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/AaiServiceImplTest.java +++ b/ms/neng/src/test/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/AaiServiceImplTest.java @@ -48,14 +48,18 @@ public class AaiServiceImplTest { AaiResponse aaiResponse = aaiServiceImpl.buildResponse(true); Assert.assertEquals(aaiResponse.isRecFound(), true); } - + @Test(expected= Exception.class) public void testValidate() throws Exception { AaiProps aaiProps=new AaiProps(); aaiProps.setUriBase("http://"); aaiServiceImpl.setAaiProps(aaiProps); aaiServiceImpl.setRestTemplate(new RestTemplate()); - aaiServiceImpl.validate("testUrl/","testName"); - + Assert.assertTrue(aaiServiceImpl.validate("testUrl/","testName")); + } + @Test(expected= Exception.class) + public void testGetRestTemplate_Null() throws Exception { + aaiServiceImpl.setRestTemplate(null); + Assert.assertNotNull(aaiServiceImpl.getRestTemplate()); } } diff --git a/ms/neng/src/test/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/PolicyFinderServiceDbImplTest.java b/ms/neng/src/test/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/PolicyFinderServiceDbImplTest.java new file mode 100644 index 00000000..5c993310 --- /dev/null +++ b/ms/neng/src/test/java/org/onap/ccsdk/apps/ms/neng/service/extinf/impl/PolicyFinderServiceDbImplTest.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2019 IBM. + * ================================================================================ + * 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. + * + * ============LICENSE_END========================================================= + */ +package org.onap.ccsdk.apps.ms.neng.service.extinf.impl; + +import org.junit.Test; +import org.junit.runner.RunWith; +import static org.mockito.Mockito.*; +import org.mockito.*; +import org.mockito.runners.MockitoJUnitRunner; +import static org.junit.Assert.assertNotNull; + +import org.onap.ccsdk.apps.ms.neng.core.resource.model.GetConfigResponse; + +@RunWith(MockitoJUnitRunner.class) +public class PolicyFinderServiceDbImplTest { + @InjectMocks + @Spy + PolicyFinderServiceDbImpl policyFinderServiceDb; + + @Test(expected = NullPointerException.class) + public void testConfig() throws Exception { + doReturn(new GetConfigResponse()).when(policyFinderServiceDb).makeOutboundCall(Matchers.any(), Matchers.any()); + assertNotNull(policyFinderServiceDb.getConfig("policy")); + } +} diff --git a/ms/vlantag-api/src/test/java/org/onap/ccsdk/apps/ms/vlangtagapi/core/model/AssignVlanTagRequestInputTest.java b/ms/vlantag-api/src/test/java/org/onap/ccsdk/apps/ms/vlangtagapi/core/model/AssignVlanTagRequestInputTest.java index 057e6721..6ae9fa01 100644 --- a/ms/vlantag-api/src/test/java/org/onap/ccsdk/apps/ms/vlangtagapi/core/model/AssignVlanTagRequestInputTest.java +++ b/ms/vlantag-api/src/test/java/org/onap/ccsdk/apps/ms/vlangtagapi/core/model/AssignVlanTagRequestInputTest.java @@ -18,6 +18,7 @@ package org.onap.ccsdk.apps.ms.vlangtagapi.core.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; import org.junit.Before; import org.junit.Test; @@ -94,7 +95,8 @@ public class AssignVlanTagRequestInputTest { @Test public void testEquals() { - assertEquals(true, assignVlanTagRequestInput.equals(assignVlanTagRequestInput1)); + assertEquals(true, assignVlanTagRequestInput.equals(assignVlanTagRequestInput1)); + assertFalse(assignVlanTagRequestInput.equals(null)); } @Test @@ -103,4 +105,6 @@ public class AssignVlanTagRequestInputTest { assertTrue(assignVlanTagRequestInput.toString() instanceof String); assertTrue((Integer)assignVlanTagRequestInput.hashCode() instanceof Integer); } + + } diff --git a/ms/vlantag-api/src/test/java/org/onap/ccsdk/apps/ms/vlangtagapi/core/model/AssignVlanTagResponseTest.java b/ms/vlantag-api/src/test/java/org/onap/ccsdk/apps/ms/vlangtagapi/core/model/AssignVlanTagResponseTest.java index 30f817ee..2ff1caa1 100644 --- a/ms/vlantag-api/src/test/java/org/onap/ccsdk/apps/ms/vlangtagapi/core/model/AssignVlanTagResponseTest.java +++ b/ms/vlantag-api/src/test/java/org/onap/ccsdk/apps/ms/vlangtagapi/core/model/AssignVlanTagResponseTest.java @@ -18,6 +18,7 @@ package org.onap.ccsdk.apps.ms.vlangtagapi.core.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; import java.util.ArrayList; import java.util.List; @@ -59,6 +60,7 @@ public class AssignVlanTagResponseTest { public void testEqualsAndHashcode() { assertTrue(assignVlanTagResponse.equals(assignVlanTagResponse1)); + assertFalse(assignVlanTagResponse.equals(null)); assertTrue((Integer)assignVlanTagResponse.hashCode() instanceof Integer); } |