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