diff options
author | 2018-08-09 20:47:29 +0000 | |
---|---|---|
committer | 2018-08-10 18:48:54 +0000 | |
commit | b35d55e3f57630551f0b773674bd1f5c44585ede (patch) | |
tree | 4429e94ad9ee813ebda5477ad7475a20017e3d62 /ms/controllerblueprints/modules/core/src/main |
Controller Blueprints MS
Creating the base directory structure for Controller Blueprints MicroService
Change-Id: I1ccf7fc76446048af3b2822f9155bb634657aee3
Issue-ID: CCSDK-410
Signed-off-by: Singal, Kapil (ks220y) <ks220y@att.com>
Diffstat (limited to 'ms/controllerblueprints/modules/core/src/main')
26 files changed, 3508 insertions, 0 deletions
diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/BluePrintConstants.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/BluePrintConstants.kt new file mode 100644 index 000000000..1bdd53073 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/BluePrintConstants.kt @@ -0,0 +1,125 @@ +/*
+ * 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
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+object BluePrintConstants {
+
+ const val TYPE_DEFAULT: String = "default"
+
+ const val DATA_TYPE_STRING: String = "string"
+ const val DATA_TYPE_INTEGER: String = "integer"
+ const val DATA_TYPE_FLOAT: String = "float"
+ const val DATA_TYPE_BOOLEAN: String = "boolean"
+ const val DATA_TYPE_TIMESTAMP: String = "timestamp"
+ const val DATA_TYPE_NULL: String = "null"
+ const val DATA_TYPE_LIST: String = "list"
+ const val DATA_TYPE_MAP: String = "map"
+
+ const val USER_SYSTEM: String = "System"
+
+ const val MODEL_CONTENT_TYPE_JSON: String = "JSON"
+ const val MODEL_CONTENT_TYPE_YAML: String = "YAML"
+ const val MODEL_CONTENT_TYPE_YANG: String = "YANG"
+ const val MODEL_CONTENT_TYPE_SCHEMA: String = "SCHEMA"
+
+ const val PATH_DIVIDER: String = "/"
+ const val PATH_INPUTS: String = "inputs"
+ const val PATH_NODE_WORKFLOWS: String = "workflows"
+ const val PATH_NODE_TEMPLATES: String = "node_templates"
+ const val PATH_CAPABILITIES: String = "capabilities"
+ const val PATH_REQUIREMENTS: String = "requirements"
+ const val PATH_INTERFACES: String = "interfaces"
+ const val PATH_OPERATIONS: String = "operations"
+ const val PATH_OUTPUTS: String = "outputs"
+ const val PATH_PROPERTIES: String = "properties"
+ const val PATH_ATTRIBUTES: String = "attributes"
+ const val PATH_ARTIFACTS: String = "artifacts"
+
+ const val MODEL_DEFINITION_TYPE_NODE_TYPE: String = "node_type"
+ const val MODEL_DEFINITION_TYPE_ARTIFACT_TYPE: String = "artifact_type"
+ const val MODEL_DEFINITION_TYPE_CAPABILITY_TYPE: String = "capability_type"
+ const val MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE: String = "relationship_type"
+ const val MODEL_DEFINITION_TYPE_DATA_TYPE: String = "data_type"
+
+ const val MODEL_TYPE_DATATYPES_ROOT: String = "tosca.datatypes.Root"
+ const val MODEL_TYPE_NODES_ROOT: String = "tosca.nodes.Root"
+ const val MODEL_TYPE_GROUPS_ROOT: String = "tosca.groups.Root"
+ const val MODEL_TYPE_RELATIONSHIPS_ROOT: String = "tosca.relationships.Root"
+ const val MODEL_TYPE_ARTIFACTS_ROOT: String = "tosca.artifacts.Root"
+ const val MODEL_TYPE_CAPABILITIES_ROOT: String = "tosca.capabilities.Root"
+ const val MODEL_TYPE_INTERFACES_ROOT: String = "tosca.interfaces.Root"
+
+ const val MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON = "tosca.relationships.DependsOn"
+ const val MODEL_TYPE_RELATIONSHIPS_HOSTED_ON = "tosca.relationships.HostedOn"
+ const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO = "tosca.relationships.ConnectsTo"
+ const val MODEL_TYPE_RELATIONSHIPS_ATTACH_TO = "tosca.relationships.AttachesTo"
+ const val MODEL_TYPE_RELATIONSHIPS_ROUTES_TO = "tosca.relationships.RoutesTo"
+
+ const val MODEL_TYPE_NODES_COMPONENT_JAVA: String = "tosca.nodes.component.Java"
+ const val MODEL_TYPE_NODES_COMPONENT_BUNDLE: String = "tosca.nodes.component.Bundle"
+ const val MODEL_TYPE_NODES_COMPONENT_SCRIPT: String = "tosca.nodes.component.Script"
+ const val MODEL_TYPE_NODES_COMPONENT_PYTHON: String = "tosca.nodes.component.Python"
+ const val MODEL_TYPE_NODES_COMPONENT_JAVA_SCRIPT: String = "tosca.nodes.component.JavaScript"
+
+ const val EXPRESSION_GET_INPUT: String = "get_input"
+ const val EXPRESSION_GET_ATTRIBUTE: String = "get_attribute"
+ const val EXPRESSION_GET_ARTIFACT: String = "get_artifact"
+ const val EXPRESSION_GET_PROPERTY: String = "get_property"
+ const val EXPRESSION_GET_OPERATION_OUTPUT: String = "get_operation_output"
+ const val EXPRESSION_GET_NODE_OF_TYPE: String = "get_nodes_of_type"
+
+ const val PROPERTY_BLUEPRINT_PROCESS_ID: String = "blueprint-process-id"
+ const val PROPERTY_BLUEPRINT_BASE_PATH: String = "blueprint-basePath"
+ const val PROPERTY_BLUEPRINT_RUNTIME: String = "blueprint-runtime"
+ const val PROPERTY_BLUEPRINT_INPUTS_DATA: String = "blueprint-inputs-data"
+ const val PROPERTY_BLUEPRINT_CONTEXT: String = "blueprint-context"
+ const val PROPERTY_BLUEPRINT_NAME: String = "template_name"
+ const val PROPERTY_BLUEPRINT_VERSION: String = "template_version"
+
+ const val TOSCA_METADATA_ENTRY_DEFINITION_FILE: String = "TOSCA-Metadata/TOSCA.meta"
+ const val TOSCA_PLANS_DIR: String = "Plans"
+ const val TOSCA_SCRIPTS_DIR: String = "Scripts"
+ const val TOSCA_MAPPINGS_DIR: String = "Mappings"
+ const val TOSCA_TEMPLATES_DIR: String = "Templates"
+
+ const val METADATA_USER_GROUPS = "user-groups"
+ const val METADATA_TEMPLATE_NAME = "template_name"
+ const val METADATA_TEMPLATE_VERSION = "template_version"
+ const val METADATA_TEMPLATE_AUTHOR = "template_author"
+ const val METADATA_TEMPLATE_TAGS = "template_tags"
+
+ const val PAYLOAD_CONTENT = "payload-content"
+ const val PAYLOAD_DATA = "payload-data"
+ const val SELECTOR = "selector"
+ const val PROPERTY_CURRENT_INTERFACE = "current-interface"
+ const val PROPERTY_CURRENT_OPERATION = "current-operation"
+ const val PROPERTY_CURRENT_IMPLEMENTATION = "current-implementation"
+
+ const val PROPERTY_ACTION_NAME = "action"
+
+ const val OPERATION_PROCESS = "process"
+ const val OPERATION_PREPARE = "prepare"
+
+ const val BLUEPRINT_RETRIEVE_TYPE_DB = "db"
+ const val BLUEPRINT_RETRIEVE_TYPE_FILE = "file"
+ const val BLUEPRINT_RETRIEVE_TYPE_REPO = "repo"
+
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/BluePrintException.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/BluePrintException.kt new file mode 100644 index 000000000..5c386c214 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/BluePrintException.kt @@ -0,0 +1,49 @@ +/*
+ * 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
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class BluePrintException : Exception {
+
+ var code: Int = 100
+
+ constructor(cause: Throwable) : super(cause)
+ constructor(message: String) : super(message)
+ constructor(message: String, cause: Throwable) : super(message, cause)
+ constructor(cause: Throwable, message: String, vararg args: Any?) : super(String.format(message, *args), cause)
+
+ constructor(code: Int, cause: Throwable) : super(cause) {
+ this.code = code
+ }
+
+ constructor(code: Int, message: String) : super(message) {
+ this.code = code
+ }
+
+ constructor(code: Int, message: String, cause: Throwable) : super(message, cause) {
+ this.code = code
+ }
+
+ constructor(code: Int, cause: Throwable, message: String, vararg args: Any?)
+ : super(String.format(message, *args), cause) {
+ this.code = code
+ }
+}
+
diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/BluePrintTypes.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/BluePrintTypes.kt new file mode 100644 index 000000000..33c811f4a --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/BluePrintTypes.kt @@ -0,0 +1,91 @@ +/*
+ * 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
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+object BluePrintTypes {
+
+ @JvmStatic
+ fun validModelTypes(): List<String> {
+ val validTypes: MutableList<String> = arrayListOf()
+ validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
+ validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE)
+ validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE)
+ validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE)
+ validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE)
+ return validTypes
+ }
+
+ @JvmStatic
+ fun validPropertyTypes(): List<String> {
+ val validTypes: MutableList<String> = arrayListOf()
+ validTypes.add(BluePrintConstants.DATA_TYPE_STRING)
+ validTypes.add(BluePrintConstants.DATA_TYPE_INTEGER)
+ validTypes.add(BluePrintConstants.DATA_TYPE_FLOAT)
+ validTypes.add(BluePrintConstants.DATA_TYPE_BOOLEAN)
+ validTypes.add(BluePrintConstants.DATA_TYPE_TIMESTAMP)
+ validTypes.add(BluePrintConstants.DATA_TYPE_NULL)
+ validTypes.add(BluePrintConstants.DATA_TYPE_LIST)
+ return validTypes
+ }
+
+ @JvmStatic
+ fun validPrimitiveTypes(): List<String> {
+ val validTypes: MutableList<String> = arrayListOf()
+ validTypes.add(BluePrintConstants.DATA_TYPE_STRING)
+ validTypes.add(BluePrintConstants.DATA_TYPE_INTEGER)
+ validTypes.add(BluePrintConstants.DATA_TYPE_FLOAT)
+ validTypes.add(BluePrintConstants.DATA_TYPE_BOOLEAN)
+ validTypes.add(BluePrintConstants.DATA_TYPE_TIMESTAMP)
+ validTypes.add(BluePrintConstants.DATA_TYPE_NULL)
+ return validTypes
+ }
+
+ @JvmStatic
+ fun validCollectionTypes(): List<String> {
+ val validTypes: MutableList<String> = arrayListOf()
+ validTypes.add(BluePrintConstants.DATA_TYPE_LIST)
+ validTypes.add(BluePrintConstants.DATA_TYPE_MAP)
+ return validTypes
+ }
+
+ @JvmStatic
+ fun validCommands(): List<String> {
+ return listOf(BluePrintConstants.EXPRESSION_GET_INPUT,
+ BluePrintConstants.EXPRESSION_GET_ATTRIBUTE,
+ BluePrintConstants.EXPRESSION_GET_PROPERTY,
+ BluePrintConstants.EXPRESSION_GET_ARTIFACT,
+ BluePrintConstants.EXPRESSION_GET_OPERATION_OUTPUT,
+ BluePrintConstants.EXPRESSION_GET_NODE_OF_TYPE)
+ }
+
+ @JvmStatic
+ fun rootNodeTypes(): List<String> {
+ return listOf(BluePrintConstants.MODEL_TYPE_NODES_ROOT)
+ }
+
+ @JvmStatic
+ fun rootDataTypes(): List<String> {
+ return listOf(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT)
+ }
+
+
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/ConfigModelConstant.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/ConfigModelConstant.kt new file mode 100644 index 000000000..bb5a78fd9 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/ConfigModelConstant.kt @@ -0,0 +1,52 @@ +/*
+ * 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
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+object ConfigModelConstant {
+
+ const val MODEL_CONTENT_TYPE_TOSCA_JSON = "TOSCA_JSON"
+ const val MODEL_CONTENT_TYPE_TEMPLATE = "TEMPLATE"
+
+ const val MODEL_TYPE_DATA_TYPE = "tosca.datatypes.Root"
+ const val MODEL_TYPE_DATA_TYPE_DYNAMIC = "tosca.datatypes.Dynamic"
+
+ const val MODEL_TYPE_NODE_DG = "tosca.nodes.DG"
+ const val MODEL_TYPE_NODE_COMPONENT = "tosca.nodes.Component"
+ const val MODEL_TYPE_NODE_VNF = "tosca.nodes.Vnf"
+ const val MODEL_TYPE_NODE_ARTIFACT = "tosca.nodes.Artifact"
+
+ const val MODEL_TYPE_CAPABILITY_NETCONF = "tosca.capability.Netconf"
+ const val MODEL_TYPE_CAPABILITY_SSH = "tosca.capability.Ssh"
+ const val MODEL_TYPE_CAPABILITY_SFTP = "tosca.capability.Sftp"
+ const val MODEL_TYPE_CAPABILITY_CHEF = "tosca.capability.Chef"
+ const val MODEL_TYPE_CAPABILITY_ANSIBLEF = "tosca.capability.Ansible"
+
+ const val CAPABILITY_PROPERTY_MAPPING = "mapping"
+
+ const val SOURCE_INPUT = "input"
+ const val SOURCE_DEFAULT = "default"
+ const val SOURCE_MDSAL = "mdsal"
+ const val SOURCE_DB = "db"
+
+ const val PROPERTY_RECIPE_NAMES = "action-names"
+
+}
diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/CustomFunctions.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/CustomFunctions.kt new file mode 100644 index 000000000..7302f2b96 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/CustomFunctions.kt @@ -0,0 +1,75 @@ +/*
+ * 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
+
+import org.slf4j.helpers.MessageFormatter
+import java.io.File
+import java.io.InputStream
+import kotlin.reflect.KClass
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+
+fun format(message: String, vararg args: Any?) : String{
+ if(args != null && args.isNotEmpty()){
+ return MessageFormatter.arrayFormat(message, args).message
+ }
+ return message
+}
+
+fun <T : Any> MutableMap<String, *>.getCastOptionalValue(key: String, valueType: KClass<T>): T? {
+ if (containsKey(key)) {
+ return get(key) as? T
+ } else {
+ return null
+ }
+}
+
+fun <T : Any> MutableMap<String, *>.getCastValue(key: String, valueType: KClass<T>): T {
+ if (containsKey(key)) {
+ return get(key) as T
+ } else {
+ throw BluePrintException("couldn't find the key " + key)
+ }
+}
+
+fun checkNotEmpty(value : String?) : Boolean{
+ return value != null && value.isNotEmpty()
+}
+
+fun checkNotEmptyNThrow(value : String?, message : String? = value.plus(" is null/empty ")) : Boolean{
+ val notEmpty = value != null && value.isNotEmpty()
+ if(!notEmpty){
+ throw BluePrintException(message!!)
+ }
+ return notEmpty
+}
+
+fun InputStream.toFile(path: String) : File {
+ val file = File(path)
+ file.outputStream().use { this.copyTo(it) }
+ return file
+}
+
+
+
+
+
+
diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/OrchestratorException.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/OrchestratorException.kt new file mode 100644 index 000000000..68abad154 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/OrchestratorException.kt @@ -0,0 +1,48 @@ +/*
+ * 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
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class OrchestratorException : Exception {
+ var code: Int = 100
+
+ constructor(message: String, cause: Throwable) : super(message, cause)
+ constructor(message: String) : super(message)
+ constructor(cause: Throwable) : super(cause)
+ constructor(cause: Throwable, message: String, vararg args: Any?) : super(format(message, *args), cause)
+
+ constructor(code: Int, cause: Throwable) : super(cause) {
+ this.code = code
+ }
+
+ constructor(code: Int, message: String) : super(message) {
+ this.code = code
+ }
+
+ constructor(code: Int, message: String, cause: Throwable) : super(message, cause) {
+ this.code = code
+ }
+
+ constructor(code: Int, cause: Throwable, message: String, vararg args: Any?)
+ : super(String.format(message, *args), cause) {
+ this.code = code
+ }
+}
+
diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/data/BluePrintExpressionData.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/data/BluePrintExpressionData.kt new file mode 100644 index 000000000..c0eb13f92 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/data/BluePrintExpressionData.kt @@ -0,0 +1,70 @@ +/*
+ * 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.data
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.node.ObjectNode
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+data class ExpressionData(
+ var isExpression: Boolean = false,
+ var valueNode: JsonNode,
+ var expressionNode: ObjectNode? = null,
+ var inputExpression: InputExpression? = null,
+ var propertyExpression: PropertyExpression? = null,
+ var attributeExpression: AttributeExpression? = null,
+ var artifactExpression: ArtifactExpression? = null,
+ var operationOutputExpression: OperationOutputExpression? = null,
+ var command: String? = null
+)
+
+data class InputExpression(
+ var propertyName: String
+)
+
+data class PropertyExpression(
+ var modelableEntityName: String = "SELF",
+ var reqOrCapEntityName: String? = null,
+ var propertyName: String,
+ var subPropertyName: String? = null
+)
+
+data class AttributeExpression(
+ var modelableEntityName: String = "SELF",
+ var reqOrCapEntityName: String? = null,
+ var attributeName: String,
+ var subAttributeName: String? = null
+)
+
+data class ArtifactExpression(
+ val modelableEntityName: String = "SELF",
+ val artifactName: String,
+ val location: String? = "LOCAL_FILE",
+ val remove: Boolean? = false
+)
+
+data class OperationOutputExpression(
+ val modelableEntityName: String = "SELF",
+ val interfaceName: String,
+ val operationName: String,
+ val propertyName: String
+)
+
+
diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/data/BluePrintModel.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/data/BluePrintModel.kt new file mode 100644 index 000000000..6d677ffae --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/data/BluePrintModel.kt @@ -0,0 +1,604 @@ +/*
+ * 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.data
+
+import com.fasterxml.jackson.annotation.JsonIgnore
+import com.fasterxml.jackson.annotation.JsonProperty
+import com.fasterxml.jackson.databind.JsonNode
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+open class EntityType {
+ @get:JsonIgnore
+ var id: String? = null
+ var description: String? = null
+ var version: String = "1.0.0"
+ var metadata: MutableMap<String, String>? = null
+ @get:JsonProperty("derived_from")
+ lateinit var derivedFrom: String
+ var attributes: MutableMap<String, AttributeDefinition>? = null
+ var properties: MutableMap<String, PropertyDefinition>? = null
+}
+
+/*
+ 5.3.2 tosca.datatypes.org.onap.ccsdk.apps.controllerblueprints.core.data.Credential
+ The org.onap.ccsdk.apps.controllerblueprints.core.data.Credential type is a complex TOSCA data Type used when describing
+ authorization credentials used to access network accessible resources.
+ */
+class Credential {
+ @get:JsonIgnore
+ var id: String? = null
+ var protocol: String? = null
+ @get:JsonProperty("token_type")
+ lateinit var tokenType: String
+ lateinit var token: String
+ var keys: MutableMap<String, String>? = null
+ lateinit var user: String
+}
+
+/*
+3.5.2 Constraint clause
+A constraint clause defines an operation along with one or more compatible values that can be used to define a constraint on a property or parameter’s allowed values when it is defined in a TOSCA Service Template or one of its entities.
+ */
+class ConstraintClause {
+ @get:JsonProperty("equal")
+ var equal: Any? = null
+ @get:JsonProperty("greater_than")
+ var greaterThan: Any? = null
+ @get:JsonProperty("greater_or_equal")
+ var greaterOrEqual: Any? = null
+ @get:JsonProperty("less_than")
+ var lessThan: Any? = null
+ @get:JsonProperty("less_or_equal")
+ var lessOrEqual: Any? = null
+ @get:JsonProperty("in_range")
+ var inRange: Any? = null
+ @get:JsonProperty("valid_values")
+ var validValues: MutableList<Any>? = null
+ @get:JsonProperty("length")
+ var length: Any? = null
+ @get:JsonProperty("min_length")
+ var minLength: Any? = null
+ @get:JsonProperty("max_length")
+ var maxLength: Any? = null
+ @get:JsonProperty("pattern")
+ var pattern: String? = null
+}
+
+/*
+3.5.4 Node Filter definition
+A node filter definition defines criteria for selection of a TOSCA Node Template based upon the template’s property values, capabilities and capability properties.
+ */
+
+class NodeFilterDefinition {
+ var properties: MutableMap<String, PropertyDefinition>? = null
+ var capabilities : MutableList<String>? = null
+}
+
+/*
+3.5.5 Repository definition
+ A repository definition defines a named external repository which contains deployment
+ and implementation artifacts that are referenced within the TOSCA Service Template.
+*/
+class RepositoryDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ var description: String? = null
+ lateinit var url: String
+ var credential: Credential? = null
+}
+
+
+/*
+3.5.6 Artifact definition
+An artifact definition defines a named, typed file that can be associated with Node Type
+or Node Template and used by orchestration engine to facilitate deployment and implementation of interface operations.
+ */
+class ArtifactDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ var type: String? = null
+ var file: String? = null
+ var repository: String? = null
+ var description: String? = null
+ @get:JsonProperty("deploy_Path")
+ var deployPath: String? = null
+ var properties: MutableMap<String, JsonNode>? = null
+ var content: String? = null
+ @Deprecated("Mapping content is define by the Type")
+ var mappingContent: String? = null
+}
+
+
+/*
+3.5.7 Import definition
+An import definition is used within a TOSCA Service Template to locate and uniquely name
+another TOSCA Service Template file which has type and template definitions to be imported (included)
+and referenced within another Service Template.
+ */
+class ImportDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ lateinit var file: String
+ var repository: String? = null
+ @get:JsonProperty("namespace_uri")
+ var namespaceUri: String? = null
+ @get:JsonProperty("namespace_prefix")
+ var namespacePrefix: String? = null
+}
+
+/*
+3.5.8 Property definition A property definition defines a named, typed value and related data that can be associated with an
+entity defined in this specification (e.g., Node Types, Relationship Types, Capability Types, etc.).
+Properties are used by template authors to provide input values to TOSCA entities which indicate their “desired state” when they are
+instantiated. The value of a property can be retrieved using the get_property function within TOSCA Service Templates.
+ */
+class PropertyDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ var description: String? = null
+ var required: Boolean? = null
+ var type: String? = null
+ @get:JsonProperty("default")
+ var defaultValue: Any? = null
+ var status: String? = null
+ var constraints: MutableList<ConstraintClause>? = null
+ @get:JsonProperty("entry_schema")
+ var entrySchema: EntrySchema? = null
+ var value: Any? = null
+}
+
+
+/*
+3.5.10 Attribute definition
+
+An attribute definition defines a named, typed value that can be associated with an entity defined in this
+specification (e.g., a Node, Relationship or Capability Type). Specifically, it is used to expose the
+“actual state” of some property of a TOSCA entity after it has been deployed and instantiated
+(as set by the TOSCA orchestrator). Attribute values can be retrieved via the get_attribute function
+from the instance model and used as values to other entities within TOSCA Service Templates.
+ */
+
+class AttributeDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ var description: String? = null
+ lateinit var type: String
+ @JsonProperty("default")
+ var _default: Any? = null
+ var status: String? = null
+ @JsonProperty("entry_schema")
+ var entry_schema: String? = null
+}
+
+/*
+3.5.13 Operation definition
+An operation definition defines a named function or procedure that can be bound to an implementation artifact (e.g., a script).
+ */
+class OperationDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ var description: String? = null
+ var implementation: Implementation? = null
+ var inputs: MutableMap<String, PropertyDefinition>? = null
+ var outputs: MutableMap<String, PropertyDefinition>? = null
+}
+
+class Implementation {
+ var primary: String? = null
+ var dependencies: MutableList<String>? = null
+}
+
+/*
+3.5.14 Interface definition
+An interface definition defines a named interface that can be associated with a Node or Relationship Type
+ */
+class InterfaceDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ var type: String? = null
+ var operations: MutableMap<String, OperationDefinition>? = null
+ var inputs: MutableMap<String, PropertyDefinition>? = null
+}
+
+/*
+3.5.15 Event Filter definition
+An event filter definition defines criteria for selection of an attribute, for the purpose of monitoring it, within a TOSCA entity, or one its capabilities.
+ */
+class EventFilterDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ lateinit var node: String
+ var requirement: String? = null
+ var capability: String? = null
+}
+
+/*
+3.5.16 Trigger definition TODO
+A trigger definition defines the event, condition and action that is used to “trigger” a policy it is associated with.
+ */
+class TriggerDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ var description: String? = null
+ @get:JsonProperty("event_type")
+ lateinit var eventType: String
+ lateinit var action: String
+}
+
+/*
+ 3.5.17 org.onap.ccsdk.apps.controllerblueprints.core.data.Workflow activity definition
+ A workflow activity defines an operation to be performed in a TOSCA workflow. Activities allows to:
+ · Delegate the workflow for a node expected to be provided by the orchestrator
+ · Set the state of a node
+ · Call an operation defined on a TOSCA interface of a node, relationship or group
+ · Inline another workflow defined in the topology (to allow reusability)
+ */
+class Activity {
+ var delegate: String? = null
+ @get:JsonProperty("set_state")
+ var setState: String? = null
+ @get:JsonProperty("call_operation")
+ var callOperation: String? = null
+ var inlines: ArrayList<String>? = null
+}
+
+/*
+3.5.20 org.onap.ccsdk.apps.controllerblueprints.core.data.Workflow precondition definition
+A workflow condition can be used as a filter or precondition to check if a workflow can be processed or not based on the state of the instances of a TOSCA topology deployment. When not met, the workflow will not be triggered.
+ */
+class PreConditionDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ lateinit var target: String
+ @get:JsonProperty("target_relationship")
+ lateinit var targetRelationship: String
+ lateinit var condition: ArrayList<ConditionClause>
+}
+
+/*
+3.5.21 org.onap.ccsdk.apps.controllerblueprints.core.data.Workflow step definition
+A workflow step allows to define one or multiple sequenced activities in a workflow and how they are connected to other steps in the workflow. They are the building blocks of a declarative workflow.
+ */
+class Step {
+ @get:JsonIgnore
+ var id: String? = null
+ var description: String? = null
+ var target: String? = null
+ @JsonProperty("target_relationship")
+ var targetRelationship: String? = null
+ @JsonProperty("operation_host")
+ var operationHost: String? = null
+ var activities: ArrayList<Activity>? = null
+ @get:JsonProperty("on_success")
+ var onSuccess: ArrayList<String>? = null
+ @get:JsonProperty("on_failure")
+ var onFailure: ArrayList<String>? = null
+}
+
+/*
+3.6.2 Capability definition
+A capability definition defines a named, typed set of data that can be associated with Node Type or Node Template to describe a transparent capability or feature of the software component the node describes.
+ */
+
+class CapabilityDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ var type: String? = null
+ var description: String? = null
+ var properties: MutableMap<String, PropertyDefinition>? = null
+ @get:JsonProperty("valid_source_types")
+ var validSourceTypes: MutableList<String>? = null
+ var occurrences: MutableList<Any>? = null
+}
+
+/*
+3.6.3 Requirement definition
+The Requirement definition describes a named requirement (dependencies) of a TOSCA Node Type or Node template which needs to be fulfilled by a matching Capability definition declared by another TOSCA modelable entity. The requirement definition may itself include the specific name of the fulfilling entity (explicitly) or provide an abstract type, along with additional filtering characteristics, that a TOSCA orchestrator can use to fulfill the capability at runtime (implicitly).
+ */
+class RequirementDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ var description: String? = null
+ var capability: String? = null
+ var node: String? = null
+ var relationship: String? = null
+ var occurrences: MutableList<Any>? = null
+}
+
+/*
+3.6.4 Artifact Type
+An Artifact Type is a reusable entity that defines the type of one or more files that are used to define implementation or deployment artifacts that are referenced by nodes or relationships on their operations.
+ */
+class ArtifactType : EntityType() {
+ @get:JsonProperty("mime_type")
+ var mimeType: String? = null
+ @get:JsonProperty("file_ext")
+ var fileExt: MutableList<String>? = null
+
+}
+
+/*
+3.6.6 Data Type
+A Data Type definition defines the schema for new named datatypes in TOSCA.
+ */
+
+class DataType : EntityType(){
+ var constraints: MutableList<MutableMap<String, Any>>? = null
+}
+
+/*
+3.6.9 Node Type
+A Node Type is a reusable entity that defines the type of one or more Node Templates. As such, a Node Type defines the structure of observable properties via a Properties Definition, the Requirements and Capabilities of the node as well as its supported interfaces.
+
+ */
+
+class NodeType : EntityType() {
+ var capabilities: MutableMap<String, CapabilityDefinition>? = null
+ var requirements: MutableMap<String, RequirementDefinition>? = null
+ var interfaces: MutableMap<String, InterfaceDefinition>? = null
+ var artifacts: MutableMap<String, ArtifactDefinition>? = null
+}
+
+/*
+3.6.8 Requirement Type
+A Requirement Type is a reusable entity that describes a kind of requirement that a Node Type can declare to expose. The TOSCA Simple Profile seeks to simplify the need for declaring specific Requirement Types from nodes and instead rely upon nodes declaring their features sets using TOSCA Capability Types along with a named Feature notation.
+ */
+
+class RequirementType : EntityType() {
+ var requirements: MutableMap<String, RequirementDefinition>? = null
+ var capabilities: MutableMap<String, CapabilityDefinition>? = null
+ var interfaces: MutableMap<String, InterfaceDefinition>? = null
+ var artifacts: MutableMap<String, ArtifactDefinition>? = null
+}
+
+/*
+3.6.10 Relationship Type
+A Relationship Type is a reusable entity that defines the type of one or more relationships between Node Types or Node Templates.
+*/
+
+class RelationshipType : EntityType() {
+ var interfaces: MutableMap<String, InterfaceDefinition>? = null
+ @get:JsonProperty("valid_target_types")
+ var validTargetTypes: ArrayList<String>? = null
+}
+
+/*
+3.6.11 Group Type
+A Group Type defines logical grouping types for nodes, typically for different management purposes.
+Groups can effectively be viewed as logical nodes that are not part of the physical deployment topology
+ of an application, yet can have capabilities and the ability to attach policies and interfaces
+ that can be applied (depending on the group type) to its member nodes.
+ */
+
+class GroupType : EntityType() {
+ var members: MutableList<String>? = null
+ var requirements: ArrayList<RequirementDefinition>? = null
+ var capabilities: MutableMap<String, CapabilityDefinition>? = null
+ var interfaces: MutableMap<String, InterfaceDefinition>? = null
+
+}
+
+/*
+ 3.6.12 Policy Type
+ A Policy Type defines a type of requirement that affects or governs an application or service’s
+ topology at some stage of its lifecycle, but is not explicitly part of the topology itself
+ (i.e., it does not prevent the application or service from being deployed or run if it did not exist).
+ */
+class PolicyType : EntityType(){
+ lateinit var targets: MutableList<String>
+}
+
+/*
+3.7.1 Capability assignment
+A capability assignment allows node template authors to assign values to properties and attributes for a named capability definition that is part of a Node Template’s type definition.
+ */
+class CapabilityAssignment {
+ @get:JsonIgnore
+ var id: String? = null
+ var attributes: MutableMap<String, JsonNode>? = null
+ var properties: MutableMap<String, JsonNode>? = null
+}
+
+/*
+3.7.4 Relationship Template
+A Relationship Template specifies the occurrence of a manageable relationship between node templates as part of an application’s topology model that is defined in a TOSCA Service Template. A Relationship template is an instance of a specified Relationship Type and can provide customized properties, constraints or operations which override the defaults provided by its Relationship Type and its implementations.
+ */
+class GroupDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ lateinit var type: String
+ var description: String? = null
+ var metadata : MutableMap<String, String>? = null
+ var properties : MutableMap<String, JsonNode>? = null
+ var members = ArrayList<String>()
+ var interfaces : MutableMap<String, InterfaceDefinition>?= null
+}
+
+/*
+3.7.6 Policy definition
+A policy definition defines a policy that can be associated with a TOSCA topology or top-level entity definition (e.g., group definition, node template, etc.).
+ */
+class PolicyDefinition {
+ @get:JsonIgnore
+ var id: String? = null
+ lateinit var type: String
+ var description: String? = null
+ var metadata: MutableMap<String, String>? = null
+ var properties: MutableMap<String, JsonNode>? = null
+ var targets: MutableList<String>? = null
+}
+
+
+/*
+3.8 Topology Template definition
+This section defines the topology template of a cloud application. The main ingredients of the topology template are node templates representing components of the application and relationship templates representing links between the components. These elements are defined in the nested node_templates section and the nested relationship_templates sections, respectively. Furthermore, a topology template allows for defining input parameters, output parameters as well as grouping of node templates.
+ */
+class TopologyTemplate {
+ @get:JsonIgnore
+ var id: String? = null
+ var description: String? = null
+ var inputs: MutableMap<String, PropertyDefinition>? = null
+ @get:JsonProperty("node_templates")
+ var nodeTemplates: MutableMap<String, NodeTemplate>? = null
+ @get:JsonProperty("relationship_templates")
+ var relationshipTemplates: MutableMap<String, RelationshipTemplate>? = null
+ var policies: MutableMap<String, PolicyDefinition>? = null
+ var outputs: MutableMap<String, PropertyDefinition>? = null
+ @get:JsonProperty("substitution_mappings")
+ var substitutionMappings: Any? = null
+ var workflows: MutableMap<String, Workflow>? = null
+}
+
+class SubstitutionMapping {
+ @get:JsonProperty("node_type")
+ lateinit var nodeType: String
+ lateinit var capabilities: ArrayList<String>
+ lateinit var requirements: ArrayList<String>
+}
+
+class EntrySchema {
+ lateinit var type: String
+ var constraints: MutableList<MutableMap<String, Any>>? = null
+}
+
+class InterfaceAssignment {
+ @get:JsonIgnore
+ var id: String? = null
+ var operations: MutableMap<String, OperationAssignment>? = null
+ var inputs: MutableMap<String, JsonNode>? = null
+}
+
+/*
+3.7.3 Node Template
+A Node Template specifies the occurrence of a manageable software component as part of an application’s topology model which is defined in a TOSCA Service Template. A Node template is an instance of a specified Node Type and can provide customized properties, constraints or operations which override the defaults provided by its Node Type and its implementations.
+ */
+
+class NodeTemplate {
+ @get:JsonIgnore
+ var id: String? = null
+ var description: String? = null
+ lateinit var type: String
+ var metadata: MutableMap<String, String>? = null
+ var directives: MutableList<String>? = null
+ //@get:JsonSerialize(using = PropertyDefinitionValueSerializer::class)
+ var properties: MutableMap<String, JsonNode>? = null
+ var attributes: MutableMap<String, JsonNode>? = null
+ var capabilities: MutableMap<String, CapabilityAssignment>? = null
+ var requirements: MutableMap<String, RequirementAssignment>? = null
+ var interfaces: MutableMap<String, InterfaceAssignment>? = null
+ var artifacts: MutableMap<String, ArtifactDefinition>? = null
+ @get:JsonProperty("node_filter")
+ var nodeFilter: NodeFilterDefinition? = null
+ var copy: String? = null
+}
+
+class OperationAssignment {
+ @get:JsonIgnore
+ var id: String? = null
+ var description: String? = null
+ var implementation: Implementation? = null
+ var inputs: MutableMap<String, JsonNode>? = null
+ var outputs: MutableMap<String, JsonNode>? = null
+}
+
+/*
+3.7.4 Relationship Template
+A Relationship Template specifies the occurrence of a manageable relationship between node templates as part of an application’s topology model that is defined in a TOSCA Service Template. A Relationship template is an instance of a specified Relationship Type and can provide customized properties, constraints or operations which override the defaults provided by its Relationship Type and its implementations.
+ */
+
+class RelationshipTemplate {
+ var type: String? = null
+ var description: String? = null
+ var metadata: MutableMap<String, String>? = null
+ var properties: MutableMap<String, PropertyDefinition>? = null
+ var attributes: MutableMap<String, JsonNode>? = null
+ var interfaces: MutableMap<String, InterfaceDefinition>? = null
+ var copy: String? = null
+}
+
+/*
+3.7.2 Requirement assignment
+A Requirement assignment allows template authors to provide either concrete names of TOSCA templates or provide abstract selection criteria for providers to use to find matching TOSCA templates that are used to fulfill a named requirement’s declared TOSCA Node Type.
+ */
+
+class RequirementAssignment {
+ @get:JsonIgnore
+ var id: String? = null
+ var capability: String? = null
+ var node: String? = null
+ //Relationship Type or Relationship Template
+ var relationship: String? = null
+}
+
+
+class Workflow {
+ @get:JsonIgnore
+ var id: String? = null
+ var description: String? = null
+ var steps: MutableMap<String, Step>? = null
+ var preconditions: ArrayList<PreConditionDefinition>? = null
+ var inputs: MutableMap<String, PropertyDefinition>? = null
+}
+
+
+class ConditionClause {
+ var and: ArrayList<MutableMap<String, Any>>? = null
+ var or: ArrayList<MutableMap<String, Any>>? = null
+ @get:JsonProperty("assert")
+ var assertConditions: ArrayList<MutableMap<String, Any>>? = null
+}
+
+/*
+3.9 Service Template definition
+A TOSCA Service Template (YAML) document contains element definitions of building blocks for cloud application, or complete models of cloud applications. This section describes the top-level structural elements (TOSCA keynames) along with their grammars, which are allowed to appear in a TOSCA Service Template document.
+ */
+
+class ServiceTemplate {
+ @get:JsonIgnore
+ var id: String? = null
+ @get:JsonProperty("tosca_definitions_version")
+ var toscaDefinitionsVersion: String = "controller_blueprint_1_0_0"
+ var metadata: MutableMap<String, String>? = null
+ var description: String? = null
+ @get:JsonProperty("dsl_definitions")
+ var dslDefinitions: MutableMap<String, Any>? = null
+ var repositories: MutableMap<String, RepositoryDefinition>? = null
+ var imports: MutableList<ImportDefinition>? = null
+ @get:JsonProperty("artifact_types")
+ var artifactTypes: MutableMap<String, ArtifactType>? = null
+ @get:JsonProperty("data_types")
+ var dataTypes: MutableMap<String, DataType>? = null
+ @get:JsonProperty("node_types")
+ var nodeTypes: MutableMap<String, NodeType>? = null
+ @get:JsonProperty("policy_types")
+ var policyTypes: PolicyType? = null
+ @get:JsonProperty("topology_template")
+ var topologyTemplate: TopologyTemplate? = null
+}
+
+class ToscaMetaData {
+ lateinit var toscaMetaFileVersion: String
+ lateinit var csarVersion: String
+ lateinit var createdBy: String
+ lateinit var entityDefinitions: String
+ var templateTags: String? = null
+}
+
diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/factory/BluePrintEnhancerFactory.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/factory/BluePrintEnhancerFactory.kt new file mode 100644 index 000000000..2a2963599 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/factory/BluePrintEnhancerFactory.kt @@ -0,0 +1,45 @@ +/*
+ * 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.factory
+
+import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintEnhancerService
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+
+/**
+ * BluePrintEnhancerFactory
+ * @author Brinda Santh
+ *
+ */
+
+object BluePrintEnhancerFactory {
+ private val logger: Logger = LoggerFactory.getLogger(this::class.toString())
+
+ var bluePrintEnhancerServices: MutableMap<String, BluePrintEnhancerService> = HashMap()
+
+ fun register(key: String, bluePrintEnhancerService: BluePrintEnhancerService) {
+ bluePrintEnhancerServices[key] = bluePrintEnhancerService
+ }
+
+ /**
+ * Called by clients to get a Blueprint Parser for the Blueprint parser type
+ */
+ fun instance(key: String): BluePrintEnhancerService? {
+ return bluePrintEnhancerServices.get(key)
+ }
+}
diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/factory/BluePrintParserFactory.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/factory/BluePrintParserFactory.kt new file mode 100644 index 000000000..10eb0e678 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/factory/BluePrintParserFactory.kt @@ -0,0 +1,51 @@ +/*
+ * 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.factory
+
+import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintParserDefaultService
+import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintParserService
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+/**
+ *
+ * BluePrintParserFactory
+ * @author Brinda Santh
+ */
+
+object BluePrintParserFactory {
+ private val logger: Logger = LoggerFactory.getLogger(this::class.toString())
+
+ var bluePrintParserServices: MutableMap<String, BluePrintParserService> = HashMap()
+
+ init {
+ logger.info("Initialised default BluePrintParser Service ")
+ bluePrintParserServices.put(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.TYPE_DEFAULT, BluePrintParserDefaultService())
+ }
+
+ fun register(key:String, bluePrintParserService: BluePrintParserService){
+ bluePrintParserServices.put(key, bluePrintParserService)
+ }
+
+ /**
+ * Called by clients to get a Blueprint Parser for the Blueprint parser type
+ */
+ fun instance(key : String) : BluePrintParserService? {
+ return bluePrintParserServices.get(key)
+ }
+}
+
diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/factory/BluePrintValidatorFactory.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/factory/BluePrintValidatorFactory.kt new file mode 100644 index 000000000..63f788a2f --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/factory/BluePrintValidatorFactory.kt @@ -0,0 +1,45 @@ +/*
+ * 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.factory
+
+
+import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintValidatorDefaultService
+import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintValidatorService
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+
+object BluePrintValidatorFactory {
+
+ var bluePrintValidatorServices: MutableMap<String, BluePrintValidatorService> = HashMap()
+
+ init {
+ bluePrintValidatorServices[org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.TYPE_DEFAULT] = BluePrintValidatorDefaultService()
+ }
+
+ fun register(key:String, bluePrintValidatorService: BluePrintValidatorService){
+ bluePrintValidatorServices[key] = bluePrintValidatorService
+ }
+
+ fun instance(key : String) : BluePrintValidatorService?{
+ return bluePrintValidatorServices[key]
+ }
+
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintChainedService.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintChainedService.kt new file mode 100644 index 000000000..065176342 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintChainedService.kt @@ -0,0 +1,117 @@ +/*
+ * 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.service
+
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.apps.controllerblueprints.core.data.*
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class BluePrintChainedService {
+ var bpc : BluePrintContext
+
+ constructor(bpc : BluePrintContext){
+ this.bpc = bpc
+ }
+
+ fun nodeTypeChained(nodeTypeName: String): NodeType {
+
+ val nodeType: NodeType = bpc.nodeTypeByName(nodeTypeName)
+ val attributes = hashMapOf<String, AttributeDefinition>()
+ val properties = hashMapOf<String, PropertyDefinition>()
+ val requirements = hashMapOf<String, RequirementDefinition>()
+ val capabilities = hashMapOf<String, CapabilityDefinition>()
+ val interfaces = hashMapOf<String, InterfaceDefinition>()
+ val artifacts = hashMapOf<String, ArtifactDefinition>()
+
+ recNodeTypesChained(nodeTypeName).forEach { nodeType ->
+
+ val subAttributes = bpc.nodeTypeByName(nodeType.id!!).attributes
+ if (subAttributes != null) {
+ attributes.putAll(subAttributes)
+ }
+
+ val subProperties = bpc.nodeTypeByName(nodeType.id!!).properties
+ if (subProperties != null) {
+ properties.putAll(subProperties)
+ }
+
+ val subRequirements = bpc.nodeTypeByName(nodeType.id!!).requirements
+ if (subRequirements != null) {
+ requirements.putAll(subRequirements)
+ }
+ val subCapabilities = bpc.nodeTypeByName(nodeType.id!!).capabilities
+ if (subCapabilities != null) {
+ capabilities.putAll(subCapabilities)
+ }
+ val subInterfaces = bpc.nodeTypeByName(nodeType.id!!).interfaces
+ if (subInterfaces != null) {
+ interfaces.putAll(subInterfaces)
+ }
+
+ val subArtifacts = bpc.nodeTypeByName(nodeType.id!!).artifacts
+ if (subArtifacts != null) {
+ artifacts.putAll(subArtifacts)
+ }
+ }
+ nodeType.attributes = attributes
+ nodeType.properties = properties
+ nodeType.requirements = requirements
+ nodeType.capabilities = capabilities
+ nodeType.interfaces = interfaces
+ nodeType.artifacts = artifacts
+ return nodeType
+ }
+
+ fun nodeTypeChainedProperties(nodeTypeName: String): MutableMap<String, PropertyDefinition>? {
+ val nodeType = bpc.nodeTypeByName(nodeTypeName)
+ val properties = hashMapOf<String, PropertyDefinition>()
+
+ recNodeTypesChained(nodeTypeName).forEach { nodeType ->
+ val subProperties = bpc.nodeTypeByName(nodeType.id!!).properties
+ if (subProperties != null) {
+ properties.putAll(subProperties)
+ }
+ }
+ return properties
+ }
+
+ private fun recNodeTypesChained(nodeTypeName: String, nodeTypes: MutableList<NodeType>? = arrayListOf()): MutableList<NodeType> {
+ val nodeType: NodeType = bpc.nodeTypeByName(nodeTypeName)
+ nodeType.id = nodeTypeName
+ val derivedFrom: String = nodeType.derivedFrom
+ if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) {
+ recNodeTypesChained(derivedFrom, nodeTypes)
+ }
+ nodeTypes!!.add(nodeType)
+ return nodeTypes
+ }
+
+ private fun recDataTypesChained(dataTypeName: String, dataTypes: MutableList<DataType>? = arrayListOf()): MutableList<DataType> {
+ val dataType: DataType = bpc.dataTypeByName(dataTypeName)!!
+ dataType.id = dataTypeName
+ val derivedFrom: String = dataType.derivedFrom
+ if (!BluePrintTypes.rootDataTypes().contains(derivedFrom)) {
+ recDataTypesChained(derivedFrom, dataTypes)
+ }
+ dataTypes!!.add(dataType)
+ return dataTypes
+ }
+
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintContext.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintContext.kt new file mode 100644 index 000000000..dde1d58c7 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintContext.kt @@ -0,0 +1,177 @@ +/*
+ * 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.service
+
+import com.fasterxml.jackson.databind.JsonNode
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.apps.controllerblueprints.core.data.*
+import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class BluePrintContext(serviceTemplate: ServiceTemplate) {
+
+ private val logger: Logger = LoggerFactory.getLogger(this::class.toString())
+
+ val serviceTemplate: ServiceTemplate = serviceTemplate
+
+ val imports: List<ImportDefinition>? = serviceTemplate.imports
+
+ val metadata: MutableMap<String, String>? = serviceTemplate.metadata
+
+ val dataTypes: MutableMap<String, DataType>? = serviceTemplate.dataTypes
+
+ val inputs: MutableMap<String, PropertyDefinition>? = serviceTemplate.topologyTemplate?.inputs
+
+ val workflows: MutableMap<String, Workflow>? = serviceTemplate.topologyTemplate?.workflows
+
+ fun blueprintJson(pretty: Boolean = false): String = print("json", pretty)
+
+ fun blueprintYaml(pretty: Boolean = false): String = print("yaml", pretty)
+
+ private fun print(type: String? = "json", pretty: Boolean = false): String {
+ return JacksonUtils.getJson(serviceTemplate, pretty)
+ }
+
+ // Workflow
+ fun workflowByName(name: String): Workflow? = workflows?.get(name)
+
+ // Data Type
+ fun dataTypeByName(name: String): DataType? = dataTypes?.get(name)
+
+ // Artifact Type
+ val artifactTypes: MutableMap<String, ArtifactType>? = serviceTemplate.artifactTypes
+
+ // Node Type Methods
+ val nodeTypes: MutableMap<String, NodeType>? = serviceTemplate.nodeTypes
+
+ fun nodeTypeByName(name: String): NodeType =
+ nodeTypes?.get(name) ?: throw BluePrintException(String.format("Failed to get node type for the name : %s", name))
+
+ fun nodeTypeDerivedFrom(name: String): MutableMap<String, NodeType>? {
+ return nodeTypes?.filterValues { nodeType -> nodeType.derivedFrom == name }?.toMutableMap()
+ }
+
+ fun nodeTypeInterface(nodeTypeName: String, interfaceName: String): InterfaceDefinition? {
+ return nodeTypeByName(nodeTypeName).interfaces?.values?.first()
+ }
+
+ fun nodeTypeInterfaceOperation(nodeTypeName: String, interfaceName: String, operationName: String): OperationDefinition? {
+ return nodeTypeInterface(nodeTypeName, interfaceName)?.operations?.get(operationName)
+ }
+
+ fun interfaceNameForNodeType(nodeTypeName: String): String? {
+ return nodeTypeByName(nodeTypeName).interfaces?.keys?.first()
+ }
+
+ fun nodeTypeInterfaceOperationInputs(nodeTypeName: String, interfaceName: String, operationName: String): MutableMap<String, PropertyDefinition>? {
+ return nodeTypeInterfaceOperation(nodeTypeName, interfaceName, operationName)?.inputs
+ }
+
+ fun nodeTypeInterfaceOperationOutputs(nodeTypeName: String, interfaceName: String, operationName: String): MutableMap<String, PropertyDefinition>? {
+ return nodeTypeInterfaceOperation(nodeTypeName, interfaceName, operationName)?.outputs
+ }
+
+ // Node Template Methods
+ val nodeTemplates: MutableMap<String, NodeTemplate>? = serviceTemplate.topologyTemplate?.nodeTemplates
+
+ fun nodeTemplateByName(name: String): NodeTemplate =
+ nodeTemplates?.get(name) ?: throw BluePrintException("Failed to get node template for the name " + name)
+
+ fun nodeTemplateForNodeType(name: String): MutableMap<String, NodeTemplate>? {
+ return nodeTemplates?.filterValues { nodeTemplate -> nodeTemplate.type == name }?.toMutableMap()
+ }
+
+ fun nodeTemplateNodeType(nodeTemplateName: String): NodeType {
+ val nodeTemplateType: String = nodeTemplateByName(nodeTemplateName).type
+ return nodeTypeByName(nodeTemplateType)
+ }
+
+ fun nodeTemplateProperty(nodeTemplateName: String, propertyName: String): Any? {
+ return nodeTemplateByName(nodeTemplateName).properties?.get(propertyName)
+ }
+
+ fun nodeTemplateArtifacts(nodeTemplateName: String): MutableMap<String, ArtifactDefinition>? {
+ return nodeTemplateByName(nodeTemplateName).artifacts
+ }
+
+ fun nodeTemplateArtifact(nodeTemplateName: String, artifactName: String): ArtifactDefinition? {
+ return nodeTemplateArtifacts(nodeTemplateName)?.get(artifactName)
+ }
+
+ fun nodeTemplateFirstInterface(nodeTemplateName: String): InterfaceAssignment? {
+ return nodeTemplateByName(nodeTemplateName).interfaces?.values?.first()
+ }
+
+ fun nodeTemplateFirstInterfaceName(nodeTemplateName: String): String? {
+ return nodeTemplateByName(nodeTemplateName).interfaces?.keys?.first()
+ }
+
+ fun nodeTemplateFirstInterfaceFirstOperationName(nodeTemplateName: String): String? {
+ return nodeTemplateFirstInterface(nodeTemplateName)?.operations?.keys?.first()
+ }
+
+ fun nodeTemplateInterfaceOperationInputs(nodeTemplateName: String, interfaceName: String, operationName: String): MutableMap<String, JsonNode>? {
+ return nodeTemplateByName(nodeTemplateName).interfaces?.get(interfaceName)?.operations?.get(operationName)?.inputs
+ }
+
+ fun nodeTemplateInterfaceOperationOutputs(nodeTemplateName: String, interfaceName: String, operationName: String): MutableMap<String, JsonNode>? {
+ return nodeTemplateByName(nodeTemplateName).interfaces?.get(interfaceName)?.operations?.get(operationName)?.outputs
+ }
+
+ fun nodeTemplateInterface(nodeTemplateName: String, interfaceName: String): InterfaceAssignment? {
+ return nodeTemplateByName(nodeTemplateName).interfaces?.get(interfaceName)
+ }
+
+
+ fun nodeTemplateInterfaceOperation(nodeTemplateName: String, interfaceName: String, operationName: String): OperationAssignment? {
+ return nodeTemplateInterface(nodeTemplateName, interfaceName)?.operations?.get(operationName)
+ }
+
+ fun nodeTemplateCapability(nodeTemplateName: String, capabilityName: String): CapabilityAssignment? {
+ return nodeTemplateByName(nodeTemplateName).capabilities?.get(capabilityName)
+ }
+
+ fun nodeTemplateRequirement(nodeTemplateName: String, requirementName: String): RequirementAssignment? {
+ return nodeTemplateByName(nodeTemplateName).requirements?.get(requirementName)
+ }
+
+ fun nodeTemplateRequirementNode(nodeTemplateName: String, requirementName: String): NodeTemplate {
+ val nodeTemplateName: String = nodeTemplateByName(nodeTemplateName).requirements?.get(requirementName)?.node
+ ?: throw BluePrintException(String.format("failed to get node name for node template's (%s) requirement's (%s) " + nodeTemplateName, requirementName))
+ return nodeTemplateByName(nodeTemplateName)
+ }
+
+ fun nodeTemplateCapabilityProperty(nodeTemplateName: String, capabilityName: String, propertyName: String): Any? {
+ return nodeTemplateCapability(nodeTemplateName, capabilityName)?.properties?.get(propertyName)
+ }
+
+ // Chained Functions
+
+ fun nodeTypeChained(nodeTypeName: String): NodeType {
+ return BluePrintChainedService(this).nodeTypeChained(nodeTypeName)
+ }
+
+ fun nodeTypeChainedProperties(nodeTypeName: String): MutableMap<String, PropertyDefinition>? {
+ return BluePrintChainedService(this).nodeTypeChainedProperties(nodeTypeName)
+ }
+
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintEnhancerRepoService.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintEnhancerRepoService.kt new file mode 100644 index 000000000..5369d509b --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintEnhancerRepoService.kt @@ -0,0 +1,92 @@ +/*
+ * 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.service
+
+import org.apache.commons.io.FileUtils
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.apps.controllerblueprints.core.data.*
+import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
+import java.io.File
+import java.io.Serializable
+import java.nio.charset.Charset
+
+/**
+ * BluePrintEnhancerRepoFileService
+ * @author Brinda Santh
+ *
+ */
+
+interface BluePrintEnhancerRepoService : Serializable {
+
+ @Throws(BluePrintException::class)
+ fun getNodeType(nodeTypeName: String): NodeType?
+
+ @Throws(BluePrintException::class)
+ fun getDataType(dataTypeName: String): DataType?
+
+ @Throws(BluePrintException::class)
+ fun getArtifactType(artifactTypeName: String): ArtifactType?
+
+ @Throws(BluePrintException::class)
+ fun getRelationshipType(relationshipTypeName: String): RelationshipType?
+
+ @Throws(BluePrintException::class)
+ fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition?
+
+}
+
+
+class BluePrintEnhancerRepoFileService(val basePath: String) : BluePrintEnhancerRepoService {
+
+ val dataTypePath = basePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
+ val nodeTypePath = basePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE)
+ val artifactTypePath = basePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE)
+ val capabilityTypePath = basePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE)
+ val relationshipTypePath = basePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE)
+ val extension = ".json"
+
+ override fun getDataType(dataTypeName: String): DataType? {
+ val content = FileUtils.readFileToString(File(dataTypePath.plus(BluePrintConstants.PATH_DIVIDER)
+ .plus(dataTypeName).plus(extension)), Charset.defaultCharset())
+ return JacksonUtils.readValue(content)
+ }
+
+ override fun getNodeType(nodeTypeName: String): NodeType? {
+ val content = FileUtils.readFileToString(File(nodeTypePath.plus(BluePrintConstants.PATH_DIVIDER)
+ .plus(nodeTypeName).plus(extension)), Charset.defaultCharset())
+ return JacksonUtils.readValue(content)
+ }
+
+ override fun getArtifactType(artifactTypeName: String): ArtifactType? {
+ val content = FileUtils.readFileToString(File(artifactTypePath.plus(BluePrintConstants.PATH_DIVIDER)
+ .plus(artifactTypeName).plus(extension)), Charset.defaultCharset())
+ return JacksonUtils.readValue(content)
+ }
+
+ override fun getRelationshipType(relationshipTypeName: String): RelationshipType? {
+ val content = FileUtils.readFileToString(File(relationshipTypePath.plus(BluePrintConstants.PATH_DIVIDER)
+ .plus(relationshipTypeName).plus(extension)), Charset.defaultCharset())
+ return JacksonUtils.readValue(content)
+ }
+
+ override fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition? {
+ val content = FileUtils.readFileToString(File(capabilityTypePath.plus(BluePrintConstants.PATH_DIVIDER)
+ .plus(capabilityDefinitionName).plus(extension)), Charset.defaultCharset())
+ return JacksonUtils.readValue(content)
+ }
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintEnhancerService.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintEnhancerService.kt new file mode 100644 index 000000000..8f1728762 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintEnhancerService.kt @@ -0,0 +1,240 @@ +/*
+ * 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.service
+
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.apps.controllerblueprints.core.data.*
+import org.onap.ccsdk.apps.controllerblueprints.core.format
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import java.io.Serializable
+
+/**
+ * BluePrintEnhancerService
+ * @author Brinda Santh
+ *
+ */
+interface BluePrintEnhancerService : Serializable {
+
+ @Throws(BluePrintException::class)
+ fun enhance(content: String): ServiceTemplate
+
+ @Throws(BluePrintException::class)
+ fun enhance(serviceTemplate: ServiceTemplate): ServiceTemplate
+
+ /**
+ * Read Blueprint from CSAR structure Directory
+ */
+ @Throws(BluePrintException::class)
+ fun enhance(fileName: String, basePath: String): ServiceTemplate
+}
+
+open class BluePrintEnhancerDefaultService(val bluePrintEnhancerRepoService: BluePrintEnhancerRepoService) : BluePrintEnhancerService {
+
+ private val log: Logger = LoggerFactory.getLogger(BluePrintEnhancerDefaultService::class.java)
+
+ lateinit var serviceTemplate: ServiceTemplate
+
+ override fun enhance(content: String): ServiceTemplate {
+ TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ }
+
+ override fun enhance(fileName: String, basePath: String): ServiceTemplate {
+ TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ }
+
+ override fun enhance(serviceTemplate: ServiceTemplate): ServiceTemplate {
+ this.serviceTemplate = serviceTemplate
+ initialCleanUp()
+ enrichTopologyTemplate(serviceTemplate)
+
+ // log.info("Enriched Blueprint :\n {}", JacksonUtils.getJson(serviceTemplate, true))
+ return this.serviceTemplate
+ }
+
+ open fun initialCleanUp() {
+ serviceTemplate.artifactTypes?.clear()
+ serviceTemplate.nodeTypes?.clear()
+ serviceTemplate.dataTypes?.clear()
+
+ serviceTemplate.artifactTypes = HashMap()
+ serviceTemplate.nodeTypes = HashMap()
+ serviceTemplate.dataTypes = HashMap()
+
+ }
+
+ open fun enrichTopologyTemplate(serviceTemplate: ServiceTemplate) {
+ serviceTemplate.topologyTemplate?.let { topologyTemplate ->
+ enrichTopologyTemplateInputs(topologyTemplate)
+ enrichTopologyTemplateNodeTemplates(topologyTemplate)
+ }
+ }
+
+ open fun enrichTopologyTemplateInputs(topologyTemplate: TopologyTemplate) {
+ topologyTemplate.inputs?.let { inputs ->
+ enrichPropertyDefinitions(inputs)
+ }
+ }
+
+ open fun enrichTopologyTemplateNodeTemplates(topologyTemplate: TopologyTemplate) {
+ topologyTemplate.nodeTemplates?.forEach { nodeTemplateName, nodeTemplate ->
+ enrichNodeTemplate(nodeTemplateName, nodeTemplate)
+ }
+ }
+
+ @Throws(BluePrintException::class)
+ open fun enrichNodeTemplate(nodeTemplateName: String, nodeTemplate: NodeTemplate) {
+ val nodeTypeName = nodeTemplate.type
+ // Get NodeType from Repo and Update Service Template
+ val nodeType = populateNodeType(nodeTypeName)
+
+ // Enrich NodeType
+ enrichNodeType(nodeTypeName, nodeType)
+
+ //Enrich Node Template Artifacts
+ enrichNodeTemplateArtifactDefinition(nodeTemplateName, nodeTemplate)
+ }
+
+ open fun enrichNodeType(nodeTypeName: String, nodeType: NodeType) {
+
+ // NodeType Property Definitions
+ enrichNodeTypeProperties(nodeTypeName, nodeType)
+
+ //NodeType Requirement
+ enrichNodeTypeRequirements(nodeTypeName, nodeType)
+
+ //NodeType Capability
+ enrichNodeTypeCapabilityProperties(nodeTypeName, nodeType)
+
+ //NodeType Interface
+ enrichNodeTypeInterfaces(nodeTypeName, nodeType)
+ }
+
+ open fun enrichNodeTypeProperties(nodeTypeName: String, nodeType: NodeType) {
+ nodeType.properties?.let { enrichPropertyDefinitions(nodeType.properties!!) }
+ }
+
+ open fun enrichNodeTypeRequirements(nodeTypeName: String, nodeType: NodeType) {
+
+ nodeType.requirements?.forEach { requirementDefinitionName, requirementDefinition ->
+ // Populate Requirement Node
+ requirementDefinition.node?.let { requirementNodeTypeName ->
+ // Get Requirement NodeType from Repo and Update Service Template
+ val requirementNodeType = populateNodeType(requirementNodeTypeName)
+
+ enrichNodeType(requirementNodeTypeName, requirementNodeType)
+ }
+ }
+ }
+
+ open fun enrichNodeTypeCapabilityProperties(nodeTypeName: String, nodeType: NodeType) {
+ nodeType.capabilities?.forEach { capabilityDefinitionName, capabilityDefinition ->
+ capabilityDefinition.properties?.let { properties ->
+ enrichPropertyDefinitions(properties)
+ }
+ }
+ }
+
+ open fun enrichNodeTypeInterfaces(nodeTypeName: String, nodeType: NodeType) {
+ nodeType.interfaces?.forEach { interfaceName, interfaceObj ->
+ // Populate Node type Interface Operation
+ log.info("*** ** Enriching NodeType: {} Interface {}", nodeTypeName, interfaceName)
+ populateNodeTypeInterfaceOperation(nodeTypeName, interfaceName, interfaceObj)
+
+ }
+ }
+
+ open fun populateNodeTypeInterfaceOperation(nodeTypeName: String, interfaceName: String, interfaceObj: InterfaceDefinition) {
+
+ interfaceObj.operations?.forEach { operationName, operation ->
+ enrichNodeTypeInterfaceOperationInputs(nodeTypeName, operationName, operation)
+ enrichNodeTypeInterfaceOperationOputputs(nodeTypeName, operationName, operation)
+ }
+ }
+
+ open fun enrichNodeTypeInterfaceOperationInputs(nodeTypeName: String, operationName: String, operation: OperationDefinition) {
+ operation.inputs?.let { inputs ->
+ enrichPropertyDefinitions(inputs)
+ }
+ }
+
+ open fun enrichNodeTypeInterfaceOperationOputputs(nodeTypeName: String, operationName: String, operation: OperationDefinition) {
+ operation.outputs?.let { inputs ->
+ enrichPropertyDefinitions(inputs)
+ }
+ }
+
+ open fun enrichPropertyDefinitions(properties: MutableMap<String, PropertyDefinition>) {
+
+ properties.forEach { propertyName, propertyDefinition ->
+ enrichPropertyDefinition(propertyName, propertyDefinition)
+ }
+ }
+
+ open fun enrichPropertyDefinition(propertyName: String, propertyDefinition: PropertyDefinition) {
+ val propertyType = propertyDefinition.type
+ ?: throw BluePrintException(format("Property type is missing for property : {}", propertyName))
+ if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)) {
+
+ } else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) {
+ val entrySchema = propertyDefinition.entrySchema
+ ?: throw BluePrintException(format("Entry Schema is missing for collection property : {}", propertyName))
+
+ if (!BluePrintTypes.validPrimitiveTypes().contains(entrySchema.type)) {
+ populateDataTypes(entrySchema.type)
+ }
+ } else {
+ populateDataTypes(propertyType)
+ }
+
+ }
+
+ open fun enrichNodeTemplateArtifactDefinition(nodeTemplateName: String, nodeTemplate: NodeTemplate) {
+
+ nodeTemplate.artifacts?.forEach { artifactDefinitionName, artifactDefinition ->
+ val artifactTypeName = artifactDefinition.type
+ ?: throw BluePrintException(format("Artifact type is missing for NodeTemplate({}) artifact({})", nodeTemplateName, artifactDefinitionName))
+
+ // Populate Artifact Type
+ populateArtifactType(artifactTypeName)
+ }
+ }
+
+ open fun populateNodeType(nodeTypeName: String): NodeType {
+ val nodeType = bluePrintEnhancerRepoService.getNodeType(nodeTypeName)
+ ?: throw BluePrintException(format("Couldn't get NodeType({}) from repo.", nodeTypeName))
+ serviceTemplate.nodeTypes?.put(nodeTypeName, nodeType)
+ return nodeType
+ }
+
+ open fun populateArtifactType(artifactTypeName: String): ArtifactType {
+ val artifactType = bluePrintEnhancerRepoService.getArtifactType(artifactTypeName)
+ ?: throw BluePrintException(format("Couldn't get ArtifactType({}) from repo.", artifactTypeName))
+ serviceTemplate.artifactTypes?.put(artifactTypeName, artifactType)
+ return artifactType
+ }
+
+ open fun populateDataTypes(dataTypeName: String): DataType {
+ val dataType = bluePrintEnhancerRepoService.getDataType(dataTypeName)
+ ?: throw BluePrintException(format("Couldn't get DataType({}) from repo.", dataTypeName))
+ serviceTemplate.dataTypes?.put(dataTypeName, dataType)
+ return dataType
+ }
+
+}
+
diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintExpressionService.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintExpressionService.kt new file mode 100644 index 000000000..36959c46d --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintExpressionService.kt @@ -0,0 +1,174 @@ +/*
+ * 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.service
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.node.ArrayNode
+import com.fasterxml.jackson.databind.node.ObjectNode
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.apps.controllerblueprints.core.data.*
+import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+object BluePrintExpressionService {
+ val logger: Logger = LoggerFactory.getLogger(this::class.toString())
+
+ @JvmStatic
+ fun getExpressionData(propertyAssignment: Any): ExpressionData {
+ val propertyAssignmentNode: JsonNode = JacksonUtils.jsonNodeFromObject(propertyAssignment)
+ return getExpressionData(propertyAssignmentNode)
+ }
+
+ @JvmStatic
+ fun getExpressionData(propertyAssignmentNode: JsonNode): ExpressionData {
+ logger.trace("Assignment Data/Expression : {}", propertyAssignmentNode)
+ val expressionData = ExpressionData(valueNode = propertyAssignmentNode)
+ if (propertyAssignmentNode is ObjectNode) {
+
+ val commands: Set<String> = propertyAssignmentNode.fieldNames().asSequence().toList().intersect(BluePrintTypes.validCommands())
+ if (commands.isNotEmpty()) {
+ expressionData.isExpression = true
+ expressionData.command = commands.first()
+ expressionData.expressionNode = propertyAssignmentNode
+
+ when (expressionData.command) {
+ org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.EXPRESSION_GET_INPUT -> {
+ expressionData.inputExpression = populateInputExpression(propertyAssignmentNode)
+ }
+ org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.EXPRESSION_GET_ATTRIBUTE -> {
+ expressionData.attributeExpression = populateAttributeExpression(propertyAssignmentNode)
+ }
+ org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.EXPRESSION_GET_PROPERTY -> {
+ expressionData.propertyExpression = populatePropertyExpression(propertyAssignmentNode)
+ }
+ org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.EXPRESSION_GET_OPERATION_OUTPUT -> {
+ expressionData.operationOutputExpression = populateOperationOutputExpression(propertyAssignmentNode)
+ }
+ org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.EXPRESSION_GET_ARTIFACT -> {
+ expressionData.artifactExpression = populateArtifactExpression(propertyAssignmentNode)
+ }
+ }
+ }
+ }
+ return expressionData
+ }
+
+ @JvmStatic
+ fun populateInputExpression(jsonNode: JsonNode): InputExpression {
+ return InputExpression(propertyName = jsonNode.first().textValue())
+ }
+
+ @JvmStatic
+ fun populatePropertyExpression(jsonNode: JsonNode): PropertyExpression {
+ val arrayNode: ArrayNode = jsonNode.first() as ArrayNode
+ check(arrayNode.size() >= 2) {
+ throw BluePrintException(String.format("missing property expression, " +
+ "it should be [ <modelable_entity_name>, <optional_req_or_cap_name>, <property_name>, " +
+ "<nested_property_name_or_index_1>, ..., <nested_property_name_or_index_n> ] , but present {}", jsonNode))
+ }
+ var reqOrCapEntityName: String? = null
+ var propertyName = ""
+ var subProperty: String? = null
+ if (arrayNode.size() == 2) {
+ propertyName = arrayNode[1].textValue()
+ } else if (arrayNode.size() == 3) {
+ reqOrCapEntityName = arrayNode[1].textValue()
+ propertyName = arrayNode[2].textValue()
+ } else if (arrayNode.size() > 3) {
+ reqOrCapEntityName = arrayNode[1].textValue()
+ propertyName = arrayNode[2].textValue()
+ val propertyPaths: List<String> = arrayNode.filterIndexed { index, obj ->
+ index >= 3
+ }.map { it.textValue() }
+ subProperty = propertyPaths.joinToString("/")
+ }
+
+ return PropertyExpression(modelableEntityName = arrayNode[0].asText(),
+ reqOrCapEntityName = reqOrCapEntityName,
+ propertyName = propertyName,
+ subPropertyName = subProperty
+ )
+ }
+
+ @JvmStatic
+ fun populateAttributeExpression(jsonNode: JsonNode): AttributeExpression {
+ val arrayNode: ArrayNode = jsonNode.first() as ArrayNode
+ check(arrayNode.size() >= 3) {
+ throw BluePrintException(String.format("missing attribute expression, " +
+ "it should be [ <modelable_entity_name>, <optional_req_or_cap_name>, <attribute_name>," +
+ " <nested_attribute_name_or_index_1>, ..., <nested_attribute_name_or_index_n> ] , but present {}", jsonNode))
+ }
+
+ var reqOrCapEntityName: String? = null
+ var propertyName: String = ""
+ var subProperty: String? = null
+ if (arrayNode.size() == 2) {
+ propertyName = arrayNode[1].textValue()
+ } else if (arrayNode.size() == 3) {
+ reqOrCapEntityName = arrayNode[1].textValue()
+ propertyName = arrayNode[2].textValue()
+ } else if (arrayNode.size() > 3) {
+ reqOrCapEntityName = arrayNode[1].textValue()
+ propertyName = arrayNode[2].textValue()
+ val propertyPaths: List<String> = arrayNode.filterIndexed { index, obj ->
+ index >= 3
+ }.map { it.textValue() }
+ subProperty = propertyPaths.joinToString("/")
+ }
+ return AttributeExpression(modelableEntityName = arrayNode[0].asText(),
+ reqOrCapEntityName = reqOrCapEntityName,
+ attributeName = propertyName,
+ subAttributeName = subProperty
+ )
+ }
+
+ @JvmStatic
+ fun populateOperationOutputExpression(jsonNode: JsonNode): OperationOutputExpression {
+ val arrayNode: ArrayNode = jsonNode.first() as ArrayNode
+
+ check(arrayNode.size() >= 4) {
+ throw BluePrintException(String.format("missing operation output expression, " +
+ "it should be (<modelable_entity_name>, <interface_name>, <operation_name>, <output_variable_name>) , but present {}", jsonNode))
+ }
+ return OperationOutputExpression(modelableEntityName = arrayNode[0].asText(),
+ interfaceName = arrayNode[1].asText(),
+ operationName = arrayNode[2].asText(),
+ propertyName = arrayNode[3].asText()
+ )
+ }
+
+ @JvmStatic
+ fun populateArtifactExpression(jsonNode: JsonNode): ArtifactExpression {
+ val arrayNode: ArrayNode = jsonNode.first() as ArrayNode
+
+ check(arrayNode.size() >= 2) {
+ throw BluePrintException(String.format("missing artifact expression, " +
+ "it should be [ <modelable_entity_name>, <artifact_name>, <location>, <remove> ] , but present {}", jsonNode))
+ }
+ return ArtifactExpression(modelableEntityName = arrayNode[0].asText(),
+ artifactName = arrayNode[1].asText(),
+ location = arrayNode[2]?.asText() ?: "LOCAL_FILE",
+ remove = arrayNode[3]?.asBoolean() ?: false
+ )
+ }
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintParserService.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintParserService.kt new file mode 100644 index 000000000..3b917202f --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintParserService.kt @@ -0,0 +1,62 @@ +/*
+ * 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.service
+
+import org.onap.ccsdk.apps.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.apps.controllerblueprints.core.utils.ServiceTemplateUtils
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import java.io.File
+import java.io.Serializable
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+interface BluePrintParserService : Serializable {
+ fun readBlueprint(content: String) : BluePrintContext
+ fun readBlueprintFile(fileName: String) : BluePrintContext
+ /**
+ * Read Blueprint from CSAR structure Directory
+ */
+ fun readBlueprintFile(fileName: String, basePath : String) : BluePrintContext
+}
+
+class BluePrintParserDefaultService : BluePrintParserService {
+
+ private val logger: Logger = LoggerFactory.getLogger(this::class.toString())
+
+ var basePath : String = javaClass.classLoader.getResource(".").path
+
+ override fun readBlueprint(content: String): BluePrintContext {
+ return BluePrintContext(ServiceTemplateUtils.getServiceTemplateFromContent(content))
+ }
+
+ override fun readBlueprintFile(fileName: String): BluePrintContext {
+ return readBlueprintFile(fileName, basePath )
+ }
+
+ override fun readBlueprintFile(fileName: String, basePath : String): BluePrintContext {
+ val rootFilePath: String = StringBuilder().append(basePath).append(File.separator).append(fileName).toString()
+ val rootServiceTemplate : ServiceTemplate = ServiceTemplateUtils.getServiceTemplate(rootFilePath)
+ // TODO("Nested Lookup Implementation based on Import files")
+ return BluePrintContext(rootServiceTemplate)
+ }
+
+
+}
diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintRuntimeService.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintRuntimeService.kt new file mode 100644 index 000000000..213f5f401 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintRuntimeService.kt @@ -0,0 +1,274 @@ +/*
+ * 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.service
+
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.node.NullNode
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.apps.controllerblueprints.core.OrchestratorException
+import org.onap.ccsdk.apps.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.apps.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.apps.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class BluePrintRuntimeService(var bluePrintContext: BluePrintContext, var context: MutableMap<String, Any> = hashMapOf()) {
+
+ private val logger: Logger = LoggerFactory.getLogger(this::class.toString())
+
+ /*
+ Get the Node Type Definition for the Node Template, Then iterate Node Type Properties and resolve the expressing
+ */
+ fun resolveNodeTemplateProperties(nodeTemplateName: String): MutableMap<String, Any?> {
+ logger.info("resolveNodeTemplatePropertyValues for node template ({})", nodeTemplateName)
+ val propertyAssignmentValue: MutableMap<String, Any?> = hashMapOf()
+
+ val nodeTemplate: NodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName)
+
+ val propertyAssignments: MutableMap<String, Any?> =
+ nodeTemplate.properties as MutableMap<String, Any?>
+
+ // Get the Node Type Definitions
+ val nodeTypeProperties: MutableMap<String, PropertyDefinition> =
+ bluePrintContext.nodeTypeChainedProperties(nodeTemplate.type)!!
+
+ // Iterate Node Type Properties
+ nodeTypeProperties.forEach { nodeTypePropertyName, nodeTypeProperty ->
+ // Get the Express or Value for the Node Template
+ val propertyAssignment: Any? = propertyAssignments[nodeTypePropertyName]
+
+ var resolvedValue: JsonNode = NullNode.getInstance()
+ if (propertyAssignment != null) {
+ // Resolve the Expressing
+ val propertyAssignmentExpression = PropertyAssignmentService(context, this)
+ resolvedValue = propertyAssignmentExpression.resolveAssignmentExpression(nodeTemplateName, nodeTypePropertyName, propertyAssignment)
+ } else {
+ // Assign default value to the Operation
+ nodeTypeProperty.defaultValue?.let {
+ resolvedValue = JacksonUtils.jsonNodeFromObject(nodeTypeProperty.defaultValue!!)
+ }
+ }
+ // Set for Return of method
+ propertyAssignmentValue[nodeTypePropertyName] = resolvedValue
+ }
+ logger.info("resolved property definition for node template ({}), values ({})", nodeTemplateName, propertyAssignmentValue)
+ return propertyAssignmentValue
+ }
+
+ fun resolveNodeTemplateInterfaceOperationInputs(nodeTemplateName: String,
+ interfaceName: String, operationName: String): MutableMap<String, Any?> {
+ logger.info("nodeTemplateInterfaceOperationInputsResolvedExpression for node template ({}),interface name ({}), " +
+ "operationName({})", nodeTemplateName, interfaceName, operationName)
+
+ val propertyAssignmentValue: MutableMap<String, Any?> = hashMapOf()
+
+ val propertyAssignments: MutableMap<String, Any> =
+ bluePrintContext.nodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName) as? MutableMap<String, Any>
+ ?: throw BluePrintException(String.format("failed to get input definitions for node template (%s), " +
+ "interface name (%s), operationName(%s)", nodeTemplateName, interfaceName, operationName))
+
+ val nodeTypeName = bluePrintContext.nodeTemplateByName(nodeTemplateName).type
+
+ val nodeTypeInterfaceOperationInputs: MutableMap<String, PropertyDefinition> =
+ bluePrintContext.nodeTypeInterfaceOperationInputs(nodeTypeName, interfaceName, operationName)
+ ?: throw BluePrintException(String.format("failed to get input definitions for node type (%s), " +
+ "interface name (%s), operationName(%s)", nodeTypeName, interfaceName, operationName))
+
+ logger.info("input definition for node template ({}), values ({})", nodeTemplateName, propertyAssignments)
+
+ // Iterate Node Type Properties
+ nodeTypeInterfaceOperationInputs.forEach { nodeTypePropertyName, nodeTypeProperty ->
+ // Get the Express or Value for the Node Template
+ val propertyAssignment: Any? = propertyAssignments[nodeTypePropertyName]
+
+ var resolvedValue: JsonNode = NullNode.getInstance()
+ if (propertyAssignment != null) {
+ // Resolve the Expressing
+ val propertyAssignmentExpression = PropertyAssignmentService( context, this)
+ resolvedValue = propertyAssignmentExpression.resolveAssignmentExpression(nodeTemplateName, nodeTypePropertyName, propertyAssignment)
+ } else {
+ // Assign default value to the Operation
+ nodeTypeProperty.defaultValue?.let {
+ resolvedValue = JacksonUtils.jsonNodeFromObject(nodeTypeProperty.defaultValue!!)
+ }
+ }
+ // Set for Return of method
+ propertyAssignmentValue[nodeTypePropertyName] = resolvedValue
+ }
+ logger.info("resolved input assignments for node template ({}), values ({})", nodeTemplateName, propertyAssignmentValue)
+
+ return propertyAssignmentValue
+ }
+
+
+ fun resolveNodeTemplateInterfaceOperationOutputs(nodeTemplateName: String,
+ interfaceName: String, operationName: String, componentContext: MutableMap<String, Any?>): Unit {
+ logger.info("nodeTemplateInterfaceOperationInputsResolvedExpression for node template ({}),interface name ({}), " +
+ "operationName({})", nodeTemplateName, interfaceName, operationName)
+
+ val nodeTypeName = bluePrintContext.nodeTemplateByName(nodeTemplateName).type
+
+ val nodeTypeInterfaceOperationOutputs: MutableMap<String, PropertyDefinition> =
+ bluePrintContext.nodeTypeInterfaceOperationOutputs(nodeTypeName, interfaceName, operationName)
+ ?: throw BluePrintException(String.format("failed to get input definitions for node type (%s), " +
+ "interface name (%s), operationName(%s)", nodeTypeName, interfaceName, operationName))
+
+ // Iterate Node Type Properties
+ nodeTypeInterfaceOperationOutputs.forEach { nodeTypePropertyName, nodeTypeProperty ->
+
+ val operationOutputPropertyName: String = StringBuilder().append(nodeTemplateName)
+ .append(".").append(interfaceName)
+ .append(".").append(operationName)
+ .append(".").append(nodeTypePropertyName).toString()
+ // Get the Value from component context
+ val resolvedValue: JsonNode = componentContext[operationOutputPropertyName] as? JsonNode
+ ?: NullNode.getInstance()
+ // Store operation output values into context
+ setNodeTemplateOperationPropertyValue(nodeTemplateName, interfaceName, operationName, nodeTypePropertyName, resolvedValue)
+ logger.debug("resolved output assignments for node template ({}), property name ({}), value ({})", nodeTemplateName, nodeTypePropertyName, resolvedValue)
+ }
+ }
+
+ fun resolveNodeTemplateArtifact(nodeTemplateName: String,
+ artifactName: String): String {
+ val nodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName)
+
+ val artifactDefinition: ArtifactDefinition = nodeTemplate.artifacts?.get(artifactName)
+ ?: throw OrchestratorException(String.format("failed to get artifat definition {} from the node template"
+ , artifactName))
+ val propertyAssignmentExpression = PropertyAssignmentService( context, this)
+ return propertyAssignmentExpression.artifactContent(artifactDefinition)
+ }
+
+
+ fun setInputValue(propertyName: String, propertyDefinition: PropertyDefinition, value: JsonNode): Unit {
+ val path = StringBuilder(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_INPUTS)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(propertyName).toString()
+ logger.trace("setting input path ({}), values ({})", path, value)
+ context[path] = value
+ }
+
+ fun setWorkflowInputValue(workflowName: String, propertyName: String, value: JsonNode): Unit {
+ val path: String = StringBuilder(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_NODE_WORKFLOWS).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(workflowName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_INPUTS)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_PROPERTIES)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(propertyName).toString()
+ context[path] = value
+ }
+
+ fun setNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String, value: JsonNode): Unit {
+
+ val path: String = StringBuilder(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_NODE_TEMPLATES).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_PROPERTIES)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(propertyName).toString()
+ context[path] = value
+ }
+
+ fun setNodeTemplateOperationPropertyValue(nodeTemplateName: String, interfaceName: String, operationName: String, propertyName: String,
+ value: JsonNode): Unit {
+ val path: String = StringBuilder(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_NODE_TEMPLATES).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_INTERFACES).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(interfaceName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_OPERATIONS).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(operationName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_PROPERTIES)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(propertyName).toString()
+ logger.trace("setting operation property path ({}), values ({})", path, value)
+ context[path] = value
+ }
+
+ fun setNodeTemplateOperationInputValue(nodeTemplateName: String, interfaceName: String, operationName: String, propertyName: String,
+ value: JsonNode): Unit {
+ val path: String = StringBuilder(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_NODE_TEMPLATES).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_INTERFACES).append(interfaceName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_OPERATIONS).append(operationName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_INPUTS)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_PROPERTIES)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(propertyName).toString()
+ context[path] = value
+ }
+
+ fun setNodeTemplateOperationOutputValue(nodeTemplateName: String, interfaceName: String, operationName: String, propertyName: String,
+ value: JsonNode): Unit {
+ val path: String = StringBuilder(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_NODE_TEMPLATES).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_INTERFACES).append(interfaceName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_OPERATIONS).append(operationName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_OUTPUTS)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_PROPERTIES)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(propertyName).toString()
+ context[path] = value
+ }
+
+
+ fun getInputValue(propertyName: String): JsonNode {
+ val path = StringBuilder(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_INPUTS)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(propertyName).toString()
+ return context[path] as? JsonNode ?: NullNode.instance
+ }
+
+ fun getNodeTemplateOperationOutputValue(nodeTemplateName: String, interfaceName: String, operationName: String, propertyName: String): JsonNode {
+ val path: String = StringBuilder(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_NODE_TEMPLATES).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_INTERFACES).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(interfaceName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_OPERATIONS).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(operationName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_PROPERTIES)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(propertyName).toString()
+ return context[path] as JsonNode
+ }
+
+ fun getPropertyValue(nodeTemplateName: String, propertyName: String): JsonNode? {
+ val path: String = StringBuilder(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_NODE_TEMPLATES).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_PROPERTIES)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(propertyName).toString()
+ return context[path] as JsonNode
+ }
+
+ fun getRequirementPropertyValue(nodeTemplateName: String, requirementName: String, propertyName: String): JsonNode? {
+ val path: String = StringBuilder(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_NODE_TEMPLATES).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_REQUIREMENTS).append(requirementName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_PROPERTIES)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(propertyName).toString()
+ return context[path] as JsonNode
+ }
+
+ fun getCapabilityPropertyValue(nodeTemplateName: String, capabilityName: String, propertyName: String): JsonNode? {
+ val path: String = StringBuilder(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_NODE_TEMPLATES).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_CAPABILITIES).append(capabilityName)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_PROPERTIES)
+ .append(org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PATH_DIVIDER).append(propertyName).toString()
+ return context[path] as JsonNode
+ }
+
+ fun assignInputs(jsonNode: JsonNode): Unit {
+ logger.info("assignInputs from input JSON ({})", jsonNode.toString())
+ bluePrintContext.inputs?.forEach { propertyName, property ->
+ val valueNode: JsonNode = jsonNode.at("/" + propertyName) ?: NullNode.getInstance()
+ setInputValue(propertyName, property, valueNode)
+ }
+ }
+
+ fun assignWorkflowInputs(workflowName: String, jsonNode: JsonNode): Unit {
+ logger.info("assign workflow {} input value ({})", workflowName, jsonNode.toString())
+ bluePrintContext.workflowByName(workflowName)?.inputs?.forEach { propertyName, property ->
+ val valueNode: JsonNode = jsonNode.at("/" + propertyName) ?: NullNode.getInstance()
+ setWorkflowInputValue(workflowName, propertyName, valueNode)
+ }
+ }
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintValidatorService.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintValidatorService.kt new file mode 100644 index 000000000..2383a6520 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/BluePrintValidatorService.kt @@ -0,0 +1,353 @@ +/*
+ * 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.service
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.google.common.base.Preconditions
+import org.apache.commons.lang3.StringUtils
+import org.onap.ccsdk.apps.controllerblueprints.core.*
+import org.onap.ccsdk.apps.controllerblueprints.core.data.*
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import java.io.Serializable
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+interface BluePrintValidatorService : Serializable {
+
+ @Throws(BluePrintException::class)
+ fun validateBlueprint(bluePrintContext: BluePrintContext, properties: MutableMap<String, Any>)
+
+ @Throws(BluePrintException::class)
+ fun validateBlueprint(serviceTemplate: ServiceTemplate, properties: MutableMap<String, Any>)
+}
+
+open class BluePrintValidatorDefaultService : BluePrintValidatorService {
+
+ val logger: Logger = LoggerFactory.getLogger(BluePrintValidatorDefaultService::class.toString())
+
+ lateinit var bluePrintContext: BluePrintContext
+ lateinit var serviceTemplate: ServiceTemplate
+ lateinit var properties: MutableMap<String, Any>
+ var message: StringBuilder = StringBuilder()
+ val seperator: String = "/"
+ var paths: MutableList<String> = arrayListOf()
+
+ @Throws(BluePrintException::class)
+ override fun validateBlueprint(bluePrintContext: BluePrintContext, properties: MutableMap<String, Any>) {
+ validateBlueprint(bluePrintContext.serviceTemplate,properties)
+ }
+
+ @Throws(BluePrintException::class)
+ override fun validateBlueprint(serviceTemplate: ServiceTemplate, properties: MutableMap<String, Any>) {
+ this.bluePrintContext = BluePrintContext(serviceTemplate)
+ this.serviceTemplate = serviceTemplate
+ this.properties = properties
+ try {
+ message.appendln("-> Config Blueprint")
+ serviceTemplate.metadata?.let { validateMetadata(serviceTemplate.metadata!!) }
+ serviceTemplate.artifactTypes?.let { validateArtifactTypes(serviceTemplate.artifactTypes!!) }
+ serviceTemplate.dataTypes?.let { validateDataTypes(serviceTemplate.dataTypes!!) }
+ serviceTemplate.nodeTypes?.let { validateNodeTypes(serviceTemplate.nodeTypes!!) }
+ serviceTemplate.topologyTemplate?.let { validateTopologyTemplate(serviceTemplate.topologyTemplate!!) }
+ } catch (e: Exception) {
+ logger.error("validation failed in the path : {}", paths.joinToString(seperator), e)
+ logger.error("validation trace message :{} ", message)
+ throw BluePrintException(e,
+ format("failed to validate blueprint on path ({}) with message {}"
+ , paths.joinToString(seperator), e.message))
+ }
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateMetadata(metaDataMap: MutableMap<String, String>) {
+ paths.add("metadata")
+ Preconditions.checkArgument(StringUtils.isNotBlank(metaDataMap[BluePrintConstants.METADATA_TEMPLATE_NAME]), "failed to get template name metadata")
+ Preconditions.checkArgument(StringUtils.isNotBlank(metaDataMap[BluePrintConstants.METADATA_TEMPLATE_VERSION]), "failed to get template version metadata")
+ Preconditions.checkArgument(StringUtils.isNotBlank(metaDataMap[BluePrintConstants.METADATA_TEMPLATE_TAGS]), "failed to get template tags metadata")
+ Preconditions.checkArgument(StringUtils.isNotBlank(metaDataMap[BluePrintConstants.METADATA_TEMPLATE_AUTHOR]), "failed to get template author metadata")
+ Preconditions.checkArgument(StringUtils.isNotBlank(metaDataMap[BluePrintConstants.METADATA_USER_GROUPS]), "failed to get user groups metadata")
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateArtifactTypes(artifactTypes: MutableMap<String, ArtifactType>) {
+ paths.add("artifact_types")
+ artifactTypes.forEach { artifactName, artifactType ->
+ paths.add(artifactName)
+ message.appendln("--> Artifact Type :" + paths.joinToString(seperator))
+ artifactType.properties?.let { validatePropertyDefinitions(artifactType.properties!!) }
+ paths.removeAt(paths.lastIndex)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateDataTypes(dataTypes: MutableMap<String, DataType>) {
+ paths.add("dataTypes")
+ dataTypes.forEach { dataTypeName, dataType ->
+ paths.add(dataTypeName)
+ message.appendln("--> Data Type :" + paths.joinToString(seperator))
+ dataType.properties?.let { validatePropertyDefinitions(dataType.properties!!) }
+ paths.removeAt(paths.lastIndex)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateNodeTypes(nodeTypes: MutableMap<String, NodeType>) {
+ paths.add("nodeTypes")
+ nodeTypes.forEach { nodeTypeName, nodeType ->
+ // Validate Single Node Type
+ validateNodeType(nodeTypeName,nodeType)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateNodeType(nodeTypeName: String, nodeType: NodeType) {
+ paths.add(nodeTypeName)
+ message.appendln("--> Node Type :" + paths.joinToString(seperator))
+ val derivedFrom: String = nodeType.derivedFrom
+ //Check Derived From
+ checkValidNodeTypesDerivedFrom(derivedFrom)
+
+ nodeType.properties?.let { validatePropertyDefinitions(nodeType.properties!!) }
+ nodeType.interfaces?.let { validateInterfaceDefinitions(nodeType.interfaces!!) }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateTopologyTemplate(topologyTemplate: TopologyTemplate) {
+ paths.add("topology")
+ message.appendln("--> Topology Template")
+ topologyTemplate.inputs?.let { validateInputs(topologyTemplate.inputs!!) }
+ topologyTemplate.nodeTemplates?.let { validateNodeTemplates(topologyTemplate.nodeTemplates!!) }
+ topologyTemplate.workflows?.let { validateWorkFlows(topologyTemplate.workflows!!) }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateInputs(inputs: MutableMap<String, PropertyDefinition>) {
+ paths.add("inputs")
+ message.appendln("---> Input :" + paths.joinToString(seperator))
+ validatePropertyDefinitions(inputs)
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateNodeTemplates(nodeTemplates: MutableMap<String, NodeTemplate>) {
+ paths.add("nodeTemplates")
+ nodeTemplates.forEach { nodeTemplateName, nodeTemplate ->
+ validateNodeTemplate(nodeTemplateName, nodeTemplate)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateNodeTemplate(nodeTemplateName : String, nodeTemplate: NodeTemplate) {
+ paths.add(nodeTemplateName)
+ message.appendln("---> Node Template :" + paths.joinToString(seperator))
+ val type: String = nodeTemplate.type
+
+ val nodeType: NodeType = serviceTemplate.nodeTypes?.get(type)
+ ?: throw BluePrintException(format("Failed to get node type definition for node template : {}", nodeTemplateName))
+
+ nodeTemplate.artifacts?.let { validateArtifactDefinitions(nodeTemplate.artifacts!!) }
+ nodeTemplate.properties?.let { validatePropertyAssignments(nodeType.properties!!, nodeTemplate.properties!!) }
+ nodeTemplate.capabilities?.let { validateCapabilityAssignments(nodeTemplate.capabilities!!) }
+ nodeTemplate.requirements?.let { validateRequirementAssignments(nodeTemplate.requirements!!) }
+ nodeTemplate.interfaces?.let { validateInterfaceAssignments(nodeTemplate.interfaces!!) }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateWorkFlows(workflows: MutableMap<String, Workflow>) {
+ paths.add("workflows")
+ workflows.forEach { workflowName, workflow ->
+
+ // Validate Single workflow
+ validateWorkFlow(workflowName, workflow)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateWorkFlow(workflowName:String, workflow: Workflow) {
+ paths.add(workflowName)
+ message.appendln("---> Workflow :" + paths.joinToString(seperator))
+ // Step Validation Start
+ paths.add("steps")
+ workflow.steps?.forEach { stepName, step ->
+ paths.add(stepName)
+ message.appendln("----> Steps :" + paths.joinToString(seperator))
+ paths.removeAt(paths.lastIndex)
+ }
+ paths.removeAt(paths.lastIndex)
+ // Step Validation Ends
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validatePropertyDefinitions(properties: MutableMap<String, PropertyDefinition>) {
+ paths.add("properties")
+ properties.forEach { propertyName, propertyDefinition ->
+ paths.add(propertyName)
+ val dataType: String = propertyDefinition.type!!
+ if (BluePrintTypes.validPrimitiveTypes().contains(dataType)) {
+ // Do Nothing
+ } else if (BluePrintTypes.validCollectionTypes().contains(dataType)) {
+ val entrySchemaType: String = propertyDefinition.entrySchema?.type
+ ?: throw BluePrintException(format("Entry schema for data type ({}) for the property ({}) not found", dataType, propertyName))
+ checkPrimitiveOrComplex(entrySchemaType, propertyName)
+ } else {
+ checkPropertyDataType(dataType, propertyName)
+ }
+ message.appendln("property " + paths.joinToString(seperator) + " of type " + dataType)
+ paths.removeAt(paths.lastIndex)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validatePropertyAssignments(nodeTypeProperties: MutableMap<String, PropertyDefinition>,
+ properties: MutableMap<String, JsonNode>) {
+ properties.forEach { propertyName, propertyAssignment ->
+ val propertyDefinition: PropertyDefinition = nodeTypeProperties[propertyName]
+ ?: throw BluePrintException(format("failed to get definition for the property ({})", propertyName))
+ // Check and Validate if Expression Node
+ val expressionData = BluePrintExpressionService.getExpressionData(propertyAssignment)
+ if (!expressionData.isExpression) {
+ checkPropertyValue(propertyDefinition, propertyAssignment)
+ }
+ }
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateArtifactDefinitions(artifacts: MutableMap<String, ArtifactDefinition>) {
+ paths.add("artifacts")
+ artifacts.forEach { artifactName, artifactDefinition ->
+ paths.add(artifactName)
+ message.appendln("Validating artifact " + paths.joinToString(seperator))
+ val type: String = artifactDefinition.type
+ ?: throw BluePrintException("type is missing for artifact definition :" + artifactName)
+ // Check Artifact Type
+ checkValidArtifactType(type)
+
+ val file: String = artifactDefinition.file
+ ?: throw BluePrintException(format("file is missing for artifact definition : {}", artifactName))
+
+ paths.removeAt(paths.lastIndex)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateCapabilityAssignments(capabilities: MutableMap<String, CapabilityAssignment>) {
+
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateRequirementAssignments(requirements: MutableMap<String, RequirementAssignment>) {
+
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateInterfaceAssignments(interfaces: MutableMap<String, InterfaceAssignment>) {
+
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateInterfaceDefinitions(interfaces: MutableMap<String, InterfaceDefinition>) {
+ paths.add("interfaces")
+ interfaces.forEach { interfaceName, interfaceDefinition ->
+ paths.add(interfaceName)
+ message.appendln("Validating : " + paths.joinToString(seperator))
+ interfaceDefinition.operations?.let { validateOperationDefinitions(interfaceDefinition.operations!!) }
+ paths.removeAt(paths.lastIndex)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateOperationDefinitions(operations: MutableMap<String, OperationDefinition>) {
+ paths.add("operations")
+ operations.forEach { opertaionName, operationDefinition ->
+ paths.add(opertaionName)
+ message.appendln("Validating : " + paths.joinToString(seperator))
+ operationDefinition.implementation?.let { validateImplementation(operationDefinition.implementation!!) }
+ operationDefinition.inputs?.let { validatePropertyDefinitions(operationDefinition.inputs!!) }
+ operationDefinition.outputs?.let { validatePropertyDefinitions(operationDefinition.outputs!!) }
+ paths.removeAt(paths.lastIndex)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateImplementation(implementation: Implementation) {
+ checkNotEmptyNThrow(implementation.primary)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun checkValidNodeType(nodeType : String) {
+
+ }
+
+ @Throws(BluePrintException::class)
+ open fun checkValidArtifactType(artifactType: String) {
+
+ serviceTemplate.artifactTypes?.containsKey(artifactType)
+ ?: throw BluePrintException(format("Failed to node type definition for artifact definition : {}", artifactType))
+ }
+
+ @Throws(BluePrintException::class)
+ open fun checkValidNodeTypesDerivedFrom(derivedFrom: String) {
+
+ }
+
+ private fun checkPropertyValue(propertyDefinition: PropertyDefinition, jsonNode: JsonNode) {
+ //logger.info("validating path ({}), Property {}, value ({})", paths, propertyDefinition, jsonNode)
+ }
+
+ private fun checkPropertyDataType(dataType: String, propertyName: String): Boolean {
+ if (checkDataType(dataType)) {
+ return true
+ } else {
+ throw BluePrintException(format("Data type ({}) for the property ({}) not found", dataType, propertyName))
+ }
+ }
+
+ private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean {
+ if (BluePrintTypes.validPrimitiveTypes().contains(dataType) || checkDataType(dataType)) {
+ return true
+ } else {
+ throw BluePrintException(format("Data type ({}) for the property ({}) is not valid", dataType))
+ }
+ }
+
+ private fun checkDataType(key: String): Boolean {
+ return serviceTemplate.dataTypes?.containsKey(key) ?: false
+ }
+
+ private fun checkNodeType(key: String): Boolean {
+ return serviceTemplate.nodeTypes?.containsKey(key) ?: false
+ }
+
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/PropertyAssignmentService.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/PropertyAssignmentService.kt new file mode 100644 index 000000000..9389a6f30 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/service/PropertyAssignmentService.kt @@ -0,0 +1,198 @@ +/*
+ * 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.service
+
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.node.NullNode
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.apps.controllerblueprints.core.data.*
+import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
+import org.onap.ccsdk.apps.controllerblueprints.core.utils.ResourceResolverUtils
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class PropertyAssignmentService(var context: MutableMap<String, Any>,
+ var bluePrintRuntimeService: BluePrintRuntimeService) {
+ private val logger: Logger = LoggerFactory.getLogger(this::class.toString())
+
+ private var bluePrintContext: BluePrintContext = bluePrintRuntimeService.bluePrintContext
+
+/*
+
+If Property Assignment is Expression.
+ Get the Expression
+ Recurssely resolve the expression
+ */
+
+ fun resolveAssignmentExpression(nodeTemplateName: String, assignmentName: String,
+ assignment: Any): JsonNode {
+ var valueNode: JsonNode = NullNode.getInstance()
+ logger.trace("Assignment ({})", assignment)
+ val expressionData = BluePrintExpressionService.getExpressionData(assignment)
+
+ if (expressionData.isExpression) {
+ valueNode = resolveExpression(nodeTemplateName, assignmentName, expressionData)
+ } else {
+ valueNode = expressionData.valueNode
+ }
+ return valueNode
+ }
+
+ fun resolveExpression(nodeTemplateName: String, propName: String, expressionData: ExpressionData): JsonNode {
+
+ var valueNode: JsonNode = NullNode.getInstance()
+
+ if(expressionData.isExpression) {
+ val command = expressionData.command!!
+
+ when(command){
+ org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.EXPRESSION_GET_INPUT ->{
+ valueNode = bluePrintRuntimeService.getInputValue(expressionData.inputExpression?.propertyName!!)
+ }
+ org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.EXPRESSION_GET_ATTRIBUTE ->{
+ valueNode = resolveAttributeExpression(nodeTemplateName, expressionData.attributeExpression!!)
+ }
+ org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.EXPRESSION_GET_PROPERTY ->{
+ valueNode = resolvePropertyExpression(nodeTemplateName, expressionData.propertyExpression!!)
+ }
+ org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.EXPRESSION_GET_OPERATION_OUTPUT ->{
+ valueNode = resolveOperationOutputExpression(nodeTemplateName, expressionData.operationOutputExpression!!)
+ }
+ org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.EXPRESSION_GET_ARTIFACT ->{
+ valueNode = resolveArtifactExpression(nodeTemplateName, expressionData.artifactExpression!!)
+ }
+ org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.EXPRESSION_GET_NODE_OF_TYPE ->{
+
+ }
+ else ->{
+ throw BluePrintException(String.format("for property ({}), command ({}) is not supported ", propName, command))
+ }
+ }
+ }
+ return valueNode
+ }
+
+ /*
+ get_property: [ <modelable_entity_name>, <optional_req_or_cap_name>, <property_name>,
+ <nested_property_name_or_index_1>, ..., <nested_property_name_or_index_n> ]
+ */
+ fun resolveAttributeExpression(nodeTemplateName: String, attributeExpression: AttributeExpression): JsonNode {
+ var valueNode: JsonNode = NullNode.getInstance()
+
+ val attributeName = attributeExpression.attributeName
+ val subAttributeName: String? = attributeExpression.subAttributeName
+
+ var attributeNodeTemplateName = nodeTemplateName
+ if (!attributeExpression.modelableEntityName.equals("SELF", true)) {
+ attributeNodeTemplateName = attributeExpression.modelableEntityName
+ }
+
+ val attributeExpression = bluePrintContext.nodeTemplateByName(attributeNodeTemplateName).attributes?.get(attributeName)
+ ?: throw BluePrintException(String.format("failed to get property definitions for node template ({})'s property name ({}) ", nodeTemplateName, attributeName))
+
+ var propertyDefinition: AttributeDefinition = bluePrintContext.nodeTemplateNodeType(attributeNodeTemplateName).attributes?.get(attributeName)!!
+
+ logger.info("template name ({}), property Name ({}) resolved value ({})", attributeNodeTemplateName, attributeName, attributeExpression)
+
+ // Check it it is a nested expression
+ valueNode = resolveAssignmentExpression(attributeNodeTemplateName, attributeName, attributeExpression)
+
+// subPropertyName?.let {
+// valueNode = valueNode.at(JsonPointer.valueOf(subPropertyName))
+// }
+ return valueNode
+ }
+
+ /*
+ get_property: [ <modelable_entity_name>, <optional_req_or_cap_name>, <property_name>,
+ <nested_property_name_or_index_1>, ..., <nested_property_name_or_index_n> ]
+ */
+ fun resolvePropertyExpression(nodeTemplateName: String, propertyExpression: PropertyExpression): JsonNode {
+ var valueNode: JsonNode = NullNode.getInstance()
+
+ val propertyName = propertyExpression.propertyName
+ val subPropertyName: String? = propertyExpression.subPropertyName
+
+ var propertyNodeTemplateName = nodeTemplateName
+ if (!propertyExpression.modelableEntityName.equals("SELF", true)) {
+ propertyNodeTemplateName = propertyExpression.modelableEntityName
+ }
+
+ val propertyExpression = bluePrintContext.nodeTemplateByName(propertyNodeTemplateName).properties?.get(propertyName)
+ ?: throw BluePrintException(String.format("failed to get property definitions for node template ({})'s property name ({}) ", nodeTemplateName, propertyName))
+
+ var propertyDefinition: PropertyDefinition = bluePrintContext.nodeTemplateNodeType(propertyNodeTemplateName).properties?.get(propertyName)!!
+
+ logger.info("template name ({}), property Name ({}) resolved value ({})", propertyNodeTemplateName, propertyName, propertyExpression)
+
+ // Check it it is a nested expression
+ valueNode = resolveAssignmentExpression(propertyNodeTemplateName, propertyName, propertyExpression)
+
+// subPropertyName?.let {
+// valueNode = valueNode.at(JsonPointer.valueOf(subPropertyName))
+// }
+ return valueNode
+ }
+
+ /*
+ get_operation_output: <modelable_entity_name>, <interface_name>, <operation_name>, <output_variable_name>
+ */
+ fun resolveOperationOutputExpression(nodeTemplateName: String, operationOutputExpression: OperationOutputExpression): JsonNode {
+ var outputNodeTemplateName = nodeTemplateName
+ if (!operationOutputExpression.modelableEntityName.equals("SELF", true)) {
+ outputNodeTemplateName = operationOutputExpression.modelableEntityName
+ }
+ return bluePrintRuntimeService.getNodeTemplateOperationOutputValue(outputNodeTemplateName,
+ operationOutputExpression.interfaceName, operationOutputExpression.operationName,
+ operationOutputExpression.propertyName)
+ }
+
+ /*
+ get_artifact: [ <modelable_entity_name>, <artifact_name>, <location>, <remove> ]
+ */
+ fun resolveArtifactExpression(nodeTemplateName: String, artifactExpression: ArtifactExpression): JsonNode {
+
+ var artifactNodeTemplateName = nodeTemplateName
+ if (!artifactExpression.modelableEntityName.equals("SELF", true)) {
+ artifactNodeTemplateName = artifactExpression.modelableEntityName
+ }
+ val artifactDefinition: ArtifactDefinition = bluePrintContext.nodeTemplateByName(artifactNodeTemplateName)
+ .artifacts?.get(artifactExpression.artifactName)
+ ?: throw BluePrintException(String.format("failed to get artifact definitions for node template ({})'s " +
+ "artifact name ({}) ", nodeTemplateName, artifactExpression.artifactName))
+
+ return JacksonUtils.jsonNodeFromObject(artifactContent(artifactDefinition))
+ }
+
+ fun artifactContent(artifactDefinition: ArtifactDefinition): String {
+ val bluePrintBasePath: String = context[org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PROPERTY_BLUEPRINT_BASE_PATH] as? String
+ ?: throw BluePrintException(String.format("failed to get property (%s) from context", org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.PROPERTY_BLUEPRINT_BASE_PATH))
+
+ if (artifactDefinition.repository != null) {
+ TODO()
+ } else if (artifactDefinition.file != null) {
+ return ResourceResolverUtils.getFileContent(artifactDefinition.file!!, bluePrintBasePath)
+ }
+ return ""
+ }
+}
+
diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/BluePrintMetadataUtils.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/BluePrintMetadataUtils.kt new file mode 100644 index 000000000..a9236f693 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/BluePrintMetadataUtils.kt @@ -0,0 +1,95 @@ +/*
+ * 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.utils
+
+
+import org.apache.commons.io.FileUtils
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.apps.controllerblueprints.core.data.ToscaMetaData
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import java.io.File
+import java.nio.charset.Charset
+
+object BluePrintMetadataUtils {
+ private val logger: Logger = LoggerFactory.getLogger(this::class.toString())
+
+ @JvmStatic
+ fun toscaMetaData(basePath: String): ToscaMetaData {
+ val toscaMetaPath = basePath.plus(BluePrintConstants.PATH_DIVIDER).plus("TOSCA-Metadata/TOSCA.meta")
+ return toscaMetaDataFromMetaFile(toscaMetaPath)
+ }
+
+ @JvmStatic
+ fun toscaMetaDataFromMetaFile(metaFilePath: String): ToscaMetaData {
+ val toscaMetaData = ToscaMetaData()
+ val lines: MutableList<String> = FileUtils.readLines(File(metaFilePath), Charset.defaultCharset())
+ lines.forEach { line ->
+ if (line.contains(":")) {
+ val keyValue = line.split(":")
+ if (keyValue.size == 2) {
+ val value: String = keyValue[1].trim()
+ when (keyValue[0]) {
+ "TOSCA-Meta-File-Version" -> toscaMetaData.toscaMetaFileVersion = value
+ "CSAR-Version" -> toscaMetaData.csarVersion = value
+ "Created-By" -> toscaMetaData.createdBy = value
+ "Entry-Definitions" -> toscaMetaData.entityDefinitions = value
+ "Template-Tags" -> toscaMetaData.templateTags = value
+ }
+ }
+ }
+
+ }
+ return toscaMetaData
+ }
+
+ /*
+ fun getBluePrintContext(blueprintBasePath: String): BluePrintContext {
+
+ val metaDataFile = StringBuilder().append(blueprintBasePath).append(File.separator)
+ .append(BluePrintConstants.DEFAULT_TOSCA_METADATA_ENTRY_DEFINITION_FILE).toString()
+
+ val toscaMetaData: ToscaMetaData = BluePrintMetadataUtils.toscaMetaData(metaDataFile)
+
+ logger.info("Processing blueprint base path ({}) and entry definition file ({})", blueprintBasePath, toscaMetaData.entityDefinitions)
+
+ return BluePrintParserFactory.instance(BluePrintConstants.TYPE_DEFAULT)!!
+ .readBlueprintFile(toscaMetaData.entityDefinitions!!, blueprintBasePath)
+ }
+
+ fun getBluePrintRuntime(requestId: String, blueprintBasePath: String): BluePrintRuntimeService {
+
+ val metaDataFile = StringBuilder().append(blueprintBasePath).append(File.separator)
+ .append(BluePrintConstants.DEFAULT_TOSCA_METADATA_ENTRY_DEFINITION_FILE).toString()
+
+ val toscaMetaData: ToscaMetaData = BluePrintMetadataUtils.toscaMetaData(metaDataFile)
+
+ logger.info("Processing blueprint base path ({}) and entry definition file ({})", blueprintBasePath, toscaMetaData.entityDefinitions)
+
+ val bluePrintContext: BluePrintContext = BluePrintParserFactory.instance(BluePrintConstants.TYPE_DEFAULT)!!
+ .readBlueprintFile(toscaMetaData.entityDefinitions!!, blueprintBasePath)
+
+ val context: MutableMap<String, Any> = hashMapOf()
+ context[BluePrintConstants.PROPERTY_BLUEPRINT_BASE_PATH] = blueprintBasePath
+ context[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] = requestId
+
+ val bluePrintRuntimeService: BluePrintRuntimeService = BluePrintRuntimeService(bluePrintContext, context)
+
+ return bluePrintRuntimeService
+ }
+ */
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/BluePrintRuntimeUtils.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/BluePrintRuntimeUtils.kt new file mode 100644 index 000000000..bad9201b7 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/BluePrintRuntimeUtils.kt @@ -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.
+ */
+
+package org.onap.ccsdk.apps.controllerblueprints.core.utils
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.node.NullNode
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintContext
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+object BluePrintRuntimeUtils {
+ private val logger: Logger = LoggerFactory.getLogger(this::class.toString())
+
+ fun assignInputsFromFile(bluePrintContext: BluePrintContext, fileName: String, context: MutableMap<String, Any>) {
+ val jsonNode: JsonNode = JacksonUtils.jsonNodeFromFile(fileName)
+ return assignInputs(bluePrintContext, jsonNode, context)
+ }
+
+ fun assignInputsFromContent(bluePrintContext: BluePrintContext, content: String, context: MutableMap<String, Any>) {
+ val jsonNode: JsonNode = JacksonUtils.jsonNode(content)
+ return assignInputs(bluePrintContext, jsonNode, context)
+ }
+
+ fun assignInputs(bluePrintContext: BluePrintContext, jsonNode: JsonNode, context: MutableMap<String, Any>) {
+ logger.info("assignInputs from input JSON ({})", jsonNode.toString())
+ bluePrintContext.inputs?.forEach { propertyName, property ->
+ val valueNode: JsonNode = jsonNode.at("/".plus(propertyName)) ?: NullNode.getInstance()
+
+ val path = BluePrintConstants.PATH_INPUTS.plus(BluePrintConstants.PATH_DIVIDER).plus(propertyName)
+ logger.trace("setting input path ({}), values ({})", path, valueNode)
+ context[path] = valueNode
+ }
+ }
+
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/JacksonUtils.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/JacksonUtils.kt new file mode 100644 index 000000000..95b2af7b7 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/JacksonUtils.kt @@ -0,0 +1,179 @@ +/*
+ * 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.utils
+
+import com.fasterxml.jackson.annotation.JsonInclude
+import com.fasterxml.jackson.core.type.TypeReference
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.SerializationFeature
+import com.fasterxml.jackson.databind.node.ArrayNode
+import com.fasterxml.jackson.databind.node.NullNode
+import com.fasterxml.jackson.databind.node.ObjectNode
+import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
+import org.apache.commons.io.FileUtils
+import org.apache.commons.io.IOUtils
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.apps.controllerblueprints.core.format
+import org.slf4j.LoggerFactory
+import java.io.File
+import java.nio.charset.Charset
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+object JacksonUtils {
+ private val log = LoggerFactory.getLogger(JacksonUtils::class.java)
+
+ inline fun <reified T : Any> readValue(content: String): T =
+ jacksonObjectMapper().readValue(content, T::class.java)
+
+ @JvmStatic
+ fun <T> readValue(content: String, valueType: Class<T>): T? {
+ return jacksonObjectMapper().readValue(content, valueType)
+ }
+
+ @JvmStatic
+ fun jsonNodeFromObject(from: kotlin.Any): JsonNode = jacksonObjectMapper().convertValue(from, JsonNode::class.java)
+
+ @JvmStatic
+ fun jsonNodeFromClassPathFile(fileName: String): JsonNode {
+ val content: String = IOUtils.toString(JacksonUtils::class.java.classLoader.getResourceAsStream(fileName), Charset.defaultCharset())
+ ?: throw BluePrintException(String.format("Failed to read json file : %s", fileName))
+ return jsonNode(content)
+ }
+
+ @JvmStatic
+ fun jsonNodeFromFile(fileName: String): JsonNode {
+ val content: String = FileUtils.readFileToString(File(fileName), Charset.defaultCharset())
+ ?: throw BluePrintException(format("Failed to read json file : {}", fileName))
+ return jsonNode(content)
+ }
+
+ @JvmStatic
+ fun jsonNode(content: String): JsonNode {
+ return jacksonObjectMapper().readTree(content)
+ }
+
+ @JvmStatic
+ fun getJson(any: kotlin.Any): String {
+ return getJson(any, false)
+ }
+
+ @JvmStatic
+ fun getJson(any: kotlin.Any, pretty: Boolean = false): String {
+ val objectMapper = jacksonObjectMapper()
+ objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
+ if (pretty) {
+ objectMapper.enable(SerializationFeature.INDENT_OUTPUT)
+ }
+ return objectMapper.writeValueAsString(any)
+ }
+
+ @JvmStatic
+ fun <T> getListFromJson(content: String, valueType: Class<T>): List<T>? {
+ val objectMapper = jacksonObjectMapper()
+ val javaType = objectMapper.typeFactory.constructCollectionType(List::class.java, valueType)
+ return objectMapper.readValue<List<T>>(content, javaType)
+ }
+
+ @JvmStatic
+ fun <T> getMapFromJson(content: String, valueType: Class<T>): MutableMap<String, T>? {
+ val objectMapper = jacksonObjectMapper()
+ val typeRef = object : TypeReference<MutableMap<String, T>>() {}
+ return objectMapper.readValue(content, typeRef)
+ }
+
+ @JvmStatic
+ fun populatePrimitiveValues(key: String, value: Any, primitiveType: String, objectNode: ObjectNode) {
+ if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_BOOLEAN == primitiveType) {
+ objectNode.put(key, value as Boolean)
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_INTEGER == primitiveType) {
+ objectNode.put(key, value as Int)
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_FLOAT == primitiveType) {
+ objectNode.put(key, value as Float)
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_TIMESTAMP == primitiveType) {
+ objectNode.put(key, value as String)
+ } else {
+ objectNode.put(key, value as String)
+ }
+ }
+
+ @JvmStatic
+ fun populatePrimitiveValues(value: Any, primitiveType: String, objectNode: ArrayNode) {
+ if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_BOOLEAN == primitiveType) {
+ objectNode.add(value as Boolean)
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_INTEGER == primitiveType) {
+ objectNode.add(value as Int)
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_FLOAT == primitiveType) {
+ objectNode.add(value as Float)
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_TIMESTAMP == primitiveType) {
+ objectNode.add(value as String)
+ } else {
+ objectNode.add(value as String)
+ }
+ }
+
+ @JvmStatic
+ fun populatePrimitiveDefaultValues(key: String, primitiveType: String, objectNode: ObjectNode) {
+ if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_BOOLEAN == primitiveType) {
+ objectNode.put(key, false)
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_INTEGER == primitiveType) {
+ objectNode.put(key, 0)
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_FLOAT == primitiveType) {
+ objectNode.put(key, 0.0)
+ } else {
+ objectNode.put(key, "")
+ }
+ }
+
+ @JvmStatic
+ fun populatePrimitiveDefaultValuesForArrayNode(primitiveType: String, arrayNode: ArrayNode) {
+ if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_BOOLEAN == primitiveType) {
+ arrayNode.add(false)
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_INTEGER == primitiveType) {
+ arrayNode.add(0)
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_FLOAT == primitiveType) {
+ arrayNode.add(0.0)
+ } else {
+ arrayNode.add("")
+ }
+ }
+
+ @JvmStatic
+ fun populateJsonNodeValues(key: String, nodeValue: JsonNode?, type: String, objectNode: ObjectNode) {
+ if (nodeValue == null || nodeValue is NullNode) {
+ objectNode.set(key, nodeValue)
+ } else if (BluePrintTypes.validPrimitiveTypes().contains(type)) {
+ if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_BOOLEAN == type) {
+ objectNode.put(key, nodeValue.asBoolean())
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_INTEGER == type) {
+ objectNode.put(key, nodeValue.asInt())
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_FLOAT == type) {
+ objectNode.put(key, nodeValue.floatValue())
+ } else if (org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants.DATA_TYPE_TIMESTAMP == type) {
+ objectNode.put(key, nodeValue.asText())
+ } else {
+ objectNode.put(key, nodeValue.asText())
+ }
+ } else {
+ objectNode.set(key, nodeValue)
+ }
+ }
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/ResourceResolverUtils.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/ResourceResolverUtils.kt new file mode 100644 index 000000000..a26745564 --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/ResourceResolverUtils.kt @@ -0,0 +1,62 @@ +/*
+ * 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.utils
+
+import org.apache.commons.io.FileUtils
+import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmpty
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import java.io.File
+import java.net.URL
+import java.nio.charset.Charset
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+object ResourceResolverUtils {
+ private val logger: Logger = LoggerFactory.getLogger(this::class.toString())
+
+ @JvmStatic
+ fun getFileContent(filename : String, basePath : String?): String {
+ logger.trace("file ({}), basePath ({}) ", filename, basePath)
+ try{
+ var resolvedFileName : String = filename
+ if(filename.startsWith("http", true)
+ || filename.startsWith("https", true)){
+ val givenUrl : String = URL(filename).toString()
+ val systemUrl : String = File(".").toURI().toURL().toString()
+ logger.trace("givenUrl ({}), systemUrl ({}) ", givenUrl, systemUrl)
+ if(givenUrl.startsWith(systemUrl)){
+
+ }
+ }else{
+ if(!filename.startsWith("/")){
+ if (checkNotEmpty(basePath)) {
+ resolvedFileName = basePath.plus(File.separator).plus(filename)
+ }else{
+ resolvedFileName = javaClass.classLoader.getResource(".").path.plus(filename)
+ }
+ }
+ }
+ return FileUtils.readFileToString(File(resolvedFileName), Charset.defaultCharset())
+ }catch (e : Exception){
+ throw BluePrintException(e, "failed to file (%s), basePath (%s) ", filename, basePath)
+ }
+ }
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/ServiceTemplateUtils.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/ServiceTemplateUtils.kt new file mode 100644 index 000000000..2fcb9b2ae --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/ServiceTemplateUtils.kt @@ -0,0 +1,44 @@ +/*
+ * 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.utils
+
+import org.apache.commons.io.FileUtils
+import org.onap.ccsdk.apps.controllerblueprints.core.data.ServiceTemplate
+import java.io.File
+import java.nio.charset.Charset
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+object ServiceTemplateUtils {
+
+ @JvmStatic
+ fun getServiceTemplate(fileName: String): ServiceTemplate {
+ val content: String = FileUtils.readFileToString(File(fileName), Charset.defaultCharset())
+ return getServiceTemplateFromContent(content)
+ }
+
+
+ @JvmStatic
+ fun getServiceTemplateFromContent(content: String): ServiceTemplate {
+ return JacksonUtils.readValue<ServiceTemplate>(content)
+ }
+
+
+}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/TopologicalSortingUtils.kt b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/TopologicalSortingUtils.kt new file mode 100644 index 000000000..dcafa974c --- /dev/null +++ b/ms/controllerblueprints/modules/core/src/main/kotlin/org/onap/ccsdk/apps/controllerblueprints/core/utils/TopologicalSortingUtils.kt @@ -0,0 +1,131 @@ +/*
+ * 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.utils
+
+import java.util.*
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class TopologicalSortingUtils<V> {
+
+ private val neighbors: MutableMap<V, MutableList<V>> = hashMapOf()
+
+ val isDag: Boolean
+ get() = topSort() != null
+
+ override fun toString(): String {
+ val s = StringBuffer()
+ for (v in neighbors.keys)
+ s.append("\n " + v + " -> " + neighbors[v])
+ return s.toString()
+ }
+
+ fun getNeighbors(): Map<V, List<V>> {
+ return neighbors
+ }
+
+ fun add(vertex: V) {
+ if (neighbors.containsKey(vertex))
+ return
+ neighbors[vertex] = arrayListOf()
+ }
+
+ operator fun contains(vertex: V): Boolean {
+ return neighbors.containsKey(vertex)
+ }
+
+ fun add(from: V, to: V) {
+ this.add(from)
+ this.add(to)
+ neighbors[from]?.add(to)
+ }
+
+ fun remove(from: V, to: V) {
+ if (!(this.contains(from) && this.contains(to)))
+ throw IllegalArgumentException("Nonexistent vertex")
+ neighbors[from]?.remove(to)
+ }
+
+ fun outDegree(): Map<V, Int> {
+ var result: MutableMap<V, Int> = hashMapOf()
+ for (v in neighbors.keys)
+ result[v] = neighbors[v]!!.size
+ return result
+ }
+
+
+ fun inDegree(): MutableMap<V, Int> {
+ val result = HashMap<V, Int>()
+ for (v in neighbors.keys)
+ result[v] = 0 // All in-degrees are 0
+ for (from in neighbors.keys) {
+ for (to in neighbors[from]!!) {
+ result[to] = result[to]!! + 1 // Increment in-degree
+ }
+ }
+ return result
+ }
+
+ fun topSort(): List<V>? {
+ val degree = inDegree()
+ // Determine all vertices with zero in-degree
+ val zeroVerts = Stack<V>() // Stack as good as any here
+ for (v in degree.keys) {
+ if (degree[v] == 0) zeroVerts.push(v)
+ }
+ // Determine the topological order
+ val result = ArrayList<V>()
+ while (!zeroVerts.isEmpty()) {
+ val v = zeroVerts.pop() // Choose a vertex with zero in-degree
+ result.add(v) // Vertex v is next in topol order
+ // "Remove" vertex v by updating its neighbors
+ for (neighbor in neighbors[v]!!) {
+ degree[neighbor] = degree[neighbor]!! - 1
+ // Remember any vertices that now have zero in-degree
+ if (degree[neighbor] == 0) zeroVerts.push(neighbor)
+ }
+ }
+ // Check that we have used the entire graph (if not, there was a cycle)
+ return if (result.size != neighbors.size) null else result
+ }
+
+
+ fun bfsDistance(start: V): Map<*, *> {
+ var distance: MutableMap<V, Int> = hashMapOf()
+ // Initially, all distance are infinity, except start node
+ for (v in neighbors.keys)
+ distance[v] = -1
+ distance[start] = 0
+ // Process nodes in queue order
+ val queue = LinkedList<V>()
+ queue.offer(start) // Place start node in queue
+ while (!queue.isEmpty()) {
+ val v = queue.remove()
+ val vDist = distance[v]!!
+ // Update neighbors
+ for (neighbor in neighbors[v]!!) {
+ if (distance[neighbor] != null) continue // Ignore if already done
+ distance[neighbor] = vDist + 1
+ queue.offer(neighbor)
+ }
+ }
+ return distance
+ }
+}
\ No newline at end of file |