From bc19e1f0dd1d9ccf17ad390690de3b8ae2f76ddc Mon Sep 17 00:00:00 2001 From: "Singal, Kapil (ks220y)" Date: Tue, 4 Sep 2018 22:29:37 -0400 Subject: SDNC Blueprints Processor Model Utils Creating SDN Controller Blueprints Processor Model Utils Change-Id: I5cfef9c2ebbc8bcdcca783fc8827520e0fc341ba Issue-ID: CCSDK-517 Signed-off-by: Singal, Kapil (ks220y) --- .../ccsdk/config/model/utils/ExpressionUtils.java | 191 +++++++++ .../ccsdk/config/model/utils/JsonParserUtils.java | 59 +++ .../onap/ccsdk/config/model/utils/JsonUtils.java | 109 ++++++ .../config/model/utils/NodePropertyUtils.java | 187 +++++++++ .../config/model/utils/PrepareContextUtils.java | 63 +++ .../model/utils/ResourceAssignmentUtils.java | 302 +++++++++++++++ .../model/utils/ResourceDictionaryUtils.java | 119 ++++++ .../config/model/utils/ServiceTemplateUtils.java | 277 +++++++++++++ .../model/utils/TopologicalSortingUtils.java | 188 +++++++++ .../config/model/utils/TransformationUtils.java | 429 +++++++++++++++++++++ 10 files changed, 1924 insertions(+) create mode 100644 blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ExpressionUtils.java create mode 100644 blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/JsonParserUtils.java create mode 100644 blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/JsonUtils.java create mode 100644 blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/NodePropertyUtils.java create mode 100644 blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/PrepareContextUtils.java create mode 100644 blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ResourceAssignmentUtils.java create mode 100644 blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ResourceDictionaryUtils.java create mode 100644 blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ServiceTemplateUtils.java create mode 100644 blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/TopologicalSortingUtils.java create mode 100644 blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/TransformationUtils.java (limited to 'blueprints-processor/plugin/model-provider') diff --git a/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ExpressionUtils.java b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ExpressionUtils.java new file mode 100644 index 000000000..06b4c3005 --- /dev/null +++ b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ExpressionUtils.java @@ -0,0 +1,191 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.config.model.utils; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.config.model.ConfigModelConstant; +import org.onap.ccsdk.config.model.data.PropertyDefinition; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public class ExpressionUtils { + private static EELFLogger logger = EELFManager.getInstance().getLogger(ExpressionUtils.class); + + private final SvcLogicContext context; + private final Map inParams; + + public ExpressionUtils(final SvcLogicContext context, final Map inParams) { + this.context = context; + this.inParams = inParams; + } + + public void populatePropertAssignmentsWithPrefix(String prefix, Map typeProperties, + Map templateProperties) throws IOException { + if (typeProperties != null && templateProperties != null) { + ObjectMapper mapper = new ObjectMapper(); + String templatejsonContent = mapper.writeValueAsString(templateProperties); + logger.debug("Expression inputs ({}).", templatejsonContent); + + JsonNode rootArray = mapper.readTree(templatejsonContent); + processJsonExpression(rootArray); + if (rootArray != null) { + Map prefixParams = new HashMap<>(); + TransformationUtils.convertJson2RootProperties(prefixParams, rootArray); + logger.info("Resolved inputs ({}).", rootArray); + prefixParams.forEach((key, value) -> { + this.inParams.put(prefix + "." + key, value); + }); + } + } + } + + public void populatePropertAssignments(Map typeProperties, + Map templateProperties) throws IOException { + if (typeProperties != null && templateProperties != null) { + ObjectMapper mapper = new ObjectMapper(); + String templatejsonContent = mapper.writeValueAsString(templateProperties); + logger.info("Expression inputs ({}).", templatejsonContent); + + JsonNode rootArray = mapper.readTree(templatejsonContent); + processJsonExpression(rootArray); + TransformationUtils.convertJson2RootProperties(this.inParams, rootArray); + logger.info("Resolved inputs ({}).", rootArray); + + } + } + + public void populateOutPropertAssignments(Map typeProperties, + Map templateProperties) throws IOException { + if (typeProperties != null && templateProperties != null) { + ObjectMapper mapper = new ObjectMapper(); + String templatejsonContent = mapper.writeValueAsString(templateProperties); + logger.info("Expression outputs ({}).", templatejsonContent); + + JsonNode rootArray = mapper.readTree(templatejsonContent); + processJsonExpression(rootArray); + logger.info("Resolved outputs ({}).", rootArray); + } + } + + public void processJsonExpression(JsonNode rootArray) throws IOException { + if (rootArray != null) { + Iterator> fields = rootArray.fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + processJsonNode(rootArray, entry.getKey(), entry.getValue()); + } + } + } + + private void processJsonNode(JsonNode parentNode, String nodeName, JsonNode node) throws IOException { + if (node == null) { + // Do Nothing + } else if (node.isArray()) { + String[] a = new String[node.size()]; + + for (int i = 0; i < a.length; i++) { + processJsonNode(null, null, node.get(i)); + } + } else if (node.isObject()) { + + Iterator> fields = node.fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + processJsonNode(node, entry.getKey(), entry.getValue()); + } + } else if (node.isTextual()) { + boolean expression = checkExpressionContent(node.asText()); + if (expression) { + processExpressionContent(parentNode, nodeName, node); + } + } + } + + private boolean checkExpressionContent(String content) { + return (StringUtils.isNotBlank(content) && (content.contains(ConfigModelConstant.EXPRESSION_GET_INPUT) + || content.contains(ConfigModelConstant.EXPRESSION_GET_ATTRIBUTE) + || content.contains(ConfigModelConstant.EXPRESSION_SET_VALUE))); + } + + @SuppressWarnings("squid:S3776") + private void processExpressionContent(JsonNode parentNode, String nodeName, JsonNode node) throws IOException { + + if (node != null && StringUtils.isNotBlank(node.asText())) { + String content = node.asText(); + ObjectMapper mapper = new ObjectMapper(); + Map expressionMap = mapper.readValue(content, Map.class); + boolean isExpressionNode = false; + + if (expressionMap != null) { + String expressionValue = null; + String expressionKey = null; + + if (expressionMap.containsKey(ConfigModelConstant.EXPRESSION_GET_INPUT)) { + isExpressionNode = true; + expressionKey = expressionMap.get(ConfigModelConstant.EXPRESSION_GET_INPUT); + expressionValue = resolveGetInputExpression(expressionKey, context); + if (expressionValue == null) { + expressionValue = resolveGetInputExpression("inputs." + expressionKey + ".default", context); + } + } else if (expressionMap.containsKey(ConfigModelConstant.EXPRESSION_GET_ATTRIBUTE)) { + isExpressionNode = true; + expressionValue = + context.getAttribute(expressionMap.get(ConfigModelConstant.EXPRESSION_GET_ATTRIBUTE)); + } else if (expressionMap.containsKey(ConfigModelConstant.EXPRESSION_SET_VALUE)) { + isExpressionNode = true; + expressionKey = expressionMap.get(ConfigModelConstant.EXPRESSION_SET_VALUE); + expressionValue = context.getAttribute(expressionKey); + + if (StringUtils.isNotBlank(expressionKey)) { + context.setAttribute(expressionKey, expressionValue); + } + } + + if (isExpressionNode && expressionValue == null) { + ((ObjectNode) parentNode).put(nodeName, ""); + } + if (StringUtils.isNotBlank(expressionValue)) { + if (expressionValue.trim().startsWith("[") || expressionValue.trim().startsWith("{")) { + JsonNode valueNode = mapper.readTree(expressionValue); + ((ObjectNode) parentNode).put(nodeName, valueNode); + } else { + ((ObjectNode) parentNode).put(nodeName, expressionValue); + } + } + logger.debug("expression ({}), expression key ({}), expression Value ({})", expressionMap, + expressionKey, expressionValue); + } + } + } + + private String resolveGetInputExpression(String key, final SvcLogicContext context) { + if (StringUtils.isNotBlank(key) && context != null) { + return context.getAttribute(key); + } + return null; + } + +} diff --git a/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/JsonParserUtils.java b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/JsonParserUtils.java new file mode 100644 index 000000000..3555ee739 --- /dev/null +++ b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/JsonParserUtils.java @@ -0,0 +1,59 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.config.model.utils; + +import static com.jayway.jsonpath.JsonPath.using; +import java.util.List; +import com.fasterxml.jackson.databind.JsonNode; +import com.jayway.jsonpath.Configuration; +import com.jayway.jsonpath.Option; +import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider; +import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; + +@SuppressWarnings("squid:S1118") +public class JsonParserUtils { + + public static final Configuration JACKSON_JSON_NODE_CONFIGURATION = Configuration.builder() + .mappingProvider(new JacksonMappingProvider()).jsonProvider(new JacksonJsonNodeJsonProvider()).build(); + + public static final Configuration PATH_CONFIGURATION = Configuration.builder().options(Option.AS_PATH_LIST).build(); + + public static List paths(String jsonContent, String expression) { + return using(PATH_CONFIGURATION).parse(jsonContent).read(expression); + } + + public static List paths(JsonNode jsonNode, String expression) { + return paths(jsonNode.toString(), expression); + } + + public static JsonNode parse(String jsonContent, String expression) { + return using(JACKSON_JSON_NODE_CONFIGURATION).parse(jsonContent).read(expression); + } + + public static JsonNode parse(JsonNode jsonNode, String expression) { + return parse(jsonNode.toString(), expression); + } + + public static JsonNode parseNSet(String jsonContent, String expression, JsonNode value) { + return using(JACKSON_JSON_NODE_CONFIGURATION).parse(jsonContent).set(expression, value).json(); + } + + public static JsonNode parseNSet(JsonNode jsonNode, String expression, JsonNode valueNode) { + return parseNSet(jsonNode.toString(), expression, valueNode); + } +} diff --git a/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/JsonUtils.java b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/JsonUtils.java new file mode 100644 index 000000000..5bc663234 --- /dev/null +++ b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/JsonUtils.java @@ -0,0 +1,109 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.config.model.utils; + +import org.onap.ccsdk.config.model.ValidTypes; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +/** + * JsonUtils.java Purpose: Provide Configuration Generator JsonUtils Information + * + * @version 1.0 + */ +public class JsonUtils { + + private JsonUtils() { + + } + + public static void populatePrimitiveValues(String key, Object value, String primitiveType, ObjectNode objectNode) { + if (ValidTypes.DATA_TYPE_BOOLEAN.equals(primitiveType)) { + objectNode.put(key, (Boolean) value); + } else if (ValidTypes.DATA_TYPE_INTEGER.equals(primitiveType)) { + objectNode.put(key, (Integer) value); + } else if (ValidTypes.DATA_TYPE_FLOAT.equals(primitiveType)) { + objectNode.put(key, (Float) value); + } else if (ValidTypes.DATA_TYPE_TIMESTAMP.equals(primitiveType)) { + objectNode.put(key, (String) value); + } else { + objectNode.put(key, (String) value); + } + } + + public static void populatePrimitiveValues(Object value, String primitiveType, ArrayNode objectNode) { + if (ValidTypes.DATA_TYPE_BOOLEAN.equals(primitiveType)) { + objectNode.add((Boolean) value); + } else if (ValidTypes.DATA_TYPE_INTEGER.equals(primitiveType)) { + objectNode.add((Integer) value); + } else if (ValidTypes.DATA_TYPE_FLOAT.equals(primitiveType)) { + objectNode.add((Float) value); + } else if (ValidTypes.DATA_TYPE_TIMESTAMP.equals(primitiveType)) { + objectNode.add((String) value); + } else { + objectNode.add((String) value); + } + } + + public static void populatePrimitiveDefaultValues(String key, String primitiveType, ObjectNode objectNode) { + if (ValidTypes.DATA_TYPE_BOOLEAN.equals(primitiveType)) { + objectNode.put(key, false); + } else if (ValidTypes.DATA_TYPE_INTEGER.equals(primitiveType)) { + objectNode.put(key, 0); + } else if (ValidTypes.DATA_TYPE_FLOAT.equals(primitiveType)) { + objectNode.put(key, 0.0); + } else { + objectNode.put(key, ""); + } + } + + public static void populatePrimitiveDefaultValuesForArrayNode(String primitiveType, ArrayNode arrayNode) { + if (ValidTypes.DATA_TYPE_BOOLEAN.equals(primitiveType)) { + arrayNode.add(false); + } else if (ValidTypes.DATA_TYPE_INTEGER.equals(primitiveType)) { + arrayNode.add(0); + } else if (ValidTypes.DATA_TYPE_FLOAT.equals(primitiveType)) { + arrayNode.add(0.0); + } else { + arrayNode.add(""); + } + } + + public static void populateJsonNodeValues(String key, JsonNode nodeValue, String type, ObjectNode objectNode) { + if (nodeValue == null || nodeValue instanceof NullNode) { + objectNode.put(key, nodeValue); + } else if (ValidTypes.getPrimitivePropertType().contains(type)) { + if (ValidTypes.DATA_TYPE_BOOLEAN.equals(type)) { + objectNode.put(key, nodeValue.asBoolean()); + } else if (ValidTypes.DATA_TYPE_INTEGER.equals(type)) { + objectNode.put(key, nodeValue.asInt()); + } else if (ValidTypes.DATA_TYPE_FLOAT.equals(type)) { + objectNode.put(key, nodeValue.floatValue()); + } else if (ValidTypes.DATA_TYPE_TIMESTAMP.equals(type)) { + objectNode.put(key, nodeValue.asText()); + } else { + objectNode.put(key, nodeValue.asText()); + } + } else { + objectNode.set(key, nodeValue); + } + } + +} diff --git a/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/NodePropertyUtils.java b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/NodePropertyUtils.java new file mode 100644 index 000000000..59da39bb5 --- /dev/null +++ b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/NodePropertyUtils.java @@ -0,0 +1,187 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.config.model.utils; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.config.model.ConfigModelConstant; +import org.onap.ccsdk.config.model.data.CapabilityAssignment; +import org.onap.ccsdk.config.model.data.CapabilityDefinition; +import org.onap.ccsdk.config.model.data.InterfaceAssignment; +import org.onap.ccsdk.config.model.data.InterfaceDefinition; +import org.onap.ccsdk.config.model.data.NodeTemplate; +import org.onap.ccsdk.config.model.data.NodeType; +import org.onap.ccsdk.config.model.data.OperationAssignment; +import org.onap.ccsdk.config.model.data.OperationDefinition; +import org.onap.ccsdk.config.model.data.PropertyDefinition; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class NodePropertyUtils { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(NodePropertyUtils.class); + private final SvcLogicContext context; + private final Map inParams; + private ExpressionUtils jsonExpressionUtils; + + public NodePropertyUtils(final SvcLogicContext context, final Map inParams) { + this.context = context; + this.inParams = inParams; + jsonExpressionUtils = new ExpressionUtils(this.context, this.inParams); + } + + @SuppressWarnings("squid:S3776") + public SvcLogicContext assignInParamsFromModel(NodeType nodetype, NodeTemplate nodeTemplate) throws IOException { + if (nodeTemplate != null) { + Map inputs = null; + // Populate the Type inputs + Map nodeTypeinputs = new HashMap<>(); + for (Map.Entry nodeTypeInterface : nodetype.getInterfaces().entrySet()) { + if (nodeTypeInterface != null && nodeTypeInterface.getValue() != null) { + for (Map.Entry nodeTypeOperation : nodeTypeInterface.getValue() + .getOperations().entrySet()) { + nodeTypeinputs = nodeTypeOperation.getValue().getInputs(); + logger.trace("Populated node type input ({}).", nodeTypeinputs); + } + } + } + + if (!nodeTypeinputs.isEmpty()) { + // Populate the Template inputs + for (Map.Entry nodeTemplateInterface : nodeTemplate.getInterfaces() + .entrySet()) { + if (nodeTemplateInterface != null && nodeTemplateInterface.getValue() != null) { + this.inParams.put(ConfigModelConstant.PROPERTY_CURRENT_INTERFACE, + nodeTemplateInterface.getKey()); + for (Map.Entry nodeTemplateOperation : nodeTemplateInterface + .getValue().getOperations().entrySet()) { + if (nodeTemplateOperation != null) { + this.inParams.put(ConfigModelConstant.PROPERTY_CURRENT_OPERATION, + nodeTemplateOperation.getKey()); + if (StringUtils.isNotBlank(nodeTemplateOperation.getValue().getImplementation())) { + this.inParams.put(ConfigModelConstant.PROPERTY_CURRENT_IMPLEMENTATION, + nodeTemplateOperation.getValue().getImplementation()); + } + inputs = nodeTemplateOperation.getValue().getInputs(); + logger.trace("Populated node template input({}).", inputs); + // Assign Default Values & Types + jsonExpressionUtils.populatePropertAssignments(nodeTypeinputs, inputs); + } + } + } + } + } + + if (nodeTemplate.getRequirements() != null && !nodeTemplate.getRequirements().isEmpty()) { + assignInParamsFromRequirementModel(nodeTemplate, context, inParams); + } + } + return context; + } + + @SuppressWarnings("squid:S3776") + public SvcLogicContext assignOutParamsFromModel(NodeType nodetype, NodeTemplate nodeTemplate) throws IOException { + + if (nodeTemplate != null) { + Map outputs = null; + // Populate the Type Outputs + Map nodeTypeOutputs = new HashMap<>(); + + for (Map.Entry nodeTypeInterface : nodetype.getInterfaces().entrySet()) { + if (nodeTypeInterface != null && nodeTypeInterface.getValue() != null) { + for (Map.Entry nodeTypeOperation : nodeTypeInterface.getValue() + .getOperations().entrySet()) { + nodeTypeOutputs = nodeTypeOperation.getValue().getOutputs(); + logger.info("Populated node type output ({}).", nodeTypeOutputs); + } + } + } + + if (!nodeTypeOutputs.isEmpty()) { + // Populate the Template Outputs + for (Map.Entry nodeTemplateInterface : nodeTemplate.getInterfaces() + .entrySet()) { + if (nodeTemplateInterface != null && nodeTemplateInterface.getValue() != null) { + for (Map.Entry nodeTemplateOperation : nodeTemplateInterface + .getValue().getOperations().entrySet()) { + outputs = nodeTemplateOperation.getValue().getOutputs(); + logger.info("Populated node template output ({}).", outputs); + // Assign Default Values & Types + jsonExpressionUtils.populateOutPropertAssignments(nodeTypeOutputs, outputs); + // TO DO + } + } + } + } + } + return context; + } + + @SuppressWarnings({"squid:S3776", "squid:S00112"}) + public SvcLogicContext assignInParamsFromRequirementModel(NodeTemplate nodeTemplate, final SvcLogicContext context, + final Map inParams) { + if (nodeTemplate != null && nodeTemplate.getRequirements() != null && context != null && inParams != null) { + nodeTemplate.getRequirements().forEach((requrementKey, requirement) -> { + if (requirement != null && StringUtils.isNotBlank(requirement.getNode()) + && StringUtils.isNotBlank(requirement.getCapability())) { + String requirementNodeTemplateContent = context + .getAttribute(ConfigModelConstant.PROPERTY_NODE_TEMPLATES_DOT + requirement.getNode()); + logger.info("Processing requirement node ({}) template content ({}) ", requirement.getNode(), + requirementNodeTemplateContent); + NodeTemplate requirementNodeTemplate = + TransformationUtils.readValue(requirementNodeTemplateContent, NodeTemplate.class); + if (requirementNodeTemplate != null && requirementNodeTemplate.getCapabilities() != null) { + String nodeTypeContent = context.getAttribute( + ConfigModelConstant.PROPERTY_NODE_TYPES_DOT + requirementNodeTemplate.getType()); + NodeType nodeType = TransformationUtils.readValue(nodeTypeContent, NodeType.class); + if (nodeType != null && nodeType.getCapabilities() != null + && nodeType.getCapabilities().containsKey(requirement.getCapability())) { + CapabilityDefinition capabilityDefinition = + nodeType.getCapabilities().get(requirement.getCapability()); + if (capabilityDefinition != null) { + CapabilityAssignment capabilityAssignment = + requirementNodeTemplate.getCapabilities().get(requirement.getCapability()); + try { + assignInParamsFromCapabilityModel(requrementKey, capabilityDefinition, + capabilityAssignment, context); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + } + } + }); + } + return context; + } + + public SvcLogicContext assignInParamsFromCapabilityModel(String requirementName, + CapabilityDefinition capabilityDefinition, CapabilityAssignment capabilityAssignment, + final SvcLogicContext context) throws IOException { + if (capabilityAssignment != null && capabilityAssignment.getProperties() != null) { + jsonExpressionUtils.populatePropertAssignmentsWithPrefix(requirementName, + capabilityDefinition.getProperties(), capabilityAssignment.getProperties()); + } + return context; + } + +} diff --git a/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/PrepareContextUtils.java b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/PrepareContextUtils.java new file mode 100644 index 000000000..ed215d2ad --- /dev/null +++ b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/PrepareContextUtils.java @@ -0,0 +1,63 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.config.model.utils; + +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.config.model.ConfigModelConstant; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class PrepareContextUtils { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(PrepareContextUtils.class); + + public Map prepareContext(Map context, String input, String serviceTemplateContent) + throws Exception { + if (StringUtils.isNotBlank(serviceTemplateContent)) { + + if (context == null) { + context = new HashMap<>(); + } + if (StringUtils.isNotBlank(input)) { + TransformationUtils.convertJson2RootProperties(context, input); + } + + String recipeName = context.get(ConfigModelConstant.PROPERTY_ACTION_NAME); + if (StringUtils.isNotBlank(recipeName)) { + String recipeInputName = + recipeName.replace(ConfigModelConstant.PROPERTY_RECIPE, ConfigModelConstant.PROPERTY_REQUEST); + String recipeInput = context.get(recipeInputName); + if (StringUtils.isNotBlank(recipeInput)) { + // Un necessary to hold the Recipe Request, It is already in input + context.remove(recipeInputName); + context.remove(ConfigModelConstant.PROPERTY_PAYLOAD); + TransformationUtils.convertJson2RootProperties(context, recipeInput); + logger.info("Converted recipe ({}) request inputs to context.", recipeName); + } + } + + ServiceTemplateUtils serviceTemplateUtils = new ServiceTemplateUtils(); + serviceTemplateUtils.convertServiceTemplate2Properties(serviceTemplateContent, context); + } + return context; + + } + +} diff --git a/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ResourceAssignmentUtils.java b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ResourceAssignmentUtils.java new file mode 100644 index 000000000..3cdf95c86 --- /dev/null +++ b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ResourceAssignmentUtils.java @@ -0,0 +1,302 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.config.model.utils; + +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.config.model.ConfigModelConstant; +import org.onap.ccsdk.config.model.ConfigModelException; +import org.onap.ccsdk.config.model.ValidTypes; +import org.onap.ccsdk.config.model.data.ResourceAssignment; +import org.onap.ccsdk.config.model.data.dict.ResourceDefinition; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.base.Preconditions; + +public class ResourceAssignmentUtils { + + private ResourceAssignmentUtils() { + + } + + private static EELFLogger logger = EELFManager.getInstance().getLogger(ResourceAssignmentUtils.class); + + public static String getArtifactNodeContent(String nodeTemplateName, Map context) { + Preconditions.checkArgument(StringUtils.isNotBlank(nodeTemplateName), + "getArtifactNodeContent missing template name"); + return (String) context.get(ConfigModelConstant.PROPERTY_NODE_TEMPLATES_DOT + nodeTemplateName + ".content"); + } + + public static List getArtifactNodeMapping(String nodeTemplateName, + Map context) { + Preconditions.checkArgument(StringUtils.isNotBlank(nodeTemplateName), + "getArtifactNodeMapping missing template name"); + List resourceAssignments = null; + String resourceMappingContent = + (String) context.get(ConfigModelConstant.PROPERTY_NODE_TEMPLATES_DOT + nodeTemplateName + ".mapping"); + if (StringUtils.isNotBlank(resourceMappingContent)) { + resourceAssignments = TransformationUtils.getListfromJson(resourceMappingContent, ResourceAssignment.class); + + } else { + logger.warn("missing mapping content for node template ({})", nodeTemplateName); + } + return resourceAssignments; + } + + // Not used Any whre + public static synchronized void cleanContextTemplateNDictionaryKeys(Map componentContext) { + String recipeName = (String) componentContext.get(ConfigModelConstant.PROPERTY_ACTION_NAME); + Set removeSet = new HashSet<>(); + componentContext.forEach((key, value) -> { + if (StringUtils.isNotBlank(key) + && (key.startsWith(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".") + || key.startsWith(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + recipeName + "."))) { + removeSet.add(key); + } + }); + componentContext.keySet().removeAll(removeSet); + } + + public static synchronized Object getDictionaryKeyValue(Map componentContext, + ResourceAssignment resourceMapping) { + Object value = null; + if (resourceMapping != null && componentContext != null) { + String recipeName = (String) componentContext.get(ConfigModelConstant.PROPERTY_ACTION_NAME); + String dictionaryKeyName = resourceMapping.getDictionaryName(); + value = componentContext + .get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + "." + dictionaryKeyName); + } + return value; + } + + public static synchronized Object getDictionaryKeyValue(Map componentContext, + ResourceDefinition resourceDictionary) { + Object value = null; + if (resourceDictionary != null && componentContext != null) { + String recipeName = (String) componentContext.get(ConfigModelConstant.PROPERTY_ACTION_NAME); + String dictionaryKeyName = resourceDictionary.getName(); + value = componentContext + .get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + "." + dictionaryKeyName); + } + return value; + } + + public static synchronized Object getTemplateKeyValue(Map componentContext, + ResourceAssignment resourceMapping) { + Object value = null; + if (resourceMapping != null && componentContext != null) { + String recipeName = (String) componentContext.get(ConfigModelConstant.PROPERTY_ACTION_NAME); + String templateKeyName = resourceMapping.getName(); + value = componentContext + .get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + recipeName + "." + templateKeyName); + } + return value; + } + + public static synchronized void setResourceDataValue(Map componentContext, + ResourceAssignment resourceAssignment, Object value) throws ConfigModelException { + + if (resourceAssignment != null && StringUtils.isNotBlank(resourceAssignment.getName()) + && resourceAssignment.getProperty() != null) { + + String recipeName = (String) componentContext.get(ConfigModelConstant.PROPERTY_ACTION_NAME); + String templateKeyName = resourceAssignment.getName(); + String dictionaryKeyName = resourceAssignment.getDictionaryName(); + + if (StringUtils.isBlank(dictionaryKeyName)) { + resourceAssignment.setDictionaryName(templateKeyName); + dictionaryKeyName = templateKeyName; + logger.warn("Missing dictionary key, setting with template key ({}) as dictionary key ({})", + templateKeyName, dictionaryKeyName); + } + String type = resourceAssignment.getProperty().getType(); + try { + if (StringUtils.isNotBlank(type)) { + Object convertedValue = convertResourceValue(type, value); + + componentContext.put( + ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + "." + dictionaryKeyName, + convertedValue); + componentContext.put( + ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + recipeName + "." + templateKeyName, + convertedValue); + + logger.trace("Setting Resource Value ({}) for Resource Name ({}) of type ({}) ", convertedValue, + dictionaryKeyName, type); + + resourceAssignment.getProperty().setValue(convertedValue); + resourceAssignment.setUpdatedDate(new Date()); + resourceAssignment.setUpdatedBy(ConfigModelConstant.USER_SYSTEM); + resourceAssignment.setStatus(ConfigModelConstant.STATUS_SUCCESS); + } + } catch (Exception e) { + throw new ConfigModelException(String.format( + "Failed in setting value for template key (%s) and dictionary key (%s) of type (%s) with error message (%s)", + templateKeyName, dictionaryKeyName, type, e.getMessage())); + } + } else { + throw new ConfigModelException( + String.format("Failed in setting resource value for resource mapping (%s)", resourceAssignment)); + } + } + + private static Object convertResourceValue(String type, Object value) { + Object convertedValue = null; + + if (value == null || value instanceof NullNode) { + logger.info("Returning {} value from convertResourceValue", value); + return null; + } + + if (ValidTypes.getPrimitivePropertType().contains(type)) { + convertedValue = convertPrimitiveResourceValue(type, value); + } else { + // Case where Resource is non-primitive type + if (value instanceof JsonNode || value instanceof ObjectNode || value instanceof ArrayNode) { + convertedValue = value; + } else if (value instanceof String) { + convertedValue = TransformationUtils.getJsonNodeForString((String) value); + } else { + convertedValue = TransformationUtils.getJsonNodeForObject(value); + } + } + return convertedValue; + } + + @SuppressWarnings("squid:S3776") + private static Object convertPrimitiveResourceValue(String type, Object value) { + Object convertedValue = value; + + if (value instanceof ArrayNode) { + if (ValidTypes.DATA_TYPE_BOOLEAN.equalsIgnoreCase(type)) { + convertedValue = ((ArrayNode) value).asBoolean(); + } else if (ValidTypes.DATA_TYPE_INTEGER.equalsIgnoreCase(type)) { + convertedValue = ((ArrayNode) value).asInt(); + } else if (ValidTypes.DATA_TYPE_FLOAT.equalsIgnoreCase(type)) { + convertedValue = Float.valueOf(((ArrayNode) value).toString()); + } else { + convertedValue = ((ArrayNode) value).toString(); + } + } else if (value instanceof JsonNode) { + if (ValidTypes.DATA_TYPE_BOOLEAN.equalsIgnoreCase(type)) { + convertedValue = ((JsonNode) value).asBoolean(); + } else if (ValidTypes.DATA_TYPE_INTEGER.equalsIgnoreCase(type)) { + convertedValue = ((JsonNode) value).asInt(); + } else if (ValidTypes.DATA_TYPE_FLOAT.equalsIgnoreCase(type)) { + convertedValue = Float.valueOf(((JsonNode) value).asText()); + } else { + convertedValue = ((JsonNode) value).asText(); + } + } else if (value instanceof String) { + if (ValidTypes.DATA_TYPE_BOOLEAN.equalsIgnoreCase(type)) { + convertedValue = Boolean.valueOf((String) value); + } else if (ValidTypes.DATA_TYPE_INTEGER.equalsIgnoreCase(type)) { + convertedValue = Integer.valueOf((String) value); + } else if (ValidTypes.DATA_TYPE_FLOAT.equalsIgnoreCase(type)) { + convertedValue = Float.valueOf((String) value); + } + } + logger.info("Returning value ({}) from convertPrimitiveResourceValue", convertedValue); + return convertedValue; + } + + @SuppressWarnings("squid:S1172") + public static synchronized void setFailedResourceDataValue(Map componentContext, + ResourceAssignment resourceAssignment, String message) { + setFailedResourceDataValue(resourceAssignment, message); + } + + public static synchronized void setFailedResourceDataValue(ResourceAssignment resourceAssignment, String message) { + if (resourceAssignment != null && StringUtils.isNotBlank(resourceAssignment.getName()) + && resourceAssignment.getProperty() != null) { + resourceAssignment.setUpdatedDate(new Date()); + resourceAssignment.setStatus(ConfigModelConstant.STATUS_FAILURE); + resourceAssignment.setUpdatedBy(ConfigModelConstant.USER_SYSTEM); + resourceAssignment.setMessage(message); + } + } + + public static synchronized void assertTemplateKeyValueNotNull(Map componentContext, + ResourceAssignment resourceAssignment) throws ConfigModelException { + if (resourceAssignment != null && resourceAssignment.getProperty() != null + && BooleanUtils.isTrue(resourceAssignment.getProperty().getRequired()) + && getTemplateKeyValue(componentContext, resourceAssignment) == null) { + logger.error("failed to populate mandatory resource mapping ({})", resourceAssignment); + throw new ConfigModelException( + String.format("failed to populate mandatory resource mapping (%s)", resourceAssignment)); + } + } + + @SuppressWarnings({"squid:S3776", "squid:S1141"}) + public static synchronized String generateResourceDataForAssignments(List assignments) + throws ConfigModelException { + String result = "{}"; + try { + ObjectMapper mapper = new ObjectMapper(); + JsonNode root = mapper.readTree(result); + for (ResourceAssignment resourceMapping : assignments) { + if (resourceMapping != null && resourceMapping.getName() != null + && resourceMapping.getProperty() != null) { + + String type = resourceMapping.getProperty().getType(); + Object value = resourceMapping.getProperty().getValue(); + logger.info("Generating Resource name ({}), type ({}), value ({})", resourceMapping.getName(), type, + value); + if (value == null) { + ((ObjectNode) root).set(resourceMapping.getName(), null); + } else if (value instanceof JsonNode) { + ((ObjectNode) root).put(resourceMapping.getName(), (JsonNode) value); + } else if (ValidTypes.DATA_TYPE_STRING.equalsIgnoreCase(type)) { + ((ObjectNode) root).put(resourceMapping.getName(), (String) value); + } else if (ValidTypes.DATA_TYPE_BOOLEAN.equalsIgnoreCase(type)) { + ((ObjectNode) root).put(resourceMapping.getName(), (Boolean) value); + } else if (ValidTypes.DATA_TYPE_INTEGER.equalsIgnoreCase(type)) { + ((ObjectNode) root).put(resourceMapping.getName(), (Integer) value); + } else if (ValidTypes.DATA_TYPE_FLOAT.equalsIgnoreCase(type)) { + ((ObjectNode) root).put(resourceMapping.getName(), (Float) value); + } else if (ValidTypes.DATA_TYPE_TIMESTAMP.equalsIgnoreCase(type)) { + ((ObjectNode) root).put(resourceMapping.getName(), (String) value); + } else { + JsonNode jsonNode = TransformationUtils.getJsonNodeForObject(value); + if (jsonNode != null) { + ((ObjectNode) root).put(resourceMapping.getName(), jsonNode); + } else { + ((ObjectNode) root).set(resourceMapping.getName(), null); + } + } + } + } + result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root); + logger.info("Generated Resource Param Data ({})", result); + } catch (Exception e) { + throw new ConfigModelException(e.getMessage(), e); + } + return result; + } + +} diff --git a/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ResourceDictionaryUtils.java b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ResourceDictionaryUtils.java new file mode 100644 index 000000000..fccf86534 --- /dev/null +++ b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ResourceDictionaryUtils.java @@ -0,0 +1,119 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.config.model.utils; + +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.config.model.ConfigModelConstant; +import org.onap.ccsdk.config.model.data.PropertyDefinition; +import org.onap.ccsdk.config.model.data.ResourceAssignment; +import org.onap.ccsdk.config.model.data.dict.ResourceDefinition; +import org.onap.ccsdk.config.model.data.dict.SourcesDefinition; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** + * ResourceDictionaryUtils.java Purpose to provide ResourceDictionaryUtils + * + * @version 1.0 + */ +public class ResourceDictionaryUtils { + + private ResourceDictionaryUtils() { + // Do nothing + } + + private static EELFLogger logger = EELFManager.getInstance().getLogger(ResourceDictionaryUtils.class); + + /** + * This Method is to assign the source name to the Dictionary Definition Check to see if the source + * definition is not present then assign, if more than one source then assign only one source. + * + * @param resourceAssignment + * @param resourceDefinition + */ + @SuppressWarnings("squid:S3776") + public static void populateSourceMapping(ResourceAssignment resourceAssignment, + ResourceDefinition resourceDefinition) { + + if (resourceAssignment != null && resourceDefinition != null + && StringUtils.isBlank(resourceAssignment.getDictionarySource())) { + + setProperty(resourceAssignment, resourceDefinition); + Map sourcesDefinition = resourceDefinition.getSources(); + + if (sourcesDefinition != null && MapUtils.isNotEmpty(sourcesDefinition) && sourcesDefinition.size() == 1) { + if (sourcesDefinition.get("input") != null) { + resourceAssignment.setDictionarySource(ConfigModelConstant.SOURCE_INPUT); + } else if (sourcesDefinition.get("default") != null) { + resourceAssignment.setDictionarySource(ConfigModelConstant.SOURCE_DEFAULT); + } else if (sourcesDefinition.get("db") != null) { + resourceAssignment.setDictionarySource(ConfigModelConstant.SOURCE_DB); + if (resolve(() -> sourcesDefinition.get("db").getProperties().getDependencies()).isPresent() + && CollectionUtils + .isNotEmpty(sourcesDefinition.get("db").getProperties().getDependencies())) { + resourceAssignment + .setDependencies(sourcesDefinition.get("db").getProperties().getDependencies()); + } + } else if (sourcesDefinition.get("mdsal") != null) { + resourceAssignment.setDictionarySource(ConfigModelConstant.SOURCE_MDSAL); + if (resolve(() -> sourcesDefinition.get("mdsal").getProperties().getDependencies()).isPresent() + && CollectionUtils + .isNotEmpty(sourcesDefinition.get("mdsal").getProperties().getDependencies())) { + resourceAssignment + .setDependencies(sourcesDefinition.get("mdsal").getProperties().getDependencies()); + } + } + logger.info("automapped resourceAssignment : {}", resourceAssignment); + } + } + } + + public static Optional resolve(Supplier resolver) { + try { + T result = resolver.get(); + return Optional.ofNullable(result); + } catch (NullPointerException e) { + return Optional.empty(); + } + } + + /** + * Overriding ResourceAssignment Properties with properties defined in Dictionary + */ + private static void setProperty(ResourceAssignment resourceAssignment, ResourceDefinition resourceDefinition) { + if (StringUtils.isNotBlank(resourceDefinition.getProperty().getType())) { + PropertyDefinition property = resourceAssignment.getProperty(); + if (property == null) { + property = new PropertyDefinition(); + } + if (resourceDefinition.getProperty() != null) { + property.setType(resourceDefinition.getProperty().getType()); + if (resourceDefinition.getProperty().getEntrySchema() != null) { + property.setEntrySchema(resourceDefinition.getProperty().getEntrySchema()); + } + resourceAssignment.setProperty(property); + } + } + } + +} diff --git a/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ServiceTemplateUtils.java b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ServiceTemplateUtils.java new file mode 100644 index 000000000..c60d624c1 --- /dev/null +++ b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/ServiceTemplateUtils.java @@ -0,0 +1,277 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.config.model.utils; + +import java.util.Map; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.config.model.ConfigModelConstant; +import org.onap.ccsdk.config.model.data.InterfaceAssignment; +import org.onap.ccsdk.config.model.data.InterfaceDefinition; +import org.onap.ccsdk.config.model.data.NodeTemplate; +import org.onap.ccsdk.config.model.data.NodeType; +import org.onap.ccsdk.config.model.data.OperationAssignment; +import org.onap.ccsdk.config.model.data.OperationDefinition; +import org.onap.ccsdk.config.model.data.ServiceTemplate; +import org.onap.ccsdk.config.model.data.TopologyTemplate; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ServiceTemplateUtils { + private static EELFLogger logger = EELFManager.getInstance().getLogger(ServiceTemplateUtils.class); + + public Map convertServiceTemplate2Properties(String serviceTemplateContent, + final Map context) { + if (StringUtils.isNotBlank(serviceTemplateContent)) { + ServiceTemplate serviceTemplate = + TransformationUtils.readValue(serviceTemplateContent, ServiceTemplate.class); + convertServiceTemplate2Properties(serviceTemplate, context); + } + return context; + } + + public Map convertServiceTemplate2Properties(ServiceTemplate serviceTemplate, + final Map context) { + if (serviceTemplate != null) { + convertServiceTemplateMetadata2Properties(serviceTemplate, context); + convertServiceTemplateInputs2Properties(serviceTemplate, context); + convertDataTypes2Properties(serviceTemplate, context); + convertNode2Properties(serviceTemplate, context); + } + return context; + } + + public Map convertServiceTemplateMetadata2Properties(ServiceTemplate serviceTemplate, + final Map context) { + + if (serviceTemplate != null && serviceTemplate.getMetadata() != null) { + serviceTemplate.getMetadata().forEach((metaDataKey, metadata) -> { + context.put(metaDataKey, metadata); + }); + } + return context; + } + + public Map convertServiceTemplateInputs2Properties(ServiceTemplate serviceTemplate, + final Map context) { + + if (serviceTemplate != null && serviceTemplate.getTopologyTemplate() != null + && serviceTemplate.getTopologyTemplate().getInputs() != null) { + + serviceTemplate.getTopologyTemplate().getInputs().forEach((paramKey, parameterDefinition) -> { + if (parameterDefinition != null) { + context.put(ConfigModelConstant.PROPERTY_INPUTS_DOT + paramKey + ".type", + parameterDefinition.getType()); + if (parameterDefinition.getRequired()) { + context.put(ConfigModelConstant.PROPERTY_INPUTS_DOT + paramKey + ".required", + String.valueOf(parameterDefinition.getRequired())); + } + if (parameterDefinition.getDefaultValue() != null) { + context.put(ConfigModelConstant.PROPERTY_INPUTS_DOT + paramKey + ".default", + String.valueOf(parameterDefinition.getDefaultValue())); + } + } + }); + } + return context; + } + + public Map convertDataTypes2Properties(ServiceTemplate serviceTemplate, + final Map context) { + if (serviceTemplate != null && serviceTemplate.getDataTypes() != null) { + serviceTemplate.getDataTypes().forEach((dataTypeKey, dataType) -> { + logger.trace("Populating Data Type Key : ({})", dataTypeKey); + String dataTypeContent = TransformationUtils.getJson(dataType); + context.put("data_types." + dataTypeKey, dataTypeContent); + }); + } + return context; + } + + public Map convertNode2Properties(ServiceTemplate serviceTemplate, + final Map context) { + + if (serviceTemplate != null && serviceTemplate.getNodeTypes() != null + && serviceTemplate.getTopologyTemplate() != null + && serviceTemplate.getTopologyTemplate().getNodeTemplates() != null) { + + serviceTemplate.getTopologyTemplate().getNodeTemplates().forEach((nodeTemplateKey, nodeTemplate) -> { + if (nodeTemplate != null && StringUtils.isNotBlank(nodeTemplate.getType())) { + String nodeTypeKey = nodeTemplate.getType(); + logger.trace("Populating Node Type Key : ({}) for Node Template : ({})", nodeTypeKey, + nodeTemplateKey); + String nodeTemplateContent = TransformationUtils.getJson(nodeTemplate); + context.put("node_templates." + nodeTemplateKey, nodeTemplateContent); + if (serviceTemplate.getNodeTypes().containsKey(nodeTypeKey)) { + NodeType nodeType = serviceTemplate.getNodeTypes().get(nodeTypeKey); + String nodeTypeContent = TransformationUtils.getJson(nodeType); + context.put("node_types." + nodeTypeKey, nodeTypeContent); + String nodeDerivedFrom = nodeType.getDerivedFrom(); + if (ConfigModelConstant.MODEL_TYPE_NODE_DG.equalsIgnoreCase(nodeDerivedFrom)) { + populateDGNodeProperties(nodeTemplateKey, nodeTemplate, context, nodeDerivedFrom); + } + } + // Populate the Artifact Definitions + populateNodeTemplateArtifacts(nodeTemplateKey, nodeTemplate, context); + } + }); + } + return context; + } + + @SuppressWarnings("squid:S1172") + public Map populateVnfNodeProperties(String nodeTemplateKey, NodeTemplate nodeTemplate, + final Map context, String nodeDerivedFrom) { + if (nodeTemplate != null && nodeTemplate.getCapabilities() != null) { + nodeTemplate.getCapabilities().forEach((capabilityKey, capability) -> { + capability.getProperties().forEach((propertyKey, property) -> { + context.put(nodeTemplateKey + "." + capabilityKey + "." + propertyKey, String.valueOf(property)); + }); + }); + } + + return context; + } + + public Map populateNodeTemplateArtifacts(String nodeTemplateKey, NodeTemplate nodeTemplate, + final Map context) { + if (MapUtils.isNotEmpty(nodeTemplate.getArtifacts())) { + nodeTemplate.getArtifacts().forEach((artifactName, artifact) -> { + if (StringUtils.isNotBlank(artifactName) && artifact != null) { + logger.trace("Populating Node Template Artifacts ({}) for Node Template ({})", artifactName, + nodeTemplateKey); + String fileKeyName = ConfigModelConstant.PROPERTY_NODE_TEMPLATES_DOT + nodeTemplateKey + "." + + ConfigModelConstant.PROPERTY_ARTIFACTS_DOT + artifactName + ".file"; + String deployKeyName = ConfigModelConstant.PROPERTY_NODE_TEMPLATES_DOT + nodeTemplateKey + "." + + ConfigModelConstant.PROPERTY_ARTIFACTS_DOT + artifactName + ".deploy_path"; + String contentKeyName = ConfigModelConstant.PROPERTY_NODE_TEMPLATES_DOT + nodeTemplateKey + "." + + ConfigModelConstant.PROPERTY_ARTIFACTS_DOT + artifactName + ".content"; + context.put(fileKeyName, artifact.getFile()); + context.put(deployKeyName, artifact.getDeployPath()); + context.put(contentKeyName, artifact.getContent()); + } + }); + } + return context; + } + + public Map populateDGNodeProperties(String nodeTemplateKey, NodeTemplate nodeTemplate, + final Map context, String nodeDerivedFrom) { + if (nodeTemplate != null && nodeTemplate.getInterfaces() != null) { + + if (nodeTemplate.getProperties() != null) { + nodeTemplate.getProperties().forEach((propKey, propValue) -> { + if (propKey != null && propValue != null) { + context.put("dg." + nodeTemplateKey + "." + propKey, String.valueOf(propValue)); + } + }); + } + + nodeTemplate.getInterfaces().forEach((interfaceKey, interfaceDefinition) -> { + + interfaceDefinition.getOperations().forEach((operationKey, operation) -> { + if (ConfigModelConstant.MODEL_TYPE_NODE_DG.equalsIgnoreCase(nodeDerivedFrom)) { + context.put("dg." + nodeTemplateKey + ".module", interfaceKey); + context.put("dg." + nodeTemplateKey + ".flow", operationKey); + } + }); + }); + } + return context; + } + + public SvcLogicContext getInterfaceOpertationDefinition(ServiceTemplate serviceTemplate, + final SvcLogicContext context) { + + if (serviceTemplate != null && serviceTemplate.getNodeTypes() != null + && serviceTemplate.getTopologyTemplate() != null + && serviceTemplate.getTopologyTemplate().getNodeTemplates() != null) { + + TopologyTemplate topologyTemplates = serviceTemplate.getTopologyTemplate(); + // Copy Definition to Template + copyNodeType2Template(serviceTemplate.getNodeTypes(), topologyTemplates.getNodeTemplates()); + + topologyTemplates.getNodeTemplates().forEach((templateKey, nodeTemplate) -> { + + if (StringUtils.isNotBlank(templateKey) && nodeTemplate != null + && nodeTemplate.getInterfaces() != null) { + + nodeTemplate.getInterfaces().forEach((interfaceKey, interfaceDefinition) -> { + if (StringUtils.isNotBlank(interfaceKey) && interfaceDefinition != null) { + interfaceDefinition.getOperations().forEach((operationKey, operation) -> { + String definitionKey = interfaceKey + "." + operationKey; + String definitionContent = TransformationUtils.getJson(operation); + context.setAttribute(definitionKey, definitionContent); + // Set the Operation & Method Params + }); + } + }); + } + }); + } + return context; + } + + public void copyNodeType2Template(Map nodeTypes, Map nodeTemplates) { + if (nodeTypes != null && nodeTemplates != null) { + + nodeTemplates.forEach((templateKey, nodeTemplate) -> { + if (StringUtils.isNotBlank(templateKey) && nodeTemplate != null) { + String type = nodeTemplate.getType(); + // Check the Node Template Type is Present + if (StringUtils.isNotBlank(type) && nodeTypes.containsKey(type)) { + NodeType nodeType = nodeTypes.get(type); + logger.trace("Checking Node Type Content : ({})", TransformationUtils.getJson(nodeType)); + copyNodeTypeInterface2Template(nodeType.getInterfaces(), nodeTemplate.getInterfaces()); + } + } + }); + } + } + + public void copyNodeTypeInterface2Template(Map nodeTypeInterfaces, + Map nodeTemplateInterfaces) { + if (nodeTypeInterfaces != null && nodeTemplateInterfaces != null) { + + nodeTemplateInterfaces.forEach((interfaceKey, nodeTemplateinterface) -> { + InterfaceDefinition nodeTypeInterface = nodeTypeInterfaces.get(interfaceKey); + logger.trace("Checking Interface Type Content : ({})", TransformationUtils.getJson(nodeTypeInterface)); + if (nodeTypeInterface != null && nodeTemplateinterface != null) { + copyNodeTypeOperation2Template(nodeTypeInterface.getOperations(), + nodeTemplateinterface.getOperations()); + } + }); + } + } + + public void copyNodeTypeOperation2Template(Map nodeTypeOperations, + Map nodeTemplateOperations) { + if (nodeTypeOperations != null && nodeTemplateOperations != null) { + + nodeTemplateOperations.forEach((operationKey, nodeTemplateOperation) -> { + OperationDefinition nodeTypeInterfaceOperation = nodeTypeOperations.get(operationKey); + if (nodeTypeInterfaceOperation != null && nodeTemplateOperation != null) { + logger.info("Checking Operation Type Content : " + operationKey + " : " + + TransformationUtils.getJson(nodeTypeInterfaceOperation)); + } + }); + } + } + +} diff --git a/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/TopologicalSortingUtils.java b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/TopologicalSortingUtils.java new file mode 100644 index 000000000..8aa4a454a --- /dev/null +++ b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/TopologicalSortingUtils.java @@ -0,0 +1,188 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.config.model.utils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Stack; + +public class TopologicalSortingUtils { + + /** + * The implementation here is basically an adjacency list, but instead of an array of lists, a Map + * is used to map each vertex to its list of adjacent vertices. + */ + private Map> neighbors = new HashMap<>(); + + /** + * String representation of graph. + */ + @Override + public String toString() { + StringBuilder s = new StringBuilder(); + neighbors.forEach((v, vs) -> s.append("\n " + v + " -> " + vs)); + return s.toString(); + } + + public Map> getNeighbors() { + return neighbors; + } + + /** + * Add a vertex to the graph. Nothing happens if vertex is already in graph. + */ + public void add(V vertex) { + if (neighbors.containsKey(vertex)) + return; + neighbors.put(vertex, new ArrayList()); + } + + /** + * True iff graph contains vertex. + */ + public boolean contains(V vertex) { + return neighbors.containsKey(vertex); + } + + /** + * Add an edge to the graph; if either vertex does not exist, it's added. This implementation allows + * the creation of multi-edges and self-loops. + */ + public void add(V from, V to) { + this.add(from); + this.add(to); + neighbors.get(from).add(to); + } + + /** + * Remove an edge from the graph. Nothing happens if no such edge. + * + * @throws IllegalArgumentException if either vertex doesn't exist. + */ + public void remove(V from, V to) { + if (!(this.contains(from) && this.contains(to))) + throw new IllegalArgumentException("Nonexistent vertex"); + neighbors.get(from).remove(to); + } + + /** + * Report (as a Map) the out-degree of each vertex. + */ + public Map outDegree() { + Map result = new HashMap<>(); + neighbors.forEach((v, vs) -> result.put(v, vs.size())); + return result; + } + + /** + * Report (as a Map) the in-degree of each vertex. + */ + public Map inDegree() { + Map result = new HashMap<>(); + for (V v : neighbors.keySet()) + result.put(v, 0); // All in-degrees are 0 + + neighbors.forEach((from, vs) -> vs.forEach(to -> result.put(to, result.get(to) + 1) // Increment in-degree + )); + + return result; + } + + /** + * Report (as a List) the topological sort of the vertices; null for no such sort. + */ + @SuppressWarnings({"squid:S1149", "squid:S1168"}) + public List topSort() { + Map degree = inDegree(); + // Determine all vertices with zero in-degree + Stack zeroVerts = new Stack<>(); // Stack as good as any here + + degree.forEach((v, vs) -> { + if (vs == 0) + zeroVerts.push(v); + }); + + // Determine the topological order + List result = new ArrayList<>(); + while (!zeroVerts.isEmpty()) { + V 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 (V neighbor : neighbors.get(v)) { + degree.put(neighbor, degree.get(neighbor) - 1); + // Remember any vertices that now have zero in-degree + if (degree.get(neighbor) == 0) + zeroVerts.push(neighbor); + } + } + // Check that we have used the entire graph (if not, there was a cycle) + if (result.size() != neighbors.size()) + return null; + return result; + } + + /** + * True iff graph is a dag (directed acyclic graph). + */ + public boolean isDag() { + return topSort() != null; + } + + /** + * Report (as a Map) the bfs distance to each vertex from the start vertex. The distance is an + * Integer; the value null is used to represent infinity (implying that the corresponding node + * cannot be reached). + */ + public Map bfsDistance(V start) { + Map distance = new HashMap<>(); + // Initially, all distance are infinity, except start node + for (V v : neighbors.keySet()) + distance.put(v, null); + distance.put(start, 0); + // Process nodes in queue order + Queue queue = new LinkedList<>(); + queue.offer(start); // Place start node in queue + while (!queue.isEmpty()) { + V v = queue.remove(); + int vDist = distance.get(v); + // Update neighbors + for (V neighbor : neighbors.get(v)) { + if (distance.get(neighbor) != null) + continue; // Ignore if already done + distance.put(neighbor, vDist + 1); + queue.offer(neighbor); + } + } + return distance; + } + + /** + * Main program (for testing). public static void main (String[] args) { // Create a Graph with + * Integer nodes TopologicalSortingUtils graph = new TopologicalSortingUtils(); + * graph.add("bundle-id", "bundle-mac"); graph.add("bundle-id", "bundle-ip"); + * graph.add("bundle-mac", "bundle-ip"); graph.add("bundle-ip", "bundle-mac"); + * System.out.println("The current graph: " + graph); System.out.println("In-degrees: " + + * graph.inDegree()); System.out.println("Out-degrees: " + graph.outDegree()); System.out.println("A + * topological sort of the vertices: " + graph.topSort()); System.out.println("The graph " + + * (graph.isDag()?"is":"is not") + " a dag"); } + */ +} diff --git a/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/TransformationUtils.java b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/TransformationUtils.java new file mode 100644 index 000000000..311be9db7 --- /dev/null +++ b/blueprints-processor/plugin/model-provider/src/main/java/org/onap/ccsdk/config/model/utils/TransformationUtils.java @@ -0,0 +1,429 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.config.model.utils; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.TreeMap; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.type.CollectionType; +import com.fasterxml.jackson.module.jsonSchema.JsonSchema; +import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator; + +/** + * TransformationUtils.java Purpose: Provide Configuration Generator TransformationUtils Information + * + * @version 1.0 + */ +public class TransformationUtils { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(TransformationUtils.class); + + private TransformationUtils() { + + } + + /** + * This is a getJson method + * + * @param configparameters + * @return String + */ + public static String getJson(Map configparameters) { + String jsonContent = null; + try { + ObjectMapper mapper = new ObjectMapper(); + jsonContent = mapper.writeValueAsString(configparameters); + } catch (JsonProcessingException e) { + logger.warn(e.getMessage()); + } + return jsonContent; + } + + /** + * This is a getJsonNode method + * + * @param configparameters + * @return String + */ + public static JsonNode getJsonNode(Map configparameters) { + JsonNode jsonContent = null; + try { + ObjectMapper mapper = new ObjectMapper(); + jsonContent = mapper.valueToTree(configparameters); + } catch (Exception e) { + logger.warn(e.getMessage()); + } + return jsonContent; + } + + /** + * This is a getJson method + * + * @param instance + * @param pretty + * @return Map + */ + public static String getJson(Object instance, boolean pretty) { + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + if (pretty) { + mapper.enable(SerializationFeature.INDENT_OUTPUT); + } + return mapper.writeValueAsString(instance); + } catch (JsonProcessingException e) { + logger.warn(e.getMessage()); + } + return null; + } + + /** + * This is a getJson method + * + * @param instance + * @return String + */ + public static String getJson(Object instance) { + return getJson(instance, false); + } + + /** + * This is a getJsonNodeForobject method + * + * @param instance + * @return JsonNode + */ + public static JsonNode getJsonNodeForObject(Object instance) { + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + return mapper.convertValue(instance, JsonNode.class); + } catch (Exception e) { + logger.warn(e.getMessage()); + } + return null; + } + + /** + * This is a getJsonNodeForString method + * + * @param content + * @return JsonNode + */ + public static JsonNode getJsonNodeForString(String content) { + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + return mapper.readTree(content); + } catch (Exception e) { + logger.warn(e.getMessage()); + } + return null; + } + + /** + * This is a getMapfromJson method + * + * @param content + * @return Map + */ + public static Map getMapfromJson(String content) { + try { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(content, new TypeReference>() {}); + } catch (Exception e) { + logger.warn("failed in getMapfromJson for the content ({}) with error message ({}).", content, + e.getMessage()); + } + return null; + } + + /** + * This is a getMapfromJson method + * + * @param content + * @return Map + */ + public static Map getMapfromJsonString(String content) { + try { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(content, new TypeReference>() {}); + } catch (Exception e) { + logger.warn("failed in getMapfromJson for the content ({}) with error message ({}).", content, + e.getMessage()); + } + return null; + } + + /** + * This is a getListfromJson method + * + * @param content + * @return Map + */ + @SuppressWarnings("squid:S1168") + public static List getListfromJson(String content, Class valueType) { + try { + ObjectMapper mapper = new ObjectMapper(); + CollectionType javaType = mapper.getTypeFactory().constructCollectionType(List.class, valueType); + return mapper.readValue(content, javaType); + } catch (Exception e) { + logger.warn("failed in getListfromJson for the content ({}) with error message ({}).", content, + e.getMessage()); + } + return null; + } + + /** + * This is a getJsonSchema method + * + * @param valueType + * @return String + */ + public static String getJsonSchema(Class clazz) { + try { + ObjectMapper mapper = new ObjectMapper(); + JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper); + JsonSchema schema = schemaGen.generateSchema(clazz); + return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema); + + } catch (Exception e) { + logger.warn("failed in getJsonSchema with error message ({}).", e.getMessage()); + } + return null; + } + + /** + * This is a readValue method + * + * @param content + * @param valueType + * @return + */ + + public static T readValue(String content, Class valueType) { + try { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(content, valueType); + } catch (Exception e) { + logger.warn("failed in readValue for the content ({}) with error message ({}).", content, e.getMessage()); + } + return null; + } + + /** + * @param node + * @param valueType + * @param + * @return + */ + public static T treeToValue(JsonNode node, Class valueType) { + try { + ObjectMapper mapper = new ObjectMapper(); + return mapper.treeToValue(node, valueType); + } catch (Exception e) { + logger.warn("failed in readValue for the content ({}) with error message ({}).", node, e.getMessage()); + } + return null; + } + + /** + * @param node + * @param valueType + * @param + * @return List + */ + public static List treeToListValue(JsonNode node, Class valueType) { + List resultList = new ArrayList<>(); + if (node instanceof ArrayNode) { + for (JsonNode subnode : node) { + if (subnode != null) { + resultList.add(treeToValue(subnode, valueType)); + } + } + } + return resultList; + } + + /** + * This is a removeJsonNullNode method + * + * @param node + */ + public static void removeJsonNullNode(JsonNode node) { + Iterator it = node.iterator(); + while (it.hasNext()) { + JsonNode child = it.next(); + if (child.isNull()) { + it.remove(); + } else { + removeJsonNullNode(child); + } + } + } + + public static void printProperty(Properties property) { + if (property != null) { + Map sortedMap = new TreeMap(property); + StringBuilder buffer = new StringBuilder(); + sortedMap.entrySet().forEach(message -> { + buffer.append("\n" + message.toString()); + }); + logger.debug("Property : ({})", buffer); + } + } + + public static void printMap(Map map) { + if (map != null) { + Map sortedMap = new TreeMap(map); + StringBuilder buffer = new StringBuilder(); + sortedMap.entrySet().forEach(message -> { + buffer.append("\n" + message.toString()); + }); + logger.debug("Map: ({})", buffer); + } + } + + @SuppressWarnings("squid:S00112") + public static Map convertJson2RootProperties(Map context, String jsonContent) + throws Exception { + if (context == null) { + context = new HashMap<>(); + } + + ObjectMapper mapper = new ObjectMapper(); + JsonNode rootArray = mapper.readTree(jsonContent); + return convertJson2RootProperties(context, rootArray); + } + + public static Map convertJson2RootProperties(Map context, JsonNode rootArray) { + Map sortedMap = null; + + if (context == null) { + context = new HashMap<>(); + } + if (rootArray != null) { + Iterator> fields = rootArray.fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + if (entry != null && entry.getValue() != null) { + if (entry.getValue().isTextual()) { + context.put(entry.getKey(), entry.getValue().textValue()); + } else { + context.put(entry.getKey(), entry.getValue().toString()); + } + } + } + } + sortedMap = new TreeMap<>(context); + return sortedMap; + } + + @SuppressWarnings("squid:S00112") + public static Map convertJson2Properties(Map context, String jsonContent, + List blockKeys) throws Exception { + Map sortedMap = null; + + if (context == null) { + context = new HashMap<>(); + } + + ObjectMapper mapper = new ObjectMapper(); + JsonNode rootArray = mapper.readTree(jsonContent); + + if (rootArray != null) { + Iterator> fields = rootArray.fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + processJsonNode(context, blockKeys, entry.getKey(), entry.getValue()); + } + } + sortedMap = new TreeMap<>(context); + return sortedMap; + } + + public static Map convertJson2Properties(Map context, JsonNode rootArray, + List blockKeys) throws IOException { + Map sortedMap = null; + + if (context == null) { + context = new HashMap<>(); + } + + if (blockKeys == null) { + blockKeys = new ArrayList<>(); + } + + if (rootArray != null) { + Iterator> fields = rootArray.fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + processJsonNode(context, blockKeys, entry.getKey(), entry.getValue()); + } + } + sortedMap = new TreeMap<>(context); + return sortedMap; + } + + private static void processJsonNode(Map propertyMap, List blockKeys, String nodeName, + JsonNode node) throws IOException { + + logger.trace("Block Key ({})", nodeName); + if (node == null) { + return; + } + + String keyName = null; + if (blockKeys != null && blockKeys.contains(nodeName)) { + if (node.isArray() || node.isObject()) { + propertyMap.put(nodeName, node.toString()); + } else { + propertyMap.put(nodeName, node.asText()); + } + } else if (node.isArray()) { + for (int i = 0; i < node.size(); i++) { + keyName = nodeName + "[" + i + "]"; + processJsonNode(propertyMap, blockKeys, keyName, node.get(i)); + } + } else if (node.isObject()) { + Iterator> fields = node.fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + keyName = nodeName + "." + entry.getKey(); + processJsonNode(propertyMap, blockKeys, keyName, entry.getValue()); + } + } else { + propertyMap.put(nodeName, node.asText()); + } + } + +} -- cgit 1.2.3-korg