From 280a0f6c73ab1c1aed9ee87fbd053d01d3838d70 Mon Sep 17 00:00:00 2001 From: "Singal, Kapil (ks220y)" Date: Wed, 12 Sep 2018 16:26:03 -0400 Subject: Controller Blueprints Nitrogen to Oxygen Migration Changing package structure from org.onap.ccsdk.config to org.onap.ccsdk.features Change-Id: I7d52b498f11ed892d547220cc4354298b6182c77 Issue-ID: CCSDK-560 Signed-off-by: Singal, Kapil (ks220y) --- .../plugin/assignment-provider/pom.xml | 10 +- .../assignment/ConfigAssignmentConstants.java | 37 --- .../assignment/data/ResourceAssignmentData.java | 163 ----------- .../assignment/processor/DBResourceProcessor.java | 267 ------------------ .../processor/DefaultResourceProcessor.java | 107 -------- .../processor/InputResourceProcessor.java | 96 ------- .../processor/MdsalResourceProcessor.java | 239 ---------------- .../assignment/processor/ProcessorFactory.java | 52 ---- .../processor/ResourceAssignmentProcessor.java | 120 -------- .../assignment/service/ConfigAssignmentNode.java | 231 ---------------- .../service/ConfigAssignmentPersistService.java | 123 --------- .../service/ConfigAssignmentProcessService.java | 238 ---------------- .../service/ConfigAssignmentService.java | 35 --- .../service/ConfigAssignmentServiceImpl.java | 79 ------ .../assignment/service/ConfigAssignmentUtils.java | 305 --------------------- .../assignment/service/ConfigPreviewService.java | 119 -------- .../service/ResourceDictionaryService.java | 112 -------- .../assignment/service/ResourceModelService.java | 97 ------- .../assignment/ConfigAssignmentConstants.java | 37 +++ .../assignment/data/ResourceAssignmentData.java | 164 +++++++++++ .../assignment/processor/DBResourceProcessor.java | 267 ++++++++++++++++++ .../processor/DefaultResourceProcessor.java | 107 ++++++++ .../processor/InputResourceProcessor.java | 96 +++++++ .../processor/MdsalResourceProcessor.java | 239 ++++++++++++++++ .../assignment/processor/ProcessorFactory.java | 52 ++++ .../processor/ResourceAssignmentProcessor.java | 120 ++++++++ .../assignment/service/ConfigAssignmentNode.java | 231 ++++++++++++++++ .../service/ConfigAssignmentPersistService.java | 123 +++++++++ .../service/ConfigAssignmentProcessService.java | 238 ++++++++++++++++ .../service/ConfigAssignmentService.java | 36 +++ .../service/ConfigAssignmentServiceImpl.java | 80 ++++++ .../assignment/service/ConfigAssignmentUtils.java | 305 +++++++++++++++++++++ .../assignment/service/ConfigPreviewService.java | 119 ++++++++ .../service/ResourceDictionaryService.java | 112 ++++++++ .../assignment/service/ResourceModelService.java | 97 +++++++ .../org/opendaylight/blueprint/impl-blueprint.xml | 18 +- .../processor/DBResourceProcessorTest.java | 231 ---------------- .../processor/DefaultResourceProcessorTest.java | 127 --------- .../processor/InputResourceProcessorTest.java | 178 ------------ .../processor/MdsalResourceProcessorTest.java | 268 ------------------ .../service/ConfigAssignmentNodeTest.java | 246 ----------------- .../service/ConfigPreviewServiceTest.java | 111 -------- .../service/ConfigResourceAssignmentTestUtils.java | 182 ------------ .../service/ResourceAssignmentGenerationTest.java | 110 -------- .../service/ResourceAssignmentValidation.java | 94 ------- .../assignment/service/TopologicalSortingTest.java | 60 ---- .../processor/DBResourceProcessorTest.java | 232 ++++++++++++++++ .../processor/DefaultResourceProcessorTest.java | 128 +++++++++ .../processor/InputResourceProcessorTest.java | 179 ++++++++++++ .../processor/MdsalResourceProcessorTest.java | 269 ++++++++++++++++++ .../service/ConfigAssignmentNodeTest.java | 247 +++++++++++++++++ .../service/ConfigPreviewServiceTest.java | 113 ++++++++ .../service/ConfigResourceAssignmentTestUtils.java | 183 +++++++++++++ .../service/ResourceAssignmentGenerationTest.java | 111 ++++++++ .../service/ResourceAssignmentValidation.java | 95 +++++++ .../assignment/service/TopologicalSortingTest.java | 60 ++++ .../service_templates/resource_assignment.json | 4 +- .../resource_assignment/resource_assignment.json | 4 +- .../vpe-201802-baseconfig.json | 4 +- 59 files changed, 4060 insertions(+), 4047 deletions(-) delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/ConfigAssignmentConstants.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/data/ResourceAssignmentData.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/DBResourceProcessor.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/DefaultResourceProcessor.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/InputResourceProcessor.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/MdsalResourceProcessor.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/ProcessorFactory.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/ResourceAssignmentProcessor.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentNode.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentPersistService.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentProcessService.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentService.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentServiceImpl.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentUtils.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigPreviewService.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ResourceDictionaryService.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ResourceModelService.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/ConfigAssignmentConstants.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/data/ResourceAssignmentData.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/DBResourceProcessor.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/DefaultResourceProcessor.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/InputResourceProcessor.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/MdsalResourceProcessor.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/ProcessorFactory.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/ResourceAssignmentProcessor.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentNode.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentPersistService.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentProcessService.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentService.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentServiceImpl.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentUtils.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigPreviewService.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ResourceDictionaryService.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ResourceModelService.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/DBResourceProcessorTest.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/DefaultResourceProcessorTest.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/InputResourceProcessorTest.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/MdsalResourceProcessorTest.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentNodeTest.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ConfigPreviewServiceTest.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ConfigResourceAssignmentTestUtils.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ResourceAssignmentGenerationTest.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ResourceAssignmentValidation.java delete mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/TopologicalSortingTest.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/DBResourceProcessorTest.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/DefaultResourceProcessorTest.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/InputResourceProcessorTest.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/MdsalResourceProcessorTest.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentNodeTest.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ConfigPreviewServiceTest.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ConfigResourceAssignmentTestUtils.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ResourceAssignmentGenerationTest.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ResourceAssignmentValidation.java create mode 100644 blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/TopologicalSortingTest.java (limited to 'blueprints-processor/plugin/assignment-provider') diff --git a/blueprints-processor/plugin/assignment-provider/pom.xml b/blueprints-processor/plugin/assignment-provider/pom.xml index 4f6b2936e..5ca679baf 100644 --- a/blueprints-processor/plugin/assignment-provider/pom.xml +++ b/blueprints-processor/plugin/assignment-provider/pom.xml @@ -105,11 +105,11 @@ ${project.artifactId} ${project.groupId}.${project.artifactId} - org.onap.ccsdk.config.assignment, - org.onap.ccsdk.config.assignment.data, - org.onap.ccsdk.config.assignment.service, - org.onap.ccsdk.config.assignment.processor, - org.onap.ccsdk.config.assignment.processor.custom + org.onap.ccsdk.features.assignment, + org.onap.ccsdk.features.assignment.data, + org.onap.ccsdk.features.assignment.service, + org.onap.ccsdk.features.assignment.processor, + org.onap.ccsdk.features.assignment.processor.custom diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/ConfigAssignmentConstants.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/ConfigAssignmentConstants.java deleted file mode 100644 index 10e217b8c..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/ConfigAssignmentConstants.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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.assignment; - -@SuppressWarnings("squid:S1118") -public class ConfigAssignmentConstants { - - public static final String OUTPUT_PARAM_STATUS = "status"; - public static final String OUTPUT_PARAM_RESOURCE_ASSIGNMENT_PARAMS = "resource-assignment-params"; - public static final String OUTPUT_PARAM_MASHED_DATA = "mashed-data"; - public static final String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; - public static final String OUTPUT_STATUS_SUCCESS = "success"; - public static final String OUTPUT_STATUS_FAILURE = "failure"; - - public static final String INPUT_PARAM_REQUEST_ID = "request-id"; - public static final String INPUT_PARAM_RESOURCE_ID = "resource-id"; - public static final String INPUT_PARAM_RESOURCE_TYPE = "resource-type"; - public static final String INPUT_PARAM_ACTION_NAME = "action-name"; - public static final String INPUT_PARAM_TEMPLATE_NAMES = "template-names"; - public static final String INPUT_PARAM_INPUT_DATA = "input-data"; - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/data/ResourceAssignmentData.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/data/ResourceAssignmentData.java deleted file mode 100644 index 816c943f3..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/data/ResourceAssignmentData.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * 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.assignment.data; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; - -public class ResourceAssignmentData { - - private String requestId; - private boolean reloadModel; - private String resourceType; - private String resourceId; - private String serviceTemplateName; - private String serviceTemplateVersion; - private String actionName; - private String inputData; - private SvcLogicContext svcLogicContext; - private List templateNames; - private Map> templatesResourceAssignments = new HashMap<>(); - private Map templatesContents = new HashMap<>(); - private Map templatesMashedContents = new HashMap<>(); - private Map templatesData = new HashMap<>(); - private Map context = new HashMap<>(); - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public String getResourceType() { - return resourceType; - } - - public void setResourceType(String resourceType) { - this.resourceType = resourceType; - } - - public String getResourceId() { - return resourceId; - } - - public void setResourceId(String resourceId) { - this.resourceId = resourceId; - } - - public String getServiceTemplateName() { - return serviceTemplateName; - } - - public void setServiceTemplateName(String serviceTemplateName) { - this.serviceTemplateName = serviceTemplateName; - } - - public String getServiceTemplateVersion() { - return serviceTemplateVersion; - } - - public void setServiceTemplateVersion(String serviceTemplateVersion) { - this.serviceTemplateVersion = serviceTemplateVersion; - } - - public String getActionName() { - return actionName; - } - - public void setActionName(String actionName) { - this.actionName = actionName; - } - - public String getInputData() { - return inputData; - } - - public void setInputData(String inputData) { - this.inputData = inputData; - } - - public List getTemplateNames() { - return templateNames; - } - - public void setTemplateNames(List templateNames) { - this.templateNames = templateNames; - } - - public Map> getTemplatesResourceAssignments() { - return templatesResourceAssignments; - } - - public void setTemplatesResourceAssignments(Map> templatesResourceAssignments) { - this.templatesResourceAssignments = templatesResourceAssignments; - } - - public Map getTemplatesContents() { - return templatesContents; - } - - public void setTemplatesContents(Map templatesContents) { - this.templatesContents = templatesContents; - } - - public Map getTemplatesMashedContents() { - return templatesMashedContents; - } - - public void setTemplatesMashedContents(Map templatesMashedContents) { - this.templatesMashedContents = templatesMashedContents; - } - - public Map getTemplatesData() { - return templatesData; - } - - public void setTemplatesData(Map templatesData) { - this.templatesData = templatesData; - } - - public Map getContext() { - return context; - } - - public void setContext(Map context) { - this.context = context; - } - - public SvcLogicContext getSvcLogicContext() { - return svcLogicContext; - } - - public void setSvcLogicContext(SvcLogicContext svcLogicContext) { - this.svcLogicContext = svcLogicContext; - } - - public boolean isReloadModel() { - return reloadModel; - } - - public void setReloadModel(boolean reloadModel) { - this.reloadModel = reloadModel; - } -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/DBResourceProcessor.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/DBResourceProcessor.java deleted file mode 100644 index 5f3e6094c..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/DBResourceProcessor.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * 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.assignment.processor; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.ccsdk.config.assignment.service.ConfigAssignmentUtils; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -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 org.onap.ccsdk.config.model.data.dict.SourcesDefinition; -import org.onap.ccsdk.config.model.service.ComponentNode; -import org.onap.ccsdk.config.model.utils.JsonUtils; -import org.onap.ccsdk.config.model.utils.ResourceAssignmentUtils; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import com.fasterxml.jackson.databind.node.ObjectNode; - -public class DBResourceProcessor implements ComponentNode { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(DBResourceProcessor.class); - private ConfigResourceService configResourceService; - private Map dictionaries; - - public DBResourceProcessor(ConfigResourceService configResourceService) { - this.configResourceService = configResourceService; - } - - @Override - public Boolean preCondition(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - return Boolean.TRUE; - } - - @Override - public void preProcess(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - // Auto-generated method stub - } - - @Override - public void process(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - // Auto-generated method stub - } - - @SuppressWarnings("unchecked") - @Override - public void process(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - try { - List batchResourceAssignment = - (List) componentContext.get(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS); - dictionaries = - (Map) componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARIES); - - if (CollectionUtils.isNotEmpty(batchResourceAssignment)) { - for (ResourceAssignment resourceAssignment : batchResourceAssignment) { - processResourceAssignment(ctx, componentContext, resourceAssignment); - } - } - } catch (Exception e) { - throw new SvcLogicException(String.format("DBResourceProcessor Exception : (%s)", e), e); - } - } - - private void processResourceAssignment(SvcLogicContext ctx, Map componentContext, - ResourceAssignment resourceAssignment) throws SvcLogicException, ConfigModelException { - if (resourceAssignment != null) { - try { - validate(resourceAssignment); - - // Check if It has Input - Object value = ConfigAssignmentUtils.getContextKeyValue(ctx, resourceAssignment.getName()); - if (value != null) { - logger.info("db source template key ({}) found from input and value is ({})", - resourceAssignment.getName(), value); - ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, value); - return; - } - - ResourceDefinition resourceDefinition = dictionaries.get(resourceAssignment.getDictionaryName()); - SourcesDefinition sourceDb = resourceDefinition.getSources().get("db"); - if (StringUtils.isBlank(sourceDb.getProperties().getQuery())) { - throw new SvcLogicException("db query property is missing"); - } - - String sql = sourceDb.getProperties().getQuery(); - Map inputKeyMapping = sourceDb.getProperties().getInputKeyMapping(); - - logger.info("Db dictionary information : ({}), ({}), ({})", sql, inputKeyMapping, - sourceDb.getProperties().getOutputKeyMapping()); - - Map namedParameters = populateNamedParameter(componentContext, inputKeyMapping); - - logger.info("Parameter information : ({})", namedParameters); - List> rows = configResourceService.query(sql, namedParameters); - if (rows != null && !rows.isEmpty()) { - processDBResults(ctx, componentContext, resourceAssignment, sourceDb, rows); - } else { - logger.warn("Failed to get db result for dictionary name ({}) the query ({})", - resourceAssignment.getDictionaryName(), sql); - } - - // Check the value has populated for mandatory case - ResourceAssignmentUtils.assertTemplateKeyValueNotNull(componentContext, resourceAssignment); - } catch (Exception e) { - ResourceAssignmentUtils.setFailedResourceDataValue(componentContext, resourceAssignment, - e.getMessage()); - throw new SvcLogicException( - String.format("Failed in template key (%s) assignments : (%s)", resourceAssignment, e), e); - } - } else { - // Do Nothing - } - } - - private void validate(ResourceAssignment resourceAssignment) throws SvcLogicException { - if (resourceAssignment == null) { - throw new SvcLogicException("resource assignment is not defined"); - } - - if (StringUtils.isBlank(resourceAssignment.getName())) { - throw new SvcLogicException("resource assignment template key is not defined"); - } - - if (StringUtils.isBlank(resourceAssignment.getDictionaryName())) { - throw new SvcLogicException( - String.format("resource assignment dictionary name is not defined for template key (%s)", - resourceAssignment.getName())); - } - - if (!ConfigModelConstant.SOURCE_DB.equalsIgnoreCase(resourceAssignment.getDictionarySource())) { - throw new SvcLogicException(String.format("resource assignment source is not db, it is (%s)", - resourceAssignment.getDictionarySource())); - } - - ResourceDefinition resourceDefinition = dictionaries.get(resourceAssignment.getDictionaryName()); - if (resourceDefinition == null) { - throw new SvcLogicException(String.format("missing resource dictionary definition for name (%s) ", - resourceAssignment.getDictionaryName())); - } - - if (resourceDefinition.getSources() == null || resourceDefinition.getSources().get("db") == null) { - throw new SvcLogicException(String.format("missing resource dictionary db source definition for name (%s) ", - resourceAssignment.getDictionaryName())); - } - - SourcesDefinition sourceDb = resourceDefinition.getSources().get("db"); - if (StringUtils.isBlank(sourceDb.getProperties().getQuery())) { - throw new SvcLogicException(String.format("Failed to get request Query for dictionary (%s)", - resourceAssignment.getDictionaryName())); - } - - } - - private Map populateNamedParameter(Map componentContext, - Map inputKeyMapping) { - Map namedParameters = new HashMap<>(); - if (MapUtils.isNotEmpty(inputKeyMapping)) { - - for (Map.Entry mapping : inputKeyMapping.entrySet()) { - ResourceDefinition referenceDictionaryDefinition = dictionaries.get(mapping.getValue()); - Object expressionValue = - ResourceAssignmentUtils.getDictionaryKeyValue(componentContext, referenceDictionaryDefinition); - logger.trace("Reference dictionary key ({}), value ({})", mapping.getKey(), expressionValue); - namedParameters.put(mapping.getKey(), expressionValue); - } - } - return namedParameters; - } - - @SuppressWarnings("squid:S3776") - private void processDBResults(SvcLogicContext ctx, Map componentContext, - ResourceAssignment resourceAssignment, SourcesDefinition sourceDb, List> rows) - throws SvcLogicException, ConfigModelException { - - Map outputKeyMapping = sourceDb.getProperties().getOutputKeyMapping(); - String type = resourceAssignment.getProperty().getType(); - String entrySchema = null; - logger.info("Response processing type({})", type); - // Primitive Types - if (ValidTypes.getPrimitivePropertType().contains(type)) { - - Map row = rows.get(0); - String dbColumnName = outputKeyMapping.get(resourceAssignment.getDictionaryName()); - Object dbColumnValue = row.get(dbColumnName); - ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, dbColumnValue); - - } else if (ValidTypes.getListPropertType().contains(type)) { - // Array Types - if (resourceAssignment.getProperty().getEntrySchema() != null) { - entrySchema = resourceAssignment.getProperty().getEntrySchema().getType(); - } - - if (StringUtils.isNotBlank(entrySchema)) { - ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode(); - - for (Map row : rows) { - if (ValidTypes.getPrimitivePropertType().contains(entrySchema)) { - String dbColumnName = outputKeyMapping.get(resourceAssignment.getDictionaryName()); - Object dbColumnValue = row.get(dbColumnName); - // Add Array JSON - JsonUtils.populatePrimitiveValues(dbColumnValue, entrySchema, arrayNode); - } else { - ObjectNode arrayChildNode = JsonNodeFactory.instance.objectNode(); - for (Map.Entry mapping : outputKeyMapping.entrySet()) { - Object dbColumnValue = row.get(mapping.getKey()); - String propertyTypeForDataType = - ConfigAssignmentUtils.getPropertyType(ctx, entrySchema, mapping.getKey()); - JsonUtils.populatePrimitiveValues(mapping.getKey(), dbColumnValue, propertyTypeForDataType, - arrayChildNode); - } - arrayNode.add(arrayChildNode); - } - } - // Set the List of Complex Values - ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, arrayNode); - } else { - throw new SvcLogicException(String.format("Entry schema is not defined for dictionary (%s) info", - resourceAssignment.getDictionaryName())); - } - } else { - // Complex Types - Map row = rows.get(0); - ObjectNode objectNode = JsonNodeFactory.instance.objectNode(); - for (Map.Entry mapping : outputKeyMapping.entrySet()) { - Object dbColumnValue = row.get(mapping.getKey()); - String propertyTypeForDataType = ConfigAssignmentUtils.getPropertyType(ctx, type, mapping.getKey()); - JsonUtils.populatePrimitiveValues(mapping.getKey(), dbColumnValue, propertyTypeForDataType, objectNode); - } - ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, objectNode); - } - } - - @Override - public void postProcess(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - // Auto-generated method stub - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/DefaultResourceProcessor.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/DefaultResourceProcessor.java deleted file mode 100644 index aac13cb9d..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/DefaultResourceProcessor.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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.assignment.processor; - -import java.util.List; -import java.util.Map; -import org.apache.commons.lang3.StringUtils; -import org.onap.ccsdk.config.assignment.service.ConfigAssignmentUtils; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.ConfigModelException; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.service.ComponentNode; -import org.onap.ccsdk.config.model.utils.ResourceAssignmentUtils; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; - -public class DefaultResourceProcessor implements ComponentNode { - - public DefaultResourceProcessor(ConfigResourceService configResourceService) {} - - @Override - public Boolean preCondition(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - return Boolean.TRUE; - } - - @Override - public void preProcess(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - // Auto-generated method stub - } - - @Override - public void process(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - // Auto-generated method stub - } - - @SuppressWarnings("unchecked") - @Override - public void process(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - try { - List batchResourceAssignment = - (List) componentContext.get(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS); - - if (batchResourceAssignment != null && !batchResourceAssignment.isEmpty()) { - for (ResourceAssignment resourceAssignment : batchResourceAssignment) { - processResourceAssignment(ctx, componentContext, resourceAssignment); - } - } - } catch (Exception e) { - throw new SvcLogicException(String.format("DefaultResourceProcessor Exception : (%s)", e), e); - } - - } - - private void processResourceAssignment(SvcLogicContext ctx, Map componentContext, - ResourceAssignment resourceAssignment) throws ConfigModelException, SvcLogicException { - if (resourceAssignment != null && StringUtils.isNotBlank(resourceAssignment.getName()) - && resourceAssignment.getProperty() != null) { - try { - // Check if It has Input - Object value = ConfigAssignmentUtils.getContextKeyValue(ctx, resourceAssignment.getName()); - if (value == null) { - value = resourceAssignment.getProperty().getDefaultValue(); - } - - // if value is null don't call setResourceDataValue to populate the value - if (value != null) { - ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, value); - } - - // Check the value has populated for mandatory case - ResourceAssignmentUtils.assertTemplateKeyValueNotNull(componentContext, resourceAssignment); - } catch (Exception e) { - ResourceAssignmentUtils.setFailedResourceDataValue(componentContext, resourceAssignment, - e.getMessage()); - throw new SvcLogicException( - String.format("Failed in template key (%s) assignments with : (%s)", resourceAssignment, e), e); - } - } - } - - @Override - public void postProcess(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - // Auto-generated method stub - - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/InputResourceProcessor.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/InputResourceProcessor.java deleted file mode 100644 index e32e7af51..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/InputResourceProcessor.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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.assignment.processor; - -import java.util.List; -import java.util.Map; -import org.apache.commons.lang3.StringUtils; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.ConfigModelException; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.service.ComponentNode; -import org.onap.ccsdk.config.model.utils.ResourceAssignmentUtils; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; - -public class InputResourceProcessor implements ComponentNode { - - public InputResourceProcessor(ConfigResourceService configResourceService) {} - - @Override - public Boolean preCondition(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - return Boolean.TRUE; - } - - @Override - public void preProcess(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - // Auto-generated method stub - } - - @Override - public void process(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - // Auto-generated method stub - } - - @SuppressWarnings("unchecked") - @Override - public void process(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - try { - List batchResourceAssignment = - (List) componentContext.get(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS); - if (batchResourceAssignment != null && !batchResourceAssignment.isEmpty()) { - for (ResourceAssignment resourceAssignment : batchResourceAssignment) { - processResourceAssignment(ctx, componentContext, resourceAssignment); - } - } - } catch (Exception e) { - throw new SvcLogicException(String.format("InputResourceProcessor Exception : (%s)", e), e); - } - } - - private void processResourceAssignment(SvcLogicContext ctx, Map componentContext, - ResourceAssignment resourceAssignment) throws ConfigModelException, SvcLogicException { - try { - if (StringUtils.isNotBlank(resourceAssignment.getName())) { - String value = ctx.getAttribute(resourceAssignment.getName()); - // if value is null don't call setResourceDataValue to populate the value - if (StringUtils.isNotBlank(value)) { - ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, value); - } - } - - // Check the value has populated for mandatory case - ResourceAssignmentUtils.assertTemplateKeyValueNotNull(componentContext, resourceAssignment); - } catch (Exception e) { - ResourceAssignmentUtils.setFailedResourceDataValue(componentContext, resourceAssignment, e.getMessage()); - throw new SvcLogicException( - String.format("Failed in template key (%s) assignments with : (%s)", resourceAssignment, e), e); - } - } - - @Override - public void postProcess(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - // Auto-generated method stub - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/MdsalResourceProcessor.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/MdsalResourceProcessor.java deleted file mode 100644 index 15528e13e..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/MdsalResourceProcessor.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * 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.assignment.processor; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.ccsdk.config.assignment.service.ConfigAssignmentUtils; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.ConfigModelException; -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 org.onap.ccsdk.config.model.service.ComponentNode; -import org.onap.ccsdk.config.model.utils.ResourceAssignmentUtils; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.config.rest.adaptor.ConfigRestAdaptorConstants; -import org.onap.ccsdk.config.rest.adaptor.service.ConfigRestAdaptorService; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; - -public class MdsalResourceProcessor implements ComponentNode { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(MdsalResourceProcessor.class); - private ConfigRestAdaptorService configRestAdaptorService; - private Map dictionaries; - - public MdsalResourceProcessor(ConfigRestAdaptorService configRestAdaptorService) { - this.configRestAdaptorService = configRestAdaptorService; - } - - @Override - public Boolean preCondition(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - return Boolean.TRUE; - } - - @Override - public void preProcess(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - // Auto-generated method stub - } - - @Override - public void process(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - // Auto-generated method stub - } - - @SuppressWarnings("unchecked") - @Override - public void process(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - try { - List batchResourceAssignment = - (List) componentContext.get(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS); - dictionaries = - (Map) componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARIES); - - if (CollectionUtils.isNotEmpty(batchResourceAssignment)) { - for (ResourceAssignment resourceAssignment : batchResourceAssignment) { - processResourceAssignmnet(ctx, componentContext, resourceAssignment); - } - } - } catch (Exception e) { - throw new SvcLogicException(String.format("MdsalResourceProcessor Exception : (%s) ", e), e); - } - } - - private void processResourceAssignmnet(SvcLogicContext ctx, Map componentContext, - ResourceAssignment resourceAssignment) throws ConfigModelException, SvcLogicException { - - try { - // Validating Resource Assignment and Dictionary Definition data - validate(resourceAssignment); - - // Check if It has Input - Object value = ConfigAssignmentUtils.getContextKeyValue(ctx, resourceAssignment.getName()); - if (value != null) { - logger.info("mdsal source template key ({}) found from input and value is ({})", - resourceAssignment.getName(), value); - ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, value); - return; - } - - ResourceDefinition resourceDefinition = dictionaries.get(resourceAssignment.getDictionaryName()); - SourcesDefinition sourceMdsal = resourceDefinition.getSources().get("mdsal"); - String urlPath = sourceMdsal.getProperties().getUrlPath(); - String path = sourceMdsal.getProperties().getPath(); - Map inputKeyMapping = sourceMdsal.getProperties().getInputKeyMapping(); - Map outputKeyMapping = sourceMdsal.getProperties().getOutputKeyMapping(); - - logger.info( - "mdsal dictionary information : urlpath ({}), path({}), inputKeyMapping ({}), outputKeyMapping ({})", - urlPath, path, inputKeyMapping, outputKeyMapping); - - // Resolving url Variables - Map urlVariables = populateUrlVariables(inputKeyMapping, componentContext); - for (Map.Entry entry : urlVariables.entrySet()) { - urlPath = urlPath.replaceAll("\\$" + entry.getKey(), entry.getValue().toString()); - } - - String restResponse = fetchResourceFromMDSAL(urlPath); - // if restResponse is null don't call processMdsalResults to populate the value - if (StringUtils.isNotBlank(restResponse)) { - // Processing MDSAL Response - processMdsalResults(ctx, componentContext, resourceAssignment, sourceMdsal, restResponse); - } else { - logger.warn("Coudn't get proper mdsal Response content ({}) for Resource Name ({}) for URI ({})", - restResponse, resourceAssignment.getDictionaryName(), urlPath); - } - - // Check the value has populated for mandatory case - ResourceAssignmentUtils.assertTemplateKeyValueNotNull(componentContext, resourceAssignment); - } catch (Exception e) { - ResourceAssignmentUtils.setFailedResourceDataValue(componentContext, resourceAssignment, e.getMessage()); - throw new SvcLogicException( - String.format("Failed in assignments for (%s) with (%s)", resourceAssignment, e), e); - } - } - - private String fetchResourceFromMDSAL(String urlPath) { - String response = null; - try { - response = configRestAdaptorService.getResource(ConfigRestAdaptorConstants.SELECTOR_RESTCONF, urlPath, - String.class); - } catch (Exception e) { - logger.warn("Fetching MDSAL data for URL ({}) failed with Error ({})", urlPath, e); - } - return response; - } - - private void validate(ResourceAssignment resourceAssignment) throws SvcLogicException { - if (resourceAssignment == null) { - throw new SvcLogicException("resource assignment is not defined"); - } - - if (StringUtils.isBlank(resourceAssignment.getName())) { - throw new SvcLogicException("resource assignment template key is not defined"); - } - - if (StringUtils.isBlank(resourceAssignment.getDictionaryName())) { - throw new SvcLogicException( - String.format("resource assignment dictionary name is not defined for template key (%s)", - resourceAssignment.getName())); - } - - if (!ConfigModelConstant.SOURCE_MDSAL.equalsIgnoreCase(resourceAssignment.getDictionarySource())) { - throw new SvcLogicException(String.format("resource assignment source is not mdsal, it is (%s)", - resourceAssignment.getDictionarySource())); - } - - ResourceDefinition resourceDefinition = dictionaries.get(resourceAssignment.getDictionaryName()); - if (resourceDefinition == null) { - throw new SvcLogicException(String.format("missing resource dictionary definition for name (%s) ", - resourceAssignment.getDictionaryName())); - } - - if (StringUtils.isBlank(resourceDefinition.getProperty().getType())) { - throw new SvcLogicException(String.format(String.format("Failed to get dictionary (%s) data type info.", - resourceAssignment.getDictionaryName()))); - } - - if (resourceDefinition.getSources() == null || resourceDefinition.getSources().get("mdsal") == null) { - throw new SvcLogicException( - String.format("missing resource dictionary mdsal source definition for name (%s) ", - resourceAssignment.getDictionaryName())); - } - - SourcesDefinition sourceMdsal = resourceDefinition.getSources().get("mdsal"); - if (StringUtils.isBlank(sourceMdsal.getProperties().getUrlPath())) { - throw new SvcLogicException(String.format("Failed to get request URL Path for dictionary (%s)", - resourceAssignment.getDictionaryName())); - } - - if (StringUtils.isBlank(sourceMdsal.getProperties().getPath())) { - throw new SvcLogicException(String.format("Failed to get request Path for dictionary (%s)", - resourceAssignment.getDictionaryName())); - } - } - - private Map populateUrlVariables(Map inputKeyMapping, - Map componentContext) { - Map urlVariables = new HashMap<>(); - if (MapUtils.isNotEmpty(inputKeyMapping)) { - - for (Map.Entry mapping : inputKeyMapping.entrySet()) { - ResourceDefinition referenceDictionaryDefinition = dictionaries.get(mapping.getValue()); - Object expressionValue = - ResourceAssignmentUtils.getDictionaryKeyValue(componentContext, referenceDictionaryDefinition); - logger.trace("Reference dictionary key ({}), value ({})", mapping.getKey(), expressionValue); - urlVariables.put(mapping.getKey(), expressionValue); - } - } - return urlVariables; - } - - private void processMdsalResults(SvcLogicContext ctx, Map componentContext, - ResourceAssignment resourceAssignment, SourcesDefinition sourceMdsal, String restResponse) - throws SvcLogicException, ConfigModelException { - - Map outputKeyMapping = sourceMdsal.getProperties().getOutputKeyMapping(); - JsonNode responseNode = TransformationUtils.getJsonNodeForString(restResponse); - if (StringUtils.isNotBlank(sourceMdsal.getProperties().getPath())) { - responseNode = responseNode.at(sourceMdsal.getProperties().getPath()); - } - if (responseNode != null) { - ConfigAssignmentUtils.populateValueForOutputMapping(ctx, componentContext, resourceAssignment, - outputKeyMapping, responseNode); - } - } - - @Override - public void postProcess(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - // Do Nothing - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/ProcessorFactory.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/ProcessorFactory.java deleted file mode 100644 index 5fcedd87f..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/ProcessorFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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.assignment.processor; - -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.service.ComponentNode; -import org.onap.ccsdk.config.model.service.ComponentNodeService; -import org.onap.ccsdk.config.rest.adaptor.service.ConfigRestAdaptorService; - -public class ProcessorFactory { - - private ConfigResourceService configResourceService; - private ConfigRestAdaptorService configRestAdaptorService; - private ComponentNodeService componentNodeService; - - public ProcessorFactory(ConfigResourceService configResourceService, - ConfigRestAdaptorService configRestAdaptorService, ComponentNodeService componentNodeService) { - this.componentNodeService = componentNodeService; - this.configResourceService = configResourceService; - this.configRestAdaptorService = configRestAdaptorService; - } - - public ComponentNode getInstance(String source) { - - if (ConfigModelConstant.SOURCE_DEFAULT.equalsIgnoreCase(source)) { - return new DefaultResourceProcessor(configResourceService); - } else if (ConfigModelConstant.SOURCE_DB.equalsIgnoreCase(source)) { - return new DBResourceProcessor(configResourceService); - } else if (ConfigModelConstant.SOURCE_MDSAL.equalsIgnoreCase(source)) { - return new MdsalResourceProcessor(configRestAdaptorService); - } - // Default - return new InputResourceProcessor(configResourceService); - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/ResourceAssignmentProcessor.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/ResourceAssignmentProcessor.java deleted file mode 100644 index 70d9abc68..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/processor/ResourceAssignmentProcessor.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * 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.assignment.processor; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.collections.CollectionUtils; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.utils.TopologicalSortingUtils; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ResourceAssignmentProcessor { - private static EELFLogger logger = EELFManager.getInstance().getLogger(ResourceAssignmentProcessor.class); - - private List assignments; - private Map resourceAssignmentMap; - - @SuppressWarnings("squid:S1172") - public ResourceAssignmentProcessor(List assignments, SvcLogicContext ctx) { - this.assignments = assignments; - this.resourceAssignmentMap = new HashMap<>(); - } - - @SuppressWarnings("squid:S3776") - public List> process() { - List> sequenceBatchResourceAssignment = new ArrayList<>(); - if (this.assignments != null) { - logger.info("Assignments ({})", this.assignments); - this.assignments.forEach(resourceMapping -> { - if (resourceMapping != null) { - logger.trace("Processing Key ({})", resourceMapping.getName()); - resourceAssignmentMap.put(resourceMapping.getName(), resourceMapping); - } - }); - - TopologicalSortingUtils topologySorting = new TopologicalSortingUtils<>(); - this.resourceAssignmentMap.forEach((mappingKey, mapping) -> { - if (mapping != null) { - if (mapping.getDependencies() != null && !mapping.getDependencies().isEmpty()) { - for (String dependency : mapping.getDependencies()) { - topologySorting.add(resourceAssignmentMap.get(dependency), mapping); - } - } else { - topologySorting.add(null, mapping); - } - } - }); - - List sequencedResourceAssignments = topologySorting.topSort(); - logger.info("Sorted Sequenced Assignments ({})", sequencedResourceAssignments); - - List batchResourceAssignment = null; - List batchAssignmentName = null; - for (int i = 0; i < sequencedResourceAssignments.size(); i++) { - ResourceAssignment resourceAssignment = sequencedResourceAssignments.get(i); - ResourceAssignment previousResourceAssignment = null; - - if (i > 0) { - previousResourceAssignment = sequencedResourceAssignments.get(i - 1); - } - if (resourceAssignment != null) { - - boolean dependencyPresence = false; - if (batchAssignmentName != null && resourceAssignment.getDependencies() != null) { - dependencyPresence = - CollectionUtils.containsAny(batchAssignmentName, resourceAssignment.getDependencies()); - } - - logger.trace("({}) -> Checking ({}), with ({}), result ({})", resourceAssignment.getName(), - batchAssignmentName, resourceAssignment.getDependencies(), dependencyPresence); - - if (previousResourceAssignment != null && resourceAssignment.getDictionarySource() != null - && resourceAssignment.getDictionarySource() - .equalsIgnoreCase(previousResourceAssignment.getDictionarySource()) - && !dependencyPresence) { - batchResourceAssignment.add(resourceAssignment); - batchAssignmentName.add(resourceAssignment.getName()); - } else { - if (batchResourceAssignment != null) { - sequenceBatchResourceAssignment.add(batchResourceAssignment); - logger.trace("Created old Set ({})", batchAssignmentName); - } - batchResourceAssignment = new ArrayList<>(); - batchResourceAssignment.add(resourceAssignment); - - batchAssignmentName = new ArrayList<>(); - batchAssignmentName.add(resourceAssignment.getName()); - } - } - - if (i == (sequencedResourceAssignments.size() - 1)) { - logger.trace("Created old Set ({})", batchAssignmentName); - sequenceBatchResourceAssignment.add(batchResourceAssignment); - } - } - logger.info("Batched Sequence : ({})", sequenceBatchResourceAssignment); - } - return sequenceBatchResourceAssignment; - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentNode.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentNode.java deleted file mode 100644 index 8ed0b71fc..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentNode.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * 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.assignment.service; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.ccsdk.config.assignment.ConfigAssignmentConstants; -import org.onap.ccsdk.config.assignment.data.ResourceAssignmentData; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.generator.service.ConfigGeneratorService; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.service.ComponentNode; -import org.onap.ccsdk.config.model.service.ComponentNodeService; -import org.onap.ccsdk.config.model.service.ConfigModelService; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.config.rest.adaptor.service.ConfigRestAdaptorService; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ConfigAssignmentNode implements ComponentNode { - private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentNode.class); - - private ComponentNodeService componentNodeService; - private ConfigResourceService configResourceService; - private ConfigModelService configModelService; - private ConfigRestAdaptorService configRestAdaptorService; - private ConfigGeneratorService configGeneratorService; - - public ConfigAssignmentNode(ConfigResourceService configResourceService, - ConfigRestAdaptorService configRestAdaptorService, ConfigModelService configModelService, - ComponentNodeService componentNodeService, ConfigGeneratorService configGeneratorService) { - logger.info("{} Constrctor Initiated", "ConfigAssignmentNode"); - this.componentNodeService = componentNodeService; - this.configResourceService = configResourceService; - this.configModelService = configModelService; - this.configRestAdaptorService = configRestAdaptorService; - this.configGeneratorService = configGeneratorService; - } - - @Override - public Boolean preCondition(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - return Boolean.TRUE; - } - - @Override - public void preProcess(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - // Auto-generated method stub - } - - /** - * This method is used to resolve the resources defined in the template. Generic Resource API DG - * calls this execute node. - * - * @param inParams This is the input parameter to process this node - * - *
-    request-id                  (string):           Tracking Id 
-    resource-type               (string):           Resource Type ( ex : vnf-type) 
-    resource-id                 (string):           Resource Id 
-    service-template-name       (string):           Blueprint Name 
-    service-template-version    (string):           Blueprint Version 
-    action-name                 (string): 
-    template-names              (List of string):   Template Names / Artifact Node Names to resolve. ["template1", "template2"] 
-    input-data                  (string):           Input Data in JSON String, for the substitution in the Template. 
-    prifix                      (string):           Return Value selector
-     *        
- * - * @param ctx This is the service logger context, Output will be stored ( - * .resource-assignment-params. : Output Data in JSON String. - * .status .error-message ) - * @throws SvcLogicException On processing error. - */ - - @Override - public void process(Map inParams, SvcLogicContext ctx) throws SvcLogicException { - - final String responsePrefix = StringUtils.isNotBlank(inParams.get(ConfigModelConstant.PROPERTY_SELECTOR)) - ? (inParams.get(ConfigModelConstant.PROPERTY_SELECTOR) + ".") - : ""; - try { - - ResourceAssignmentData resourceAssignmentData = populateResourceData(inParams); - resourceAssignmentData.setSvcLogicContext(ctx); - Map componentContext = new HashMap<>(); - resourceAssignmentData.setContext(componentContext); - resourceAssignmentData.setReloadModel(true); - - ConfigAssignmentProcessService configAssignmentProcessService = - new ConfigAssignmentProcessService(configResourceService, configRestAdaptorService, - configModelService, componentNodeService, configGeneratorService); - configAssignmentProcessService.resolveResources(resourceAssignmentData); - - if (MapUtils.isNotEmpty(resourceAssignmentData.getTemplatesMashedContents())) { - resourceAssignmentData.getTemplatesMashedContents().forEach((templateName, previewContent) -> { - logger.debug("For Template name : ({}),\n Preview Content is : ({})", templateName, previewContent); - ctx.setAttribute( - responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_MASHED_DATA + "." + templateName, - previewContent); - }); - } - ctx.setAttribute(responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_STATUS, - ConfigAssignmentConstants.OUTPUT_STATUS_SUCCESS); - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_STATUS, - ConfigAssignmentConstants.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - throw new SvcLogicException(e.getMessage(), e); - } - } - - @Override - public void process(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - - final String responsePrefix = StringUtils.isNotBlank(inParams.get(ConfigModelConstant.PROPERTY_SELECTOR)) - ? (inParams.get(ConfigModelConstant.PROPERTY_SELECTOR) + ".") - : ""; - try { - - ResourceAssignmentData resourceAssignmentData = populateResourceData(inParams); - resourceAssignmentData.setSvcLogicContext(ctx); - resourceAssignmentData.setContext(componentContext); - resourceAssignmentData.setReloadModel(false); - - ConfigAssignmentProcessService configAssignmentProcessService = - new ConfigAssignmentProcessService(configResourceService, configRestAdaptorService, - configModelService, componentNodeService, configGeneratorService); - configAssignmentProcessService.resolveResources(resourceAssignmentData); - ctx.setAttribute(responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_STATUS, - ConfigAssignmentConstants.OUTPUT_STATUS_SUCCESS); - - } catch (Exception e) { - ctx.setAttribute(responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_STATUS, - ConfigAssignmentConstants.OUTPUT_STATUS_FAILURE); - ctx.setAttribute(responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); - throw new SvcLogicException(e.getMessage(), e); - } - } - - @Override - public void postProcess(Map inParams, SvcLogicContext ctx, Map componentContext) - throws SvcLogicException { - // Do Nothing - } - - private ResourceAssignmentData populateResourceData(Map inParams) throws SvcLogicException { - validateInputParams(inParams); - - String requestId = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_REQUEST_ID); - String resourceId = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_ID); - String resourceType = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_TYPE); - String serviceTemplateName = inParams.get(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_NAME); - String serviceTemplateVersion = inParams.get(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_VERSION); - String actionName = inParams.get(ConfigModelConstant.PROPERTY_ACTION_NAME); - String inputData = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_INPUT_DATA); - - String templateNamesStr = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_TEMPLATE_NAMES); - List templateNames = TransformationUtils.getListfromJson(templateNamesStr, String.class); - - ResourceAssignmentData resourceAssignmentData = new ResourceAssignmentData(); - resourceAssignmentData.setRequestId(requestId); - resourceAssignmentData.setResourceId(resourceId); - resourceAssignmentData.setResourceType(resourceType); - resourceAssignmentData.setServiceTemplateName(serviceTemplateName); - resourceAssignmentData.setServiceTemplateVersion(serviceTemplateVersion); - resourceAssignmentData.setActionName(actionName); - resourceAssignmentData.setInputData(inputData); - resourceAssignmentData.setTemplateNames(templateNames); - - return resourceAssignmentData; - } - - private void validateInputParams(Map inParams) throws SvcLogicException { - if (inParams == null) { - throw new SvcLogicException("Input parameters missing"); - } - - String requestId = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_REQUEST_ID); - if (StringUtils.isBlank(requestId)) { - throw new SvcLogicException("Request id parameters missing"); - } - String resourceId = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_ID); - if (StringUtils.isBlank(resourceId)) { - throw new SvcLogicException("Resource id parameter is missing"); - } - String resourceType = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_TYPE); - if (StringUtils.isBlank(resourceType)) { - throw new SvcLogicException("Resource type parameter is missing"); - } - String recipeName = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_ACTION_NAME); - if (StringUtils.isBlank(recipeName)) { - throw new SvcLogicException("Action name is parameter is missing"); - } - String templateNames = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_TEMPLATE_NAMES); - if (StringUtils.isBlank(templateNames)) { - throw new SvcLogicException("Template names parameter missing"); - } - String serviceTemplateName = inParams.get(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_NAME); - if (StringUtils.isBlank(serviceTemplateName)) { - throw new SvcLogicException("Service Template name parameter missing"); - } - String serviceTemplateVersion = inParams.get(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_VERSION); - if (StringUtils.isBlank(serviceTemplateVersion)) { - throw new SvcLogicException("Service Template version parameter missing"); - } - - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentPersistService.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentPersistService.java deleted file mode 100644 index 320f4369b..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentPersistService.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * 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.assignment.service; - -import java.util.List; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.ccsdk.config.data.adaptor.DataAdaptorConstants; -import org.onap.ccsdk.config.data.adaptor.domain.ConfigResource; -import org.onap.ccsdk.config.data.adaptor.domain.ResourceAssignmentData; -import org.onap.ccsdk.config.data.adaptor.domain.TransactionLog; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.utils.ResourceAssignmentUtils; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ConfigAssignmentPersistService { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentPersistService.class); - - private ConfigResourceService configResourceService; - - public ConfigAssignmentPersistService(ConfigResourceService configResourceService) { - this.configResourceService = configResourceService; - } - - public void saveResourceMapping(org.onap.ccsdk.config.assignment.data.ResourceAssignmentData resourceAssignmentData, - String templateName, List resourceAssignments) throws SvcLogicException { - try { - - if (resourceAssignmentData == null) { - throw new SvcLogicException("Resource assignment data is missing"); - } - - if (StringUtils.isBlank(resourceAssignmentData.getRequestId())) { - logger.warn("Request Id ({}) is missing, may be getting request for resource update.", - resourceAssignmentData.getRequestId()); - } - - if (StringUtils.isBlank(resourceAssignmentData.getResourceId())) { - throw new SvcLogicException("Resource Id is missing"); - } - - if (StringUtils.isBlank(resourceAssignmentData.getResourceType())) { - throw new SvcLogicException("Resource type is missing"); - } - - if (StringUtils.isBlank(resourceAssignmentData.getActionName())) { - throw new SvcLogicException("Action name is missing"); - } - - if (StringUtils.isBlank(templateName)) { - throw new SvcLogicException("template name is missing"); - } - - StringBuilder builder = new StringBuilder(); - builder.append("Resource Assignment for Template Name :"); - builder.append(templateName); - builder.append("\n"); - builder.append(TransformationUtils.getJson(resourceAssignments, true)); - - configResourceService.save(new TransactionLog(resourceAssignmentData.getRequestId(), - DataAdaptorConstants.LOG_MESSAGE_TYPE_LOG, builder.toString())); - - // Resource Data should be Regenerated based on the new Updates - String resourceData = ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments); - - List resourceAssignmentDataList = - ConfigAssignmentUtils.convertResoureAssignmentList(resourceAssignments); - - ConfigResource configResource = new ConfigResource(); - configResource.setRequestId(resourceAssignmentData.getRequestId()); - configResource.setServiceTemplateName(resourceAssignmentData.getServiceTemplateName()); - configResource.setServiceTemplateVersion(resourceAssignmentData.getServiceTemplateVersion()); - configResource.setRecipeName(resourceAssignmentData.getActionName()); - configResource.setResourceId(resourceAssignmentData.getResourceId()); - configResource.setResourceType(resourceAssignmentData.getResourceType()); - configResource.setResourceData(resourceData); - configResource.setTemplateName(templateName); - configResource.setStatus(ConfigModelConstant.STATUS_SUCCESS); - configResource.setUpdatedBy(ConfigModelConstant.USER_SYSTEM); - - if (CollectionUtils.isNotEmpty(resourceAssignmentDataList)) { - configResource.setResourceAssignments(resourceAssignmentDataList); - } - configResource = configResourceService.saveConfigResource(configResource); - logger.info("Resource data saved successfully for the template ({}) with resource id ({})", templateName, - configResource.getResourceId()); - - builder = new StringBuilder(); - builder.append("Resource Data Template Name :"); - builder.append(templateName); - builder.append("\n"); - builder.append(resourceData); - configResourceService.save(new TransactionLog(resourceAssignmentData.getRequestId(), - DataAdaptorConstants.LOG_MESSAGE_TYPE_LOG, builder.toString())); - - } catch (Exception e) { - throw new SvcLogicException("ConfigAssignmentPersistService : " + e.getMessage(), e); - } - - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentProcessService.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentProcessService.java deleted file mode 100644 index 85ff82db6..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentProcessService.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * 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.assignment.service; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.ccsdk.config.assignment.ConfigAssignmentConstants; -import org.onap.ccsdk.config.assignment.data.ResourceAssignmentData; -import org.onap.ccsdk.config.assignment.processor.ProcessorFactory; -import org.onap.ccsdk.config.assignment.processor.ResourceAssignmentProcessor; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.generator.service.ConfigGeneratorService; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.data.dict.ResourceDefinition; -import org.onap.ccsdk.config.model.service.ComponentNode; -import org.onap.ccsdk.config.model.service.ComponentNodeService; -import org.onap.ccsdk.config.model.service.ConfigModelService; -import org.onap.ccsdk.config.model.utils.ResourceAssignmentUtils; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.config.rest.adaptor.service.ConfigRestAdaptorService; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ConfigAssignmentProcessService { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentProcessService.class); - - private ComponentNodeService componentNodeService; - private ConfigResourceService configResourceService; - private ConfigModelService configModelService; - private ConfigRestAdaptorService configRestAdaptorService; - private ConfigGeneratorService configGeneratorService; - - public ConfigAssignmentProcessService(ConfigResourceService configResourceService, - ConfigRestAdaptorService configRestAdaptorService, ConfigModelService configModelService, - ComponentNodeService componentNodeService, ConfigGeneratorService configGeneratorService) { - this.componentNodeService = componentNodeService; - this.configResourceService = configResourceService; - this.configModelService = configModelService; - this.configRestAdaptorService = configRestAdaptorService; - this.configGeneratorService = configGeneratorService; - } - - @SuppressWarnings("squid:S1141") - public void resolveResources(ResourceAssignmentData resourceAssignmentData) throws SvcLogicException { - try { - validateInputParams(resourceAssignmentData); - - String serviceTemplateName = resourceAssignmentData.getServiceTemplateName(); - String serviceTemplateVersion = resourceAssignmentData.getServiceTemplateVersion(); - String actionName = resourceAssignmentData.getActionName(); - String inputData = resourceAssignmentData.getInputData(); - SvcLogicContext svcLogicContext = resourceAssignmentData.getSvcLogicContext(); - List templateNames = resourceAssignmentData.getTemplateNames(); - - if (resourceAssignmentData.isReloadModel()) { - Map context = new HashMap<>(); - context.put(ConfigModelConstant.PROPERTY_ACTION_NAME, actionName); - context = configModelService.prepareContext(context, inputData, serviceTemplateName, - serviceTemplateVersion); - context.forEach((key, value) -> svcLogicContext.setAttribute(key, value)); - logger.info("List of Resources provided in input: {}", svcLogicContext.toProperties()); - } - - Map componentContext = resourceAssignmentData.getContext(); - - if (CollectionUtils.isNotEmpty(templateNames)) { - // Get the Resource Assignments for templates and Validate the mappings - ResourceModelService resourceModelService = new ResourceModelService(configModelService); - - // Get the Resource Assignment - Map> templatesResourceAssignments = - resourceModelService.getTemplatesResourceAssignments(svcLogicContext, templateNames); - - // Get the Template Contents - Map templatesContents = - resourceModelService.getTemplatesContents(svcLogicContext, templateNames); - - // Process each template - for (String templateName : templateNames) { - List resourceAssignments = templatesResourceAssignments.get(templateName); - String templateContent = templatesContents.get(templateName); - if (resourceAssignments != null) { - String templateData = null; - try { - // Populate the Dictionary - ResourceDictionaryService resourceDictionaryService = - new ResourceDictionaryService(configRestAdaptorService); - Map dictionaries = - resourceDictionaryService.getDataDictionaryDefinitions(resourceAssignments); - - processResourceAssignments(resourceAssignmentData, svcLogicContext, componentContext, - templateName, resourceAssignments, dictionaries); - - logger.info("decrypting config data for templateName {}", templateName); - templateData = - ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments); - } finally { - saveResourceMapping(resourceAssignmentData, templateName, resourceAssignments); - } - - logger.info("generating config preview for templateName {}", templateName); - ConfigPreviewService configPreviewService = new ConfigPreviewService(configResourceService, - configModelService, configGeneratorService); - String mashedData = configPreviewService.generatePreview(templateContent, templateData); - resourceAssignmentData.getTemplatesMashedContents().put(templateName, mashedData); - resourceAssignmentData.getTemplatesData().put(templateName, templateData); - - } else { - // Do nothing for Mapping not found - logger.warn("No resource Assignment mappings to resolve for templateName {}", templateName); - } - } - } - - } catch (Exception e) { - throw new SvcLogicException(e.getMessage(), e); - } - } - - private void processResourceAssignments(ResourceAssignmentData resourceAssignmentData, SvcLogicContext ctx, - Map componentContext, String templateName, List resourceAssignments, - Map dictionaries) throws SvcLogicException { - - String recipeName = resourceAssignmentData.getActionName(); - - ResourceAssignmentProcessor resourceAssignmentProcessor = - new ResourceAssignmentProcessor(resourceAssignments, ctx); - List> sequenceBatchResourceAssignment = resourceAssignmentProcessor.process(); - - logger.debug("Resource dictionary Info ({})", dictionaries); - - if (sequenceBatchResourceAssignment != null) { - componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); - componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, templateName); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); - for (List batchResourceAssignment : sequenceBatchResourceAssignment) { - - processBatchResourceAssignments(resourceAssignmentData, ctx, componentContext, batchResourceAssignment); - - logger.debug("Batch Resource data status ({})", TransformationUtils.getJson(batchResourceAssignment)); - } - } - } - - private void processBatchResourceAssignments(ResourceAssignmentData resourceAssignmentData, SvcLogicContext ctx, - Map componentContext, List batchResourceAssignment) - throws SvcLogicException { - - if (CollectionUtils.isNotEmpty(batchResourceAssignment)) { - - ResourceAssignment batchFirstResourceAssignment = batchResourceAssignment.get(0); - if (batchFirstResourceAssignment != null - && StringUtils.isNotBlank(batchFirstResourceAssignment.getDictionarySource())) { - String source = batchFirstResourceAssignment.getDictionarySource(); - // Processing their Source - logger.info("Processing source ({}) with batch ({}) ", source, batchResourceAssignment); - componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); - - ProcessorFactory factory = - new ProcessorFactory(configResourceService, configRestAdaptorService, componentNodeService); - - ComponentNode processor = factory.getInstance(source); - - Map inParams = new HashMap<>(); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_REQUEST_ID, resourceAssignmentData.getRequestId()); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_ID, resourceAssignmentData.getResourceId()); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_TYPE, - resourceAssignmentData.getResourceType()); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_ACTION_NAME, resourceAssignmentData.getActionName()); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_TEMPLATE_NAMES, - resourceAssignmentData.getTemplateNames().toString()); - processor.process(inParams, ctx, componentContext); - } - } - } - - private void saveResourceMapping(ResourceAssignmentData resourceAssignmentData, String templateName, - List resourceAssignments) throws SvcLogicException { - if (resourceAssignmentData != null && StringUtils.isNotBlank(templateName)) { - - ConfigAssignmentPersistService configAssignmentPersistService = - new ConfigAssignmentPersistService(configResourceService); - configAssignmentPersistService.saveResourceMapping(resourceAssignmentData, templateName, - resourceAssignments); - } - } - - private void validateInputParams(ResourceAssignmentData resourceAssignmentData) throws SvcLogicException { - if (resourceAssignmentData == null) { - throw new SvcLogicException("Input parameters missing"); - } - - String requestId = resourceAssignmentData.getRequestId(); - if (StringUtils.isBlank(requestId)) { - throw new SvcLogicException("Request id parameters missing"); - } - String resourceId = resourceAssignmentData.getResourceId(); - if (StringUtils.isBlank(resourceId)) { - throw new SvcLogicException("Resource id parameter is missing"); - } - String resourceType = resourceAssignmentData.getResourceType(); - if (StringUtils.isBlank(resourceType)) { - throw new SvcLogicException("Resource type parameter is missing"); - } - String actionName = resourceAssignmentData.getActionName(); - if (StringUtils.isBlank(actionName)) { - throw new SvcLogicException("Action name is parameter is missing"); - } - - List templatesNames = resourceAssignmentData.getTemplateNames(); - if (CollectionUtils.isEmpty(templatesNames)) { - throw new SvcLogicException("Template names parameter missing"); - } - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentService.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentService.java deleted file mode 100644 index 4866f258b..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentService.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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.assignment.service; - -import java.util.List; -import org.onap.ccsdk.config.assignment.data.ResourceAssignmentData; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; - -public interface ConfigAssignmentService { - - public void resolveResources(ResourceAssignmentData resourceAssignmentData) throws SvcLogicException; - - public void saveResourceMapping(ResourceAssignmentData resourceAssignmentData, String templateName, - List resourceAssignments) throws SvcLogicException; - - public ResourceAssignmentData generateTemplateResourceMash(ResourceAssignmentData resourceAssignmentData) - throws SvcLogicException; - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentServiceImpl.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentServiceImpl.java deleted file mode 100644 index 9e2bdcf8d..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentServiceImpl.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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.assignment.service; - -import java.util.List; -import org.onap.ccsdk.config.assignment.data.ResourceAssignmentData; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.generator.service.ConfigGeneratorService; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.service.ComponentNodeService; -import org.onap.ccsdk.config.model.service.ConfigModelService; -import org.onap.ccsdk.config.rest.adaptor.service.ConfigRestAdaptorService; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ConfigAssignmentServiceImpl implements ConfigAssignmentService { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentServiceImpl.class); - - private ComponentNodeService componentNodeService; - private ConfigResourceService configResourceService; - private ConfigModelService configModelService; - private ConfigRestAdaptorService configRestAdaptorService; - private ConfigGeneratorService configGeneratorService; - - private static final String CLASS_NAME = "ConfigAssignmentServiceImpl"; - - public ConfigAssignmentServiceImpl(ConfigResourceService configResourceService, - ConfigRestAdaptorService configRestAdaptorService, ConfigModelService configModelService, - ComponentNodeService componentNodeService, ConfigGeneratorService configGeneratorService) { - logger.info("{} Constuctor Initated...", CLASS_NAME); - this.componentNodeService = componentNodeService; - this.configResourceService = configResourceService; - this.configModelService = configModelService; - this.configRestAdaptorService = configRestAdaptorService; - this.configGeneratorService = configGeneratorService; - } - - @Override - public void resolveResources(ResourceAssignmentData resourceAssignmentData) throws SvcLogicException { - ConfigAssignmentProcessService configAssignmentProcessService = - new ConfigAssignmentProcessService(configResourceService, configRestAdaptorService, configModelService, - componentNodeService, configGeneratorService); - configAssignmentProcessService.resolveResources(resourceAssignmentData); - } - - @Override - public void saveResourceMapping(ResourceAssignmentData resourceAssignmentData, String templateName, - List resourceAssignments) throws SvcLogicException { - ConfigAssignmentPersistService configAssignmentPersistService = - new ConfigAssignmentPersistService(configResourceService); - configAssignmentPersistService.saveResourceMapping(resourceAssignmentData, templateName, resourceAssignments); - } - - @Override - public ResourceAssignmentData generateTemplateResourceMash(ResourceAssignmentData resourceAssignmentData) - throws SvcLogicException { - ConfigPreviewService configPreviewService = - new ConfigPreviewService(configResourceService, configModelService, configGeneratorService); - return configPreviewService.generateTemplateResourceMash(resourceAssignmentData); - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentUtils.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentUtils.java deleted file mode 100644 index 32adbe249..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentUtils.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * 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.assignment.service; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.IteratorUtils; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.ccsdk.config.data.adaptor.domain.ResourceAssignmentData; -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.DataType; -import org.onap.ccsdk.config.model.data.EntrySchema; -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.domain.ResourceDictionary; -import org.onap.ccsdk.config.model.utils.JsonUtils; -import org.onap.ccsdk.config.model.utils.ResourceAssignmentUtils; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import com.fasterxml.jackson.databind.node.ObjectNode; - -public class ConfigAssignmentUtils { - - private ConfigAssignmentUtils() { - - } - - private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentUtils.class); - - public static synchronized Object getContextKeyValue(SvcLogicContext context, String key) { - Object value = null; - if (context != null && key != null) { - if (context.getAttributeKeySet().contains(key)) { - String strValue = context.getAttribute(key); - if (StringUtils.isNotBlank(strValue)) { - value = strValue; - } - } else { - // Do Nothing - } - } - return value; - } - - /* - * Populate the Field property type for the Data type - */ - public static synchronized String getPropertyType(SvcLogicContext ctx, String dataTypeName, String propertyName) - throws SvcLogicException { - String type = ValidTypes.DATA_TYPE_STRING; - try { - if (ctx != null && StringUtils.isNotBlank(dataTypeName) && StringUtils.isNotBlank(propertyName)) { - String dataTypeContent = ctx.getAttribute(ConfigModelConstant.PROPERTY_DATA_TYPES_DOT + dataTypeName); - if (StringUtils.isNotBlank(dataTypeContent)) { - DataType dataType = TransformationUtils.readValue(dataTypeContent, DataType.class); - if (dataType != null && dataType.getProperties() != null - && dataType.getProperties().containsKey(propertyName)) { - PropertyDefinition propertyDefinition = dataType.getProperties().get(propertyName); - if (StringUtils.isNotBlank(propertyDefinition.getType())) { - type = propertyDefinition.getType(); - logger.trace("Data type({})'s property ({}) is ({})", dataTypeName, propertyName, type); - } else { - throw new SvcLogicException(String.format("Couldn't get data type (%s) ", dataTypeName)); - } - } - } else { - throw new SvcLogicException(String.format("Couldn't get data type (%s) content", dataTypeName)); - } - } - } catch (Exception e) { - logger.error("couldn't get data type({})'s property ({}), type ({}), error message ({}).", dataTypeName, - propertyName, type, e.getMessage()); - throw new SvcLogicException(e.getMessage()); - } - return type; - } - - /* - * Populate the Field property type for the Data type - */ - public static synchronized PropertyDefinition getPropertyDefinition(SvcLogicContext ctx, String dataTypeName, - String propertyName) throws SvcLogicException { - PropertyDefinition propertyDefinition = null; - try { - if (ctx != null && StringUtils.isNotBlank(dataTypeName) && StringUtils.isNotBlank(propertyName)) { - String dataTypeContent = ctx.getAttribute(ConfigModelConstant.PROPERTY_DATA_TYPES_DOT + dataTypeName); - if (StringUtils.isNotBlank(dataTypeContent)) { - DataType dataType = TransformationUtils.readValue(dataTypeContent, DataType.class); - if (dataType != null && dataType.getProperties() != null - && dataType.getProperties().containsKey(propertyName)) { - propertyDefinition = dataType.getProperties().get(propertyName); - if (propertyDefinition == null) { - throw new SvcLogicException(String.format("couldn't get data type (%s) ", dataTypeName)); - } - } - } else { - throw new SvcLogicException(String.format("couldn't get data type (%s) content.", dataTypeName)); - } - } - } catch (Exception e) { - throw new SvcLogicException(e.getMessage()); - } - return propertyDefinition; - } - - public static synchronized ResourceDefinition getDictionaryDefinition(Map dictionaries, - String dictionaryName) { - ResourceDefinition resourceDefinition = null; - if (dictionaries != null && StringUtils.isNotBlank(dictionaryName)) { - ResourceDictionary resourceDictionary = dictionaries.get(dictionaryName); - if (resourceDictionary != null && StringUtils.isNotBlank(resourceDictionary.getDefinition())) { - resourceDefinition = - TransformationUtils.readValue(resourceDictionary.getDefinition(), ResourceDefinition.class); - } - } - return resourceDefinition; - } - - @SuppressWarnings("squid:S3776") - public static synchronized void populateValueForOutputMapping(SvcLogicContext ctx, - Map componentContext, ResourceAssignment resourceAssignment, - Map outputKeyMapping, JsonNode responseNode) - throws ConfigModelException, SvcLogicException { - if (resourceAssignment == null) { - throw new SvcLogicException("resourceAssignment is null."); - } - - if (ctx == null) { - throw new SvcLogicException("service logic context is null."); - } - - if (componentContext == null) { - throw new SvcLogicException("component context is null."); - } - - logger.info("populating value for output mapping ({}), from json ({})", outputKeyMapping, responseNode); - String dictionaryName = resourceAssignment.getDictionaryName(); - String type = resourceAssignment.getProperty().getType(); - - String entrySchema = null; - if (ValidTypes.getPrimitivePropertType().contains(type)) { - ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, responseNode); - } else if (ValidTypes.getListPropertType().contains(type)) { - // Array Types - if (resourceAssignment.getProperty().getEntrySchema() != null) { - entrySchema = resourceAssignment.getProperty().getEntrySchema().getType(); - } - - if (StringUtils.isNotBlank(entrySchema)) { - ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode(); - if (ValidTypes.getPrimitivePropertType().contains(entrySchema)) { - arrayNode = (ArrayNode) responseNode; - } else if (MapUtils.isNotEmpty(outputKeyMapping)) { - List responseArrayNode = IteratorUtils.toList(responseNode.elements()); - for (JsonNode responseSingleJsonNode : responseArrayNode) { - if (responseSingleJsonNode != null) { - ObjectNode arrayChildNode = JsonNodeFactory.instance.objectNode(); - for (Map.Entry mapping : outputKeyMapping.entrySet()) { - JsonNode responseKeyValue = responseSingleJsonNode.get(mapping.getKey()); - - String propertyTypeForDataType = - ConfigAssignmentUtils.getPropertyType(ctx, entrySchema, mapping.getKey()); - logger.info("For List Type Resource: key ({}), value ({}), type ({})", - mapping.getKey(), responseKeyValue, propertyTypeForDataType); - JsonUtils.populateJsonNodeValues(mapping.getValue(), responseKeyValue, - propertyTypeForDataType, arrayChildNode); - } - arrayNode.add(arrayChildNode); - } - } - } else { - arrayNode = (ArrayNode) responseNode; - } - // Set the List of Complex Values - ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, arrayNode); - } else { - throw new SvcLogicException( - String.format("Entry schema is not defined for dictionary (%s) info", dictionaryName)); - } - } else { - // Complex Types - ObjectNode objectNode = null; - if (MapUtils.isNotEmpty(outputKeyMapping)) { - objectNode = JsonNodeFactory.instance.objectNode(); - for (Map.Entry mapping : outputKeyMapping.entrySet()) { - JsonNode responseKeyValue = responseNode.get(mapping.getKey()); - String propertyTypeForDataType = - ConfigAssignmentUtils.getPropertyType(ctx, entrySchema, mapping.getKey()); - logger.info("For Complex Type Resource: key ({}), value ({}), type ({})", mapping.getKey(), - responseKeyValue, propertyTypeForDataType); - JsonUtils.populateJsonNodeValues(mapping.getValue(), responseKeyValue, propertyTypeForDataType, - objectNode); - } - } else { - objectNode = (ObjectNode) responseNode; - } - ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, objectNode); - } - } - - @SuppressWarnings("squid:S3776") - public static synchronized List convertResoureAssignmentDataList( - List resourceAssignmentDataList) { - List assignments = new ArrayList<>(); - if (CollectionUtils.isNotEmpty(resourceAssignmentDataList)) { - for (ResourceAssignmentData resourceAssignmentData : resourceAssignmentDataList) { - if (resourceAssignmentData != null) { - ResourceAssignment resourceAssignment = new ResourceAssignment(); - resourceAssignment.setName(resourceAssignmentData.getTemplateKeyName()); - resourceAssignment.setVersion(resourceAssignmentData.getVersion()); - resourceAssignment.setUpdatedBy(resourceAssignmentData.getUpdatedBy()); - resourceAssignment.setUpdatedDate(resourceAssignmentData.getUpdatedDate()); - resourceAssignment.setDictionaryName(resourceAssignmentData.getResourceName()); - resourceAssignment.setDictionarySource(resourceAssignmentData.getSource()); - resourceAssignment.setStatus(resourceAssignmentData.getStatus()); - resourceAssignment.setMessage(resourceAssignmentData.getMessage()); - PropertyDefinition property = new PropertyDefinition(); - property.setType(resourceAssignmentData.getDataType()); - - if (StringUtils.isNotBlank(resourceAssignmentData.getResourceValue())) { - if (ValidTypes.getPrimitivePropertType().contains(resourceAssignmentData.getDataType())) { - property.setValue(resourceAssignmentData.getResourceValue()); - } else { - JsonNode valueNode = - TransformationUtils.getJsonNodeForString(resourceAssignmentData.getResourceValue()); - property.setValue(valueNode); - } - } - if (StringUtils.isNotBlank(resourceAssignmentData.getEntrySchema())) { - EntrySchema entrySchema = new EntrySchema(); - entrySchema.setType(resourceAssignmentData.getEntrySchema()); - property.setEntrySchema(entrySchema); - } else { - property.setEntrySchema(null); - } - resourceAssignment.setProperty(property); - assignments.add(resourceAssignment); - } - } - - } - return assignments; - } - - @SuppressWarnings("squid:S3776") - public static synchronized List convertResoureAssignmentList( - List assignments) { - List resourceAssignmentDataList = new ArrayList<>(); - if (CollectionUtils.isNotEmpty(assignments)) { - for (ResourceAssignment assignment : assignments) { - if (assignment != null) { - ResourceAssignmentData resourceAssignmentData = new ResourceAssignmentData(); - resourceAssignmentData.setTemplateKeyName(assignment.getName()); - resourceAssignmentData.setVersion(assignment.getVersion()); - resourceAssignmentData.setUpdatedBy(assignment.getUpdatedBy()); - resourceAssignmentData.setUpdatedDate(assignment.getUpdatedDate()); - if (assignment.getProperty() != null) { - resourceAssignmentData.setDataType(assignment.getProperty().getType()); - if (assignment.getProperty().getEntrySchema() != null) { - resourceAssignmentData.setEntrySchema(assignment.getProperty().getEntrySchema().getType()); - } - if (assignment.getProperty().getValue() != null) { - String valueContent = TransformationUtils.getJson(assignment.getProperty().getValue()); - resourceAssignmentData.setResourceValue(valueContent); - } - } - resourceAssignmentData.setResourceName(assignment.getDictionaryName()); - resourceAssignmentData.setSource(assignment.getDictionarySource()); - resourceAssignmentData.setStatus(assignment.getStatus()); - resourceAssignmentData.setMessage(assignment.getMessage()); - resourceAssignmentDataList.add(resourceAssignmentData); - } - } - } - return resourceAssignmentDataList; - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigPreviewService.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigPreviewService.java deleted file mode 100644 index ae5c01c88..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ConfigPreviewService.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * 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.assignment.service; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.ccsdk.config.assignment.data.ResourceAssignmentData; -import org.onap.ccsdk.config.data.adaptor.domain.ConfigResource; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.generator.data.ConfigGeneratorInfo; -import org.onap.ccsdk.config.generator.service.ConfigGeneratorService; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.service.ConfigModelService; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ConfigPreviewService { - private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentPersistService.class); - private ConfigResourceService configResourceService; - private ConfigModelService configModelService; - private ConfigGeneratorService configGeneratorService; - - public ConfigPreviewService(ConfigResourceService configResourceService, ConfigModelService configModelService, - ConfigGeneratorService configGeneratorService) { - this.configResourceService = configResourceService; - this.configModelService = configModelService; - this.configGeneratorService = configGeneratorService; - } - - public String generatePreview(String templateContent, String templateData) throws SvcLogicException { - String mashedData = ""; - ConfigGeneratorInfo configGeneratorInfo = - configGeneratorService.generateConfiguration(templateContent, templateData); - if (configGeneratorInfo != null) { - mashedData = configGeneratorInfo.getMashedData(); - } - return mashedData; - } - - public ResourceAssignmentData generateTemplateResourceMash(ResourceAssignmentData resourceAssignmentData) - throws SvcLogicException { - if (resourceAssignmentData == null) { - throw new SvcLogicException("Resource assignment data is missing"); - } - if (StringUtils.isBlank(resourceAssignmentData.getServiceTemplateName())) { - throw new SvcLogicException("Service template name is missing"); - } - if (StringUtils.isBlank(resourceAssignmentData.getServiceTemplateVersion())) { - throw new SvcLogicException("Service template version is missing"); - } - if (StringUtils.isBlank(resourceAssignmentData.getResourceType())) { - throw new SvcLogicException("Resource type is missing"); - } - if (StringUtils.isBlank(resourceAssignmentData.getResourceId())) { - throw new SvcLogicException("Resource Id is missing"); - } - if (StringUtils.isBlank(resourceAssignmentData.getActionName())) { - throw new SvcLogicException("Action name is missing"); - } - - String serviceTemplateName = resourceAssignmentData.getServiceTemplateName(); - String serviceTemplateVersion = resourceAssignmentData.getServiceTemplateVersion(); - String actionName = resourceAssignmentData.getActionName(); - String resourceId = resourceAssignmentData.getResourceId(); - String resourceType = resourceAssignmentData.getResourceType(); - String inputData = "{}"; - - Map context = new HashMap<>(); - context.put(ConfigModelConstant.PROPERTY_ACTION_NAME, actionName); - context = configModelService.prepareContext(context, inputData, serviceTemplateName, serviceTemplateVersion); - - ConfigResource configResourceQuery = new ConfigResource(); - configResourceQuery.setServiceTemplateVersion(serviceTemplateName); - configResourceQuery.setServiceTemplateVersion(serviceTemplateVersion); - configResourceQuery.setRecipeName(actionName); - configResourceQuery.setResourceId(resourceId); - configResourceQuery.setResourceType(resourceType); - - List configResources = configResourceService.getConfigResource(configResourceQuery); - if (CollectionUtils.isNotEmpty(configResources)) { - for (ConfigResource cr : configResources) { - String templateContent = context - .get(ConfigModelConstant.PROPERTY_NODE_TEMPLATES_DOT + cr.getTemplateName() + ".content"); - String templateData = cr.getResourceData(); - String previewContent = generatePreview(templateContent, templateData); - resourceAssignmentData.getTemplatesMashedContents().put(cr.getTemplateName(), previewContent); - logger.info("Preview generated for template name ({}) ", cr.getTemplateName()); - logger.trace("Preview generated for preview ({}) ", previewContent); - } - } else { - logger.info( - "Couldn't get config resource for service template name ({}) service template version ({})" - + " action ({}) resource id ({}) resource type ({})", - serviceTemplateName, serviceTemplateVersion, actionName, resourceId, resourceType); - } - return resourceAssignmentData; - - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ResourceDictionaryService.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ResourceDictionaryService.java deleted file mode 100644 index 50562b0e8..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ResourceDictionaryService.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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.assignment.service; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.lang3.StringUtils; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.data.dict.ResourceDefinition; -import org.onap.ccsdk.config.model.domain.ResourceDictionary; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.config.rest.adaptor.ConfigRestAdaptorConstants; -import org.onap.ccsdk.config.rest.adaptor.ConfigRestAdaptorException; -import org.onap.ccsdk.config.rest.adaptor.service.ConfigRestAdaptorService; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ResourceDictionaryService { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(ResourceDictionaryService.class); - private ConfigRestAdaptorService configRestAdaptorService; - - public ResourceDictionaryService(ConfigRestAdaptorService configRestAdaptorService) { - this.configRestAdaptorService = configRestAdaptorService; - } - - @SuppressWarnings("squid:S3776") - public Map getDataDictionaryDefinitions(List resourceAssignments) - throws SvcLogicException { - try { - Map dictionaries = new HashMap<>(); - if (resourceAssignments != null) { - List names = new ArrayList<>(); - for (ResourceAssignment resourceAssignment : resourceAssignments) { - if (resourceAssignment != null && StringUtils.isNotBlank(resourceAssignment.getDictionaryName())) { - - if (!names.contains(resourceAssignment.getDictionaryName())) { - names.add(resourceAssignment.getDictionaryName()); - } - - if (resourceAssignment.getDependencies() != null - && !resourceAssignment.getDependencies().isEmpty()) { - List dependencieNames = resourceAssignment.getDependencies(); - for (String dependencieName : dependencieNames) { - if (StringUtils.isNotBlank(dependencieName) && !names.contains(dependencieName)) { - names.add(dependencieName); - } - } - } - } - } - queryResourceDictionaryDefinitions(dictionaries, names); - } - return dictionaries; - } catch (Exception e) { - throw new SvcLogicException("Failed in getting resource data dictionary : " + e.getMessage()); - } - - } - - @SuppressWarnings("squid:S3776") - private void queryResourceDictionaryDefinitions(Map dictionaries, List names) - throws SvcLogicException, ConfigRestAdaptorException { - logger.info("Getting resource dictionary definition for the names ({})", names); - if (!names.isEmpty()) { - - String dictionaryContents = configRestAdaptorService.postResource( - ConfigRestAdaptorConstants.SELECTOR_MODEL_SERVICE, "dictionarybynames", names, String.class); - - if (StringUtils.isNotBlank(dictionaryContents)) { - List dataDictionaries = - TransformationUtils.getListfromJson(dictionaryContents, ResourceDictionary.class); - if (dataDictionaries != null) { - for (ResourceDictionary dataDictionary : dataDictionaries) { - if (dataDictionary != null && StringUtils.isNotBlank(dataDictionary.getName()) - && StringUtils.isNotBlank(dataDictionary.getDefinition())) { - ResourceDefinition resourceDefinition = TransformationUtils - .readValue(dataDictionary.getDefinition(), ResourceDefinition.class); - if (resourceDefinition != null && StringUtils.isNotBlank(resourceDefinition.getName())) { - dictionaries.put(resourceDefinition.getName(), resourceDefinition); - } else { - throw new SvcLogicException( - "Failed in getting resource data dictionary definition for : " - + dataDictionary.getName()); - } - } - } - } - } else { - logger.warn("No resource dictionary definition found for the names ({})", names); - } - } - } -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ResourceModelService.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ResourceModelService.java deleted file mode 100644 index 9f3013b73..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/config/assignment/service/ResourceModelService.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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.assignment.service; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.service.ConfigModelService; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.config.model.validator.ResourceAssignmentValidator; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ResourceModelService { - private static EELFLogger logger = EELFManager.getInstance().getLogger(ResourceModelService.class); - - private ConfigModelService configModelService; - - public ResourceModelService(ConfigModelService configModelService) { - this.configModelService = configModelService; - } - - public Map getTemplatesContents(SvcLogicContext ctx, List templateNames) - throws SvcLogicException { - Map templatesContents = new HashMap<>(); - try { - if (CollectionUtils.isNotEmpty(templateNames)) { - for (String templateName : templateNames) { - String templateContent = this.configModelService.getNodeTemplateContent(ctx, templateName); - logger.trace("Processing template ({}) with content : {}", templateName, templateContent); - templatesContents.put(templateName, templateContent); - } - } - } catch (Exception e) { - throw new SvcLogicException(e.getMessage()); - } - return templatesContents; - } - - public Map> getTemplatesResourceAssignments(SvcLogicContext ctx, - List templateNames) throws SvcLogicException { - Map> templatesResourceAssignments = new HashMap<>(); - try { - if (CollectionUtils.isNotEmpty(templateNames)) { - for (String templateName : templateNames) { - String resourceMappingContent = this.configModelService.getNodeTemplateMapping(ctx, templateName); - logger.info("Processing template ({}) with resource assignment content : {}", templateName, - resourceMappingContent); - - if (StringUtils.isNotBlank(resourceMappingContent)) { - - List resourceAssignments = - TransformationUtils.getListfromJson(resourceMappingContent, ResourceAssignment.class); - - if (resourceAssignments != null) { - ResourceAssignmentValidator resourceAssignmentValidator = - new ResourceAssignmentValidator(resourceAssignments); - resourceAssignmentValidator.validateResourceAssignment(); - logger.info("Resource assignment validated successfully for the template ({})", - templateName); - templatesResourceAssignments.put(templateName, resourceAssignments); - } else { - throw new SvcLogicException(String.format( - "Failed to convert assignment content (%s) to object", resourceMappingContent)); - } - } else { - // Do nothing, because som e templates may not have mappings - } - } - } - } catch (Exception e) { - throw new SvcLogicException(e.getMessage()); - } - - return templatesResourceAssignments; - } -} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/ConfigAssignmentConstants.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/ConfigAssignmentConstants.java new file mode 100644 index 000000000..3052a8611 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/ConfigAssignmentConstants.java @@ -0,0 +1,37 @@ +/* + * 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.features.assignment; + +@SuppressWarnings("squid:S1118") +public class ConfigAssignmentConstants { + + public static final String OUTPUT_PARAM_STATUS = "status"; + public static final String OUTPUT_PARAM_RESOURCE_ASSIGNMENT_PARAMS = "resource-assignment-params"; + public static final String OUTPUT_PARAM_MASHED_DATA = "mashed-data"; + public static final String OUTPUT_PARAM_ERROR_MESSAGE = "error-message"; + public static final String OUTPUT_STATUS_SUCCESS = "success"; + public static final String OUTPUT_STATUS_FAILURE = "failure"; + + public static final String INPUT_PARAM_REQUEST_ID = "request-id"; + public static final String INPUT_PARAM_RESOURCE_ID = "resource-id"; + public static final String INPUT_PARAM_RESOURCE_TYPE = "resource-type"; + public static final String INPUT_PARAM_ACTION_NAME = "action-name"; + public static final String INPUT_PARAM_TEMPLATE_NAMES = "template-names"; + public static final String INPUT_PARAM_INPUT_DATA = "input-data"; + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/data/ResourceAssignmentData.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/data/ResourceAssignmentData.java new file mode 100644 index 000000000..2bd067461 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/data/ResourceAssignmentData.java @@ -0,0 +1,164 @@ +/* + * 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.features.assignment.data; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +public class ResourceAssignmentData { + + private String requestId; + private boolean reloadModel; + private String resourceType; + private String resourceId; + private String serviceTemplateName; + private String serviceTemplateVersion; + private String actionName; + private String inputData; + private SvcLogicContext svcLogicContext; + private List templateNames; + private Map> templatesResourceAssignments = new HashMap<>(); + private Map templatesContents = new HashMap<>(); + private Map templatesMashedContents = new HashMap<>(); + private Map templatesData = new HashMap<>(); + private Map context = new HashMap<>(); + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public String getResourceId() { + return resourceId; + } + + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + + public String getServiceTemplateName() { + return serviceTemplateName; + } + + public void setServiceTemplateName(String serviceTemplateName) { + this.serviceTemplateName = serviceTemplateName; + } + + public String getServiceTemplateVersion() { + return serviceTemplateVersion; + } + + public void setServiceTemplateVersion(String serviceTemplateVersion) { + this.serviceTemplateVersion = serviceTemplateVersion; + } + + public String getActionName() { + return actionName; + } + + public void setActionName(String actionName) { + this.actionName = actionName; + } + + public String getInputData() { + return inputData; + } + + public void setInputData(String inputData) { + this.inputData = inputData; + } + + public List getTemplateNames() { + return templateNames; + } + + public void setTemplateNames(List templateNames) { + this.templateNames = templateNames; + } + + public Map> getTemplatesResourceAssignments() { + return templatesResourceAssignments; + } + + public void setTemplatesResourceAssignments(Map> templatesResourceAssignments) { + this.templatesResourceAssignments = templatesResourceAssignments; + } + + public Map getTemplatesContents() { + return templatesContents; + } + + public void setTemplatesContents(Map templatesContents) { + this.templatesContents = templatesContents; + } + + public Map getTemplatesMashedContents() { + return templatesMashedContents; + } + + public void setTemplatesMashedContents(Map templatesMashedContents) { + this.templatesMashedContents = templatesMashedContents; + } + + public Map getTemplatesData() { + return templatesData; + } + + public void setTemplatesData(Map templatesData) { + this.templatesData = templatesData; + } + + public Map getContext() { + return context; + } + + public void setContext(Map context) { + this.context = context; + } + + public SvcLogicContext getSvcLogicContext() { + return svcLogicContext; + } + + public void setSvcLogicContext(SvcLogicContext svcLogicContext) { + this.svcLogicContext = svcLogicContext; + } + + public boolean isReloadModel() { + return reloadModel; + } + + public void setReloadModel(boolean reloadModel) { + this.reloadModel = reloadModel; + } +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/DBResourceProcessor.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/DBResourceProcessor.java new file mode 100644 index 000000000..132d03c4f --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/DBResourceProcessor.java @@ -0,0 +1,267 @@ +/* + * 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.features.assignment.processor; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.features.assignment.service.ConfigAssignmentUtils; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.ConfigModelException; +import org.onap.ccsdk.features.model.ValidTypes; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.data.dict.ResourceDefinition; +import org.onap.ccsdk.features.model.data.dict.SourcesDefinition; +import org.onap.ccsdk.features.model.service.ComponentNode; +import org.onap.ccsdk.features.model.utils.JsonUtils; +import org.onap.ccsdk.features.model.utils.ResourceAssignmentUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public class DBResourceProcessor implements ComponentNode { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(DBResourceProcessor.class); + private ConfigResourceService configResourceService; + private Map dictionaries; + + public DBResourceProcessor(ConfigResourceService configResourceService) { + this.configResourceService = configResourceService; + } + + @Override + public Boolean preCondition(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + return Boolean.TRUE; + } + + @Override + public void preProcess(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + // Auto-generated method stub + } + + @Override + public void process(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + // Auto-generated method stub + } + + @SuppressWarnings("unchecked") + @Override + public void process(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + try { + List batchResourceAssignment = + (List) componentContext.get(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS); + dictionaries = + (Map) componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARIES); + + if (CollectionUtils.isNotEmpty(batchResourceAssignment)) { + for (ResourceAssignment resourceAssignment : batchResourceAssignment) { + processResourceAssignment(ctx, componentContext, resourceAssignment); + } + } + } catch (Exception e) { + throw new SvcLogicException(String.format("DBResourceProcessor Exception : (%s)", e), e); + } + } + + private void processResourceAssignment(SvcLogicContext ctx, Map componentContext, + ResourceAssignment resourceAssignment) throws SvcLogicException, ConfigModelException { + if (resourceAssignment != null) { + try { + validate(resourceAssignment); + + // Check if It has Input + Object value = ConfigAssignmentUtils.getContextKeyValue(ctx, resourceAssignment.getName()); + if (value != null) { + logger.info("db source template key ({}) found from input and value is ({})", + resourceAssignment.getName(), value); + ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, value); + return; + } + + ResourceDefinition resourceDefinition = dictionaries.get(resourceAssignment.getDictionaryName()); + SourcesDefinition sourceDb = resourceDefinition.getSources().get("db"); + if (StringUtils.isBlank(sourceDb.getProperties().getQuery())) { + throw new SvcLogicException("db query property is missing"); + } + + String sql = sourceDb.getProperties().getQuery(); + Map inputKeyMapping = sourceDb.getProperties().getInputKeyMapping(); + + logger.info("Db dictionary information : ({}), ({}), ({})", sql, inputKeyMapping, + sourceDb.getProperties().getOutputKeyMapping()); + + Map namedParameters = populateNamedParameter(componentContext, inputKeyMapping); + + logger.info("Parameter information : ({})", namedParameters); + List> rows = configResourceService.query(sql, namedParameters); + if (rows != null && !rows.isEmpty()) { + processDBResults(ctx, componentContext, resourceAssignment, sourceDb, rows); + } else { + logger.warn("Failed to get db result for dictionary name ({}) the query ({})", + resourceAssignment.getDictionaryName(), sql); + } + + // Check the value has populated for mandatory case + ResourceAssignmentUtils.assertTemplateKeyValueNotNull(componentContext, resourceAssignment); + } catch (Exception e) { + ResourceAssignmentUtils.setFailedResourceDataValue(componentContext, resourceAssignment, + e.getMessage()); + throw new SvcLogicException( + String.format("Failed in template key (%s) assignments : (%s)", resourceAssignment, e), e); + } + } else { + // Do Nothing + } + } + + private void validate(ResourceAssignment resourceAssignment) throws SvcLogicException { + if (resourceAssignment == null) { + throw new SvcLogicException("resource assignment is not defined"); + } + + if (StringUtils.isBlank(resourceAssignment.getName())) { + throw new SvcLogicException("resource assignment template key is not defined"); + } + + if (StringUtils.isBlank(resourceAssignment.getDictionaryName())) { + throw new SvcLogicException( + String.format("resource assignment dictionary name is not defined for template key (%s)", + resourceAssignment.getName())); + } + + if (!ConfigModelConstant.SOURCE_DB.equalsIgnoreCase(resourceAssignment.getDictionarySource())) { + throw new SvcLogicException(String.format("resource assignment source is not db, it is (%s)", + resourceAssignment.getDictionarySource())); + } + + ResourceDefinition resourceDefinition = dictionaries.get(resourceAssignment.getDictionaryName()); + if (resourceDefinition == null) { + throw new SvcLogicException(String.format("missing resource dictionary definition for name (%s) ", + resourceAssignment.getDictionaryName())); + } + + if (resourceDefinition.getSources() == null || resourceDefinition.getSources().get("db") == null) { + throw new SvcLogicException(String.format("missing resource dictionary db source definition for name (%s) ", + resourceAssignment.getDictionaryName())); + } + + SourcesDefinition sourceDb = resourceDefinition.getSources().get("db"); + if (StringUtils.isBlank(sourceDb.getProperties().getQuery())) { + throw new SvcLogicException(String.format("Failed to get request Query for dictionary (%s)", + resourceAssignment.getDictionaryName())); + } + + } + + private Map populateNamedParameter(Map componentContext, + Map inputKeyMapping) { + Map namedParameters = new HashMap<>(); + if (MapUtils.isNotEmpty(inputKeyMapping)) { + + for (Map.Entry mapping : inputKeyMapping.entrySet()) { + ResourceDefinition referenceDictionaryDefinition = dictionaries.get(mapping.getValue()); + Object expressionValue = + ResourceAssignmentUtils.getDictionaryKeyValue(componentContext, referenceDictionaryDefinition); + logger.trace("Reference dictionary key ({}), value ({})", mapping.getKey(), expressionValue); + namedParameters.put(mapping.getKey(), expressionValue); + } + } + return namedParameters; + } + + @SuppressWarnings("squid:S3776") + private void processDBResults(SvcLogicContext ctx, Map componentContext, + ResourceAssignment resourceAssignment, SourcesDefinition sourceDb, List> rows) + throws SvcLogicException, ConfigModelException { + + Map outputKeyMapping = sourceDb.getProperties().getOutputKeyMapping(); + String type = resourceAssignment.getProperty().getType(); + String entrySchema = null; + logger.info("Response processing type({})", type); + // Primitive Types + if (ValidTypes.getPrimitivePropertType().contains(type)) { + + Map row = rows.get(0); + String dbColumnName = outputKeyMapping.get(resourceAssignment.getDictionaryName()); + Object dbColumnValue = row.get(dbColumnName); + ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, dbColumnValue); + + } else if (ValidTypes.getListPropertType().contains(type)) { + // Array Types + if (resourceAssignment.getProperty().getEntrySchema() != null) { + entrySchema = resourceAssignment.getProperty().getEntrySchema().getType(); + } + + if (StringUtils.isNotBlank(entrySchema)) { + ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode(); + + for (Map row : rows) { + if (ValidTypes.getPrimitivePropertType().contains(entrySchema)) { + String dbColumnName = outputKeyMapping.get(resourceAssignment.getDictionaryName()); + Object dbColumnValue = row.get(dbColumnName); + // Add Array JSON + JsonUtils.populatePrimitiveValues(dbColumnValue, entrySchema, arrayNode); + } else { + ObjectNode arrayChildNode = JsonNodeFactory.instance.objectNode(); + for (Map.Entry mapping : outputKeyMapping.entrySet()) { + Object dbColumnValue = row.get(mapping.getKey()); + String propertyTypeForDataType = + ConfigAssignmentUtils.getPropertyType(ctx, entrySchema, mapping.getKey()); + JsonUtils.populatePrimitiveValues(mapping.getKey(), dbColumnValue, propertyTypeForDataType, + arrayChildNode); + } + arrayNode.add(arrayChildNode); + } + } + // Set the List of Complex Values + ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, arrayNode); + } else { + throw new SvcLogicException(String.format("Entry schema is not defined for dictionary (%s) info", + resourceAssignment.getDictionaryName())); + } + } else { + // Complex Types + Map row = rows.get(0); + ObjectNode objectNode = JsonNodeFactory.instance.objectNode(); + for (Map.Entry mapping : outputKeyMapping.entrySet()) { + Object dbColumnValue = row.get(mapping.getKey()); + String propertyTypeForDataType = ConfigAssignmentUtils.getPropertyType(ctx, type, mapping.getKey()); + JsonUtils.populatePrimitiveValues(mapping.getKey(), dbColumnValue, propertyTypeForDataType, objectNode); + } + ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, objectNode); + } + } + + @Override + public void postProcess(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + // Auto-generated method stub + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/DefaultResourceProcessor.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/DefaultResourceProcessor.java new file mode 100644 index 000000000..563d5b523 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/DefaultResourceProcessor.java @@ -0,0 +1,107 @@ +/* + * 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.features.assignment.processor; + +import java.util.List; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.features.assignment.service.ConfigAssignmentUtils; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.ConfigModelException; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.service.ComponentNode; +import org.onap.ccsdk.features.model.utils.ResourceAssignmentUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class DefaultResourceProcessor implements ComponentNode { + + public DefaultResourceProcessor(ConfigResourceService configResourceService) {} + + @Override + public Boolean preCondition(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + return Boolean.TRUE; + } + + @Override + public void preProcess(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + // Auto-generated method stub + } + + @Override + public void process(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + // Auto-generated method stub + } + + @SuppressWarnings("unchecked") + @Override + public void process(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + try { + List batchResourceAssignment = + (List) componentContext.get(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS); + + if (batchResourceAssignment != null && !batchResourceAssignment.isEmpty()) { + for (ResourceAssignment resourceAssignment : batchResourceAssignment) { + processResourceAssignment(ctx, componentContext, resourceAssignment); + } + } + } catch (Exception e) { + throw new SvcLogicException(String.format("DefaultResourceProcessor Exception : (%s)", e), e); + } + + } + + private void processResourceAssignment(SvcLogicContext ctx, Map componentContext, + ResourceAssignment resourceAssignment) throws ConfigModelException, SvcLogicException { + if (resourceAssignment != null && StringUtils.isNotBlank(resourceAssignment.getName()) + && resourceAssignment.getProperty() != null) { + try { + // Check if It has Input + Object value = ConfigAssignmentUtils.getContextKeyValue(ctx, resourceAssignment.getName()); + if (value == null) { + value = resourceAssignment.getProperty().getDefaultValue(); + } + + // if value is null don't call setResourceDataValue to populate the value + if (value != null) { + ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, value); + } + + // Check the value has populated for mandatory case + ResourceAssignmentUtils.assertTemplateKeyValueNotNull(componentContext, resourceAssignment); + } catch (Exception e) { + ResourceAssignmentUtils.setFailedResourceDataValue(componentContext, resourceAssignment, + e.getMessage()); + throw new SvcLogicException( + String.format("Failed in template key (%s) assignments with : (%s)", resourceAssignment, e), e); + } + } + } + + @Override + public void postProcess(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + // Auto-generated method stub + + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/InputResourceProcessor.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/InputResourceProcessor.java new file mode 100644 index 000000000..6c73b08de --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/InputResourceProcessor.java @@ -0,0 +1,96 @@ +/* + * 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.features.assignment.processor; + +import java.util.List; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.ConfigModelException; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.service.ComponentNode; +import org.onap.ccsdk.features.model.utils.ResourceAssignmentUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class InputResourceProcessor implements ComponentNode { + + public InputResourceProcessor(ConfigResourceService configResourceService) {} + + @Override + public Boolean preCondition(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + return Boolean.TRUE; + } + + @Override + public void preProcess(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + // Auto-generated method stub + } + + @Override + public void process(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + // Auto-generated method stub + } + + @SuppressWarnings("unchecked") + @Override + public void process(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + try { + List batchResourceAssignment = + (List) componentContext.get(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS); + if (batchResourceAssignment != null && !batchResourceAssignment.isEmpty()) { + for (ResourceAssignment resourceAssignment : batchResourceAssignment) { + processResourceAssignment(ctx, componentContext, resourceAssignment); + } + } + } catch (Exception e) { + throw new SvcLogicException(String.format("InputResourceProcessor Exception : (%s)", e), e); + } + } + + private void processResourceAssignment(SvcLogicContext ctx, Map componentContext, + ResourceAssignment resourceAssignment) throws ConfigModelException, SvcLogicException { + try { + if (StringUtils.isNotBlank(resourceAssignment.getName())) { + String value = ctx.getAttribute(resourceAssignment.getName()); + // if value is null don't call setResourceDataValue to populate the value + if (StringUtils.isNotBlank(value)) { + ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, value); + } + } + + // Check the value has populated for mandatory case + ResourceAssignmentUtils.assertTemplateKeyValueNotNull(componentContext, resourceAssignment); + } catch (Exception e) { + ResourceAssignmentUtils.setFailedResourceDataValue(componentContext, resourceAssignment, e.getMessage()); + throw new SvcLogicException( + String.format("Failed in template key (%s) assignments with : (%s)", resourceAssignment, e), e); + } + } + + @Override + public void postProcess(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + // Auto-generated method stub + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/MdsalResourceProcessor.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/MdsalResourceProcessor.java new file mode 100644 index 000000000..dfc041cee --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/MdsalResourceProcessor.java @@ -0,0 +1,239 @@ +/* + * 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.features.assignment.processor; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.features.assignment.service.ConfigAssignmentUtils; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.ConfigModelException; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.data.dict.ResourceDefinition; +import org.onap.ccsdk.features.model.data.dict.SourcesDefinition; +import org.onap.ccsdk.features.model.service.ComponentNode; +import org.onap.ccsdk.features.model.utils.ResourceAssignmentUtils; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.features.rest.adaptor.ConfigRestAdaptorConstants; +import org.onap.ccsdk.features.rest.adaptor.service.ConfigRestAdaptorService; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; + +public class MdsalResourceProcessor implements ComponentNode { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(MdsalResourceProcessor.class); + private ConfigRestAdaptorService configRestAdaptorService; + private Map dictionaries; + + public MdsalResourceProcessor(ConfigRestAdaptorService configRestAdaptorService) { + this.configRestAdaptorService = configRestAdaptorService; + } + + @Override + public Boolean preCondition(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + return Boolean.TRUE; + } + + @Override + public void preProcess(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + // Auto-generated method stub + } + + @Override + public void process(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + // Auto-generated method stub + } + + @SuppressWarnings("unchecked") + @Override + public void process(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + try { + List batchResourceAssignment = + (List) componentContext.get(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS); + dictionaries = + (Map) componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARIES); + + if (CollectionUtils.isNotEmpty(batchResourceAssignment)) { + for (ResourceAssignment resourceAssignment : batchResourceAssignment) { + processResourceAssignmnet(ctx, componentContext, resourceAssignment); + } + } + } catch (Exception e) { + throw new SvcLogicException(String.format("MdsalResourceProcessor Exception : (%s) ", e), e); + } + } + + private void processResourceAssignmnet(SvcLogicContext ctx, Map componentContext, + ResourceAssignment resourceAssignment) throws ConfigModelException, SvcLogicException { + + try { + // Validating Resource Assignment and Dictionary Definition data + validate(resourceAssignment); + + // Check if It has Input + Object value = ConfigAssignmentUtils.getContextKeyValue(ctx, resourceAssignment.getName()); + if (value != null) { + logger.info("mdsal source template key ({}) found from input and value is ({})", + resourceAssignment.getName(), value); + ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, value); + return; + } + + ResourceDefinition resourceDefinition = dictionaries.get(resourceAssignment.getDictionaryName()); + SourcesDefinition sourceMdsal = resourceDefinition.getSources().get("mdsal"); + String urlPath = sourceMdsal.getProperties().getUrlPath(); + String path = sourceMdsal.getProperties().getPath(); + Map inputKeyMapping = sourceMdsal.getProperties().getInputKeyMapping(); + Map outputKeyMapping = sourceMdsal.getProperties().getOutputKeyMapping(); + + logger.info( + "mdsal dictionary information : urlpath ({}), path({}), inputKeyMapping ({}), outputKeyMapping ({})", + urlPath, path, inputKeyMapping, outputKeyMapping); + + // Resolving url Variables + Map urlVariables = populateUrlVariables(inputKeyMapping, componentContext); + for (Map.Entry entry : urlVariables.entrySet()) { + urlPath = urlPath.replaceAll("\\$" + entry.getKey(), entry.getValue().toString()); + } + + String restResponse = fetchResourceFromMDSAL(urlPath); + // if restResponse is null don't call processMdsalResults to populate the value + if (StringUtils.isNotBlank(restResponse)) { + // Processing MDSAL Response + processMdsalResults(ctx, componentContext, resourceAssignment, sourceMdsal, restResponse); + } else { + logger.warn("Coudn't get proper mdsal Response content ({}) for Resource Name ({}) for URI ({})", + restResponse, resourceAssignment.getDictionaryName(), urlPath); + } + + // Check the value has populated for mandatory case + ResourceAssignmentUtils.assertTemplateKeyValueNotNull(componentContext, resourceAssignment); + } catch (Exception e) { + ResourceAssignmentUtils.setFailedResourceDataValue(componentContext, resourceAssignment, e.getMessage()); + throw new SvcLogicException( + String.format("Failed in assignments for (%s) with (%s)", resourceAssignment, e), e); + } + } + + private String fetchResourceFromMDSAL(String urlPath) { + String response = null; + try { + response = configRestAdaptorService.getResource(ConfigRestAdaptorConstants.SELECTOR_RESTCONF, urlPath, + String.class); + } catch (Exception e) { + logger.warn("Fetching MDSAL data for URL ({}) failed with Error ({})", urlPath, e); + } + return response; + } + + private void validate(ResourceAssignment resourceAssignment) throws SvcLogicException { + if (resourceAssignment == null) { + throw new SvcLogicException("resource assignment is not defined"); + } + + if (StringUtils.isBlank(resourceAssignment.getName())) { + throw new SvcLogicException("resource assignment template key is not defined"); + } + + if (StringUtils.isBlank(resourceAssignment.getDictionaryName())) { + throw new SvcLogicException( + String.format("resource assignment dictionary name is not defined for template key (%s)", + resourceAssignment.getName())); + } + + if (!ConfigModelConstant.SOURCE_MDSAL.equalsIgnoreCase(resourceAssignment.getDictionarySource())) { + throw new SvcLogicException(String.format("resource assignment source is not mdsal, it is (%s)", + resourceAssignment.getDictionarySource())); + } + + ResourceDefinition resourceDefinition = dictionaries.get(resourceAssignment.getDictionaryName()); + if (resourceDefinition == null) { + throw new SvcLogicException(String.format("missing resource dictionary definition for name (%s) ", + resourceAssignment.getDictionaryName())); + } + + if (StringUtils.isBlank(resourceDefinition.getProperty().getType())) { + throw new SvcLogicException(String.format(String.format("Failed to get dictionary (%s) data type info.", + resourceAssignment.getDictionaryName()))); + } + + if (resourceDefinition.getSources() == null || resourceDefinition.getSources().get("mdsal") == null) { + throw new SvcLogicException( + String.format("missing resource dictionary mdsal source definition for name (%s) ", + resourceAssignment.getDictionaryName())); + } + + SourcesDefinition sourceMdsal = resourceDefinition.getSources().get("mdsal"); + if (StringUtils.isBlank(sourceMdsal.getProperties().getUrlPath())) { + throw new SvcLogicException(String.format("Failed to get request URL Path for dictionary (%s)", + resourceAssignment.getDictionaryName())); + } + + if (StringUtils.isBlank(sourceMdsal.getProperties().getPath())) { + throw new SvcLogicException(String.format("Failed to get request Path for dictionary (%s)", + resourceAssignment.getDictionaryName())); + } + } + + private Map populateUrlVariables(Map inputKeyMapping, + Map componentContext) { + Map urlVariables = new HashMap<>(); + if (MapUtils.isNotEmpty(inputKeyMapping)) { + + for (Map.Entry mapping : inputKeyMapping.entrySet()) { + ResourceDefinition referenceDictionaryDefinition = dictionaries.get(mapping.getValue()); + Object expressionValue = + ResourceAssignmentUtils.getDictionaryKeyValue(componentContext, referenceDictionaryDefinition); + logger.trace("Reference dictionary key ({}), value ({})", mapping.getKey(), expressionValue); + urlVariables.put(mapping.getKey(), expressionValue); + } + } + return urlVariables; + } + + private void processMdsalResults(SvcLogicContext ctx, Map componentContext, + ResourceAssignment resourceAssignment, SourcesDefinition sourceMdsal, String restResponse) + throws SvcLogicException, ConfigModelException { + + Map outputKeyMapping = sourceMdsal.getProperties().getOutputKeyMapping(); + JsonNode responseNode = TransformationUtils.getJsonNodeForString(restResponse); + if (StringUtils.isNotBlank(sourceMdsal.getProperties().getPath())) { + responseNode = responseNode.at(sourceMdsal.getProperties().getPath()); + } + if (responseNode != null) { + ConfigAssignmentUtils.populateValueForOutputMapping(ctx, componentContext, resourceAssignment, + outputKeyMapping, responseNode); + } + } + + @Override + public void postProcess(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + // Do Nothing + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/ProcessorFactory.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/ProcessorFactory.java new file mode 100644 index 000000000..bb620a1a3 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/ProcessorFactory.java @@ -0,0 +1,52 @@ +/* + * 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.features.assignment.processor; + +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.service.ComponentNode; +import org.onap.ccsdk.features.model.service.ComponentNodeService; +import org.onap.ccsdk.features.rest.adaptor.service.ConfigRestAdaptorService; + +public class ProcessorFactory { + + private ConfigResourceService configResourceService; + private ConfigRestAdaptorService configRestAdaptorService; + private ComponentNodeService componentNodeService; + + public ProcessorFactory(ConfigResourceService configResourceService, + ConfigRestAdaptorService configRestAdaptorService, ComponentNodeService componentNodeService) { + this.componentNodeService = componentNodeService; + this.configResourceService = configResourceService; + this.configRestAdaptorService = configRestAdaptorService; + } + + public ComponentNode getInstance(String source) { + + if (ConfigModelConstant.SOURCE_DEFAULT.equalsIgnoreCase(source)) { + return new DefaultResourceProcessor(configResourceService); + } else if (ConfigModelConstant.SOURCE_DB.equalsIgnoreCase(source)) { + return new DBResourceProcessor(configResourceService); + } else if (ConfigModelConstant.SOURCE_MDSAL.equalsIgnoreCase(source)) { + return new MdsalResourceProcessor(configRestAdaptorService); + } + // Default + return new InputResourceProcessor(configResourceService); + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/ResourceAssignmentProcessor.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/ResourceAssignmentProcessor.java new file mode 100644 index 000000000..3ee49f085 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/processor/ResourceAssignmentProcessor.java @@ -0,0 +1,120 @@ +/* + * 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.features.assignment.processor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.collections.CollectionUtils; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.utils.TopologicalSortingUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ResourceAssignmentProcessor { + private static EELFLogger logger = EELFManager.getInstance().getLogger(ResourceAssignmentProcessor.class); + + private List assignments; + private Map resourceAssignmentMap; + + @SuppressWarnings("squid:S1172") + public ResourceAssignmentProcessor(List assignments, SvcLogicContext ctx) { + this.assignments = assignments; + this.resourceAssignmentMap = new HashMap<>(); + } + + @SuppressWarnings("squid:S3776") + public List> process() { + List> sequenceBatchResourceAssignment = new ArrayList<>(); + if (this.assignments != null) { + logger.info("Assignments ({})", this.assignments); + this.assignments.forEach(resourceMapping -> { + if (resourceMapping != null) { + logger.trace("Processing Key ({})", resourceMapping.getName()); + resourceAssignmentMap.put(resourceMapping.getName(), resourceMapping); + } + }); + + TopologicalSortingUtils topologySorting = new TopologicalSortingUtils<>(); + this.resourceAssignmentMap.forEach((mappingKey, mapping) -> { + if (mapping != null) { + if (mapping.getDependencies() != null && !mapping.getDependencies().isEmpty()) { + for (String dependency : mapping.getDependencies()) { + topologySorting.add(resourceAssignmentMap.get(dependency), mapping); + } + } else { + topologySorting.add(null, mapping); + } + } + }); + + List sequencedResourceAssignments = topologySorting.topSort(); + logger.info("Sorted Sequenced Assignments ({})", sequencedResourceAssignments); + + List batchResourceAssignment = null; + List batchAssignmentName = null; + for (int i = 0; i < sequencedResourceAssignments.size(); i++) { + ResourceAssignment resourceAssignment = sequencedResourceAssignments.get(i); + ResourceAssignment previousResourceAssignment = null; + + if (i > 0) { + previousResourceAssignment = sequencedResourceAssignments.get(i - 1); + } + if (resourceAssignment != null) { + + boolean dependencyPresence = false; + if (batchAssignmentName != null && resourceAssignment.getDependencies() != null) { + dependencyPresence = + CollectionUtils.containsAny(batchAssignmentName, resourceAssignment.getDependencies()); + } + + logger.trace("({}) -> Checking ({}), with ({}), result ({})", resourceAssignment.getName(), + batchAssignmentName, resourceAssignment.getDependencies(), dependencyPresence); + + if (previousResourceAssignment != null && resourceAssignment.getDictionarySource() != null + && resourceAssignment.getDictionarySource() + .equalsIgnoreCase(previousResourceAssignment.getDictionarySource()) + && !dependencyPresence) { + batchResourceAssignment.add(resourceAssignment); + batchAssignmentName.add(resourceAssignment.getName()); + } else { + if (batchResourceAssignment != null) { + sequenceBatchResourceAssignment.add(batchResourceAssignment); + logger.trace("Created old Set ({})", batchAssignmentName); + } + batchResourceAssignment = new ArrayList<>(); + batchResourceAssignment.add(resourceAssignment); + + batchAssignmentName = new ArrayList<>(); + batchAssignmentName.add(resourceAssignment.getName()); + } + } + + if (i == (sequencedResourceAssignments.size() - 1)) { + logger.trace("Created old Set ({})", batchAssignmentName); + sequenceBatchResourceAssignment.add(batchResourceAssignment); + } + } + logger.info("Batched Sequence : ({})", sequenceBatchResourceAssignment); + } + return sequenceBatchResourceAssignment; + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentNode.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentNode.java new file mode 100644 index 000000000..aaeadcabd --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentNode.java @@ -0,0 +1,231 @@ +/* + * 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.features.assignment.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.features.assignment.ConfigAssignmentConstants; +import org.onap.ccsdk.features.assignment.data.ResourceAssignmentData; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.generator.service.ConfigGeneratorService; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.service.ComponentNode; +import org.onap.ccsdk.features.model.service.ComponentNodeService; +import org.onap.ccsdk.features.model.service.ConfigModelService; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.features.rest.adaptor.service.ConfigRestAdaptorService; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ConfigAssignmentNode implements ComponentNode { + private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentNode.class); + + private ComponentNodeService componentNodeService; + private ConfigResourceService configResourceService; + private ConfigModelService configModelService; + private ConfigRestAdaptorService configRestAdaptorService; + private ConfigGeneratorService configGeneratorService; + + public ConfigAssignmentNode(ConfigResourceService configResourceService, + ConfigRestAdaptorService configRestAdaptorService, ConfigModelService configModelService, + ComponentNodeService componentNodeService, ConfigGeneratorService configGeneratorService) { + logger.info("{} Constrctor Initiated", "ConfigAssignmentNode"); + this.componentNodeService = componentNodeService; + this.configResourceService = configResourceService; + this.configModelService = configModelService; + this.configRestAdaptorService = configRestAdaptorService; + this.configGeneratorService = configGeneratorService; + } + + @Override + public Boolean preCondition(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + return Boolean.TRUE; + } + + @Override + public void preProcess(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + // Auto-generated method stub + } + + /** + * This method is used to resolve the resources defined in the template. Generic Resource API DG + * calls this execute node. + * + * @param inParams This is the input parameter to process this node + * + *
+    request-id                  (string):           Tracking Id 
+    resource-type               (string):           Resource Type ( ex : vnf-type) 
+    resource-id                 (string):           Resource Id 
+    service-template-name       (string):           Blueprint Name 
+    service-template-version    (string):           Blueprint Version 
+    action-name                 (string): 
+    template-names              (List of string):   Template Names / Artifact Node Names to resolve. ["template1", "template2"] 
+    input-data                  (string):           Input Data in JSON String, for the substitution in the Template. 
+    prifix                      (string):           Return Value selector
+     *        
+ * + * @param ctx This is the service logger context, Output will be stored ( + * .resource-assignment-params. : Output Data in JSON String. + * .status .error-message ) + * @throws SvcLogicException On processing error. + */ + + @Override + public void process(Map inParams, SvcLogicContext ctx) throws SvcLogicException { + + final String responsePrefix = StringUtils.isNotBlank(inParams.get(ConfigModelConstant.PROPERTY_SELECTOR)) + ? (inParams.get(ConfigModelConstant.PROPERTY_SELECTOR) + ".") + : ""; + try { + + ResourceAssignmentData resourceAssignmentData = populateResourceData(inParams); + resourceAssignmentData.setSvcLogicContext(ctx); + Map componentContext = new HashMap<>(); + resourceAssignmentData.setContext(componentContext); + resourceAssignmentData.setReloadModel(true); + + ConfigAssignmentProcessService configAssignmentProcessService = + new ConfigAssignmentProcessService(configResourceService, configRestAdaptorService, + configModelService, componentNodeService, configGeneratorService); + configAssignmentProcessService.resolveResources(resourceAssignmentData); + + if (MapUtils.isNotEmpty(resourceAssignmentData.getTemplatesMashedContents())) { + resourceAssignmentData.getTemplatesMashedContents().forEach((templateName, previewContent) -> { + logger.debug("For Template name : ({}),\n Preview Content is : ({})", templateName, previewContent); + ctx.setAttribute( + responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_MASHED_DATA + "." + templateName, + previewContent); + }); + } + ctx.setAttribute(responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_STATUS, + ConfigAssignmentConstants.OUTPUT_STATUS_SUCCESS); + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_STATUS, + ConfigAssignmentConstants.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + throw new SvcLogicException(e.getMessage(), e); + } + } + + @Override + public void process(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + + final String responsePrefix = StringUtils.isNotBlank(inParams.get(ConfigModelConstant.PROPERTY_SELECTOR)) + ? (inParams.get(ConfigModelConstant.PROPERTY_SELECTOR) + ".") + : ""; + try { + + ResourceAssignmentData resourceAssignmentData = populateResourceData(inParams); + resourceAssignmentData.setSvcLogicContext(ctx); + resourceAssignmentData.setContext(componentContext); + resourceAssignmentData.setReloadModel(false); + + ConfigAssignmentProcessService configAssignmentProcessService = + new ConfigAssignmentProcessService(configResourceService, configRestAdaptorService, + configModelService, componentNodeService, configGeneratorService); + configAssignmentProcessService.resolveResources(resourceAssignmentData); + ctx.setAttribute(responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_STATUS, + ConfigAssignmentConstants.OUTPUT_STATUS_SUCCESS); + + } catch (Exception e) { + ctx.setAttribute(responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_STATUS, + ConfigAssignmentConstants.OUTPUT_STATUS_FAILURE); + ctx.setAttribute(responsePrefix + ConfigAssignmentConstants.OUTPUT_PARAM_ERROR_MESSAGE, e.getMessage()); + throw new SvcLogicException(e.getMessage(), e); + } + } + + @Override + public void postProcess(Map inParams, SvcLogicContext ctx, Map componentContext) + throws SvcLogicException { + // Do Nothing + } + + private ResourceAssignmentData populateResourceData(Map inParams) throws SvcLogicException { + validateInputParams(inParams); + + String requestId = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_REQUEST_ID); + String resourceId = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_ID); + String resourceType = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_TYPE); + String serviceTemplateName = inParams.get(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_NAME); + String serviceTemplateVersion = inParams.get(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_VERSION); + String actionName = inParams.get(ConfigModelConstant.PROPERTY_ACTION_NAME); + String inputData = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_INPUT_DATA); + + String templateNamesStr = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_TEMPLATE_NAMES); + List templateNames = TransformationUtils.getListfromJson(templateNamesStr, String.class); + + ResourceAssignmentData resourceAssignmentData = new ResourceAssignmentData(); + resourceAssignmentData.setRequestId(requestId); + resourceAssignmentData.setResourceId(resourceId); + resourceAssignmentData.setResourceType(resourceType); + resourceAssignmentData.setServiceTemplateName(serviceTemplateName); + resourceAssignmentData.setServiceTemplateVersion(serviceTemplateVersion); + resourceAssignmentData.setActionName(actionName); + resourceAssignmentData.setInputData(inputData); + resourceAssignmentData.setTemplateNames(templateNames); + + return resourceAssignmentData; + } + + private void validateInputParams(Map inParams) throws SvcLogicException { + if (inParams == null) { + throw new SvcLogicException("Input parameters missing"); + } + + String requestId = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_REQUEST_ID); + if (StringUtils.isBlank(requestId)) { + throw new SvcLogicException("Request id parameters missing"); + } + String resourceId = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_ID); + if (StringUtils.isBlank(resourceId)) { + throw new SvcLogicException("Resource id parameter is missing"); + } + String resourceType = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_TYPE); + if (StringUtils.isBlank(resourceType)) { + throw new SvcLogicException("Resource type parameter is missing"); + } + String recipeName = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_ACTION_NAME); + if (StringUtils.isBlank(recipeName)) { + throw new SvcLogicException("Action name is parameter is missing"); + } + String templateNames = inParams.get(ConfigAssignmentConstants.INPUT_PARAM_TEMPLATE_NAMES); + if (StringUtils.isBlank(templateNames)) { + throw new SvcLogicException("Template names parameter missing"); + } + String serviceTemplateName = inParams.get(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_NAME); + if (StringUtils.isBlank(serviceTemplateName)) { + throw new SvcLogicException("Service Template name parameter missing"); + } + String serviceTemplateVersion = inParams.get(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_VERSION); + if (StringUtils.isBlank(serviceTemplateVersion)) { + throw new SvcLogicException("Service Template version parameter missing"); + } + + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentPersistService.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentPersistService.java new file mode 100644 index 000000000..c4083f86d --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentPersistService.java @@ -0,0 +1,123 @@ +/* + * 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.features.assignment.service; + +import java.util.List; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.features.data.adaptor.DataAdaptorConstants; +import org.onap.ccsdk.features.data.adaptor.domain.ConfigResource; +import org.onap.ccsdk.features.data.adaptor.domain.ResourceAssignmentData; +import org.onap.ccsdk.features.data.adaptor.domain.TransactionLog; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.utils.ResourceAssignmentUtils; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ConfigAssignmentPersistService { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentPersistService.class); + + private ConfigResourceService configResourceService; + + public ConfigAssignmentPersistService(ConfigResourceService configResourceService) { + this.configResourceService = configResourceService; + } + + public void saveResourceMapping(org.onap.ccsdk.features.assignment.data.ResourceAssignmentData resourceAssignmentData, + String templateName, List resourceAssignments) throws SvcLogicException { + try { + + if (resourceAssignmentData == null) { + throw new SvcLogicException("Resource assignment data is missing"); + } + + if (StringUtils.isBlank(resourceAssignmentData.getRequestId())) { + logger.warn("Request Id ({}) is missing, may be getting request for resource update.", + resourceAssignmentData.getRequestId()); + } + + if (StringUtils.isBlank(resourceAssignmentData.getResourceId())) { + throw new SvcLogicException("Resource Id is missing"); + } + + if (StringUtils.isBlank(resourceAssignmentData.getResourceType())) { + throw new SvcLogicException("Resource type is missing"); + } + + if (StringUtils.isBlank(resourceAssignmentData.getActionName())) { + throw new SvcLogicException("Action name is missing"); + } + + if (StringUtils.isBlank(templateName)) { + throw new SvcLogicException("template name is missing"); + } + + StringBuilder builder = new StringBuilder(); + builder.append("Resource Assignment for Template Name :"); + builder.append(templateName); + builder.append("\n"); + builder.append(TransformationUtils.getJson(resourceAssignments, true)); + + configResourceService.save(new TransactionLog(resourceAssignmentData.getRequestId(), + DataAdaptorConstants.LOG_MESSAGE_TYPE_LOG, builder.toString())); + + // Resource Data should be Regenerated based on the new Updates + String resourceData = ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments); + + List resourceAssignmentDataList = + ConfigAssignmentUtils.convertResoureAssignmentList(resourceAssignments); + + ConfigResource configResource = new ConfigResource(); + configResource.setRequestId(resourceAssignmentData.getRequestId()); + configResource.setServiceTemplateName(resourceAssignmentData.getServiceTemplateName()); + configResource.setServiceTemplateVersion(resourceAssignmentData.getServiceTemplateVersion()); + configResource.setRecipeName(resourceAssignmentData.getActionName()); + configResource.setResourceId(resourceAssignmentData.getResourceId()); + configResource.setResourceType(resourceAssignmentData.getResourceType()); + configResource.setResourceData(resourceData); + configResource.setTemplateName(templateName); + configResource.setStatus(ConfigModelConstant.STATUS_SUCCESS); + configResource.setUpdatedBy(ConfigModelConstant.USER_SYSTEM); + + if (CollectionUtils.isNotEmpty(resourceAssignmentDataList)) { + configResource.setResourceAssignments(resourceAssignmentDataList); + } + configResource = configResourceService.saveConfigResource(configResource); + logger.info("Resource data saved successfully for the template ({}) with resource id ({})", templateName, + configResource.getResourceId()); + + builder = new StringBuilder(); + builder.append("Resource Data Template Name :"); + builder.append(templateName); + builder.append("\n"); + builder.append(resourceData); + configResourceService.save(new TransactionLog(resourceAssignmentData.getRequestId(), + DataAdaptorConstants.LOG_MESSAGE_TYPE_LOG, builder.toString())); + + } catch (Exception e) { + throw new SvcLogicException("ConfigAssignmentPersistService : " + e.getMessage(), e); + } + + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentProcessService.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentProcessService.java new file mode 100644 index 000000000..61c035960 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentProcessService.java @@ -0,0 +1,238 @@ +/* + * 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.features.assignment.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.features.assignment.ConfigAssignmentConstants; +import org.onap.ccsdk.features.assignment.data.ResourceAssignmentData; +import org.onap.ccsdk.features.assignment.processor.ProcessorFactory; +import org.onap.ccsdk.features.assignment.processor.ResourceAssignmentProcessor; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.generator.service.ConfigGeneratorService; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.data.dict.ResourceDefinition; +import org.onap.ccsdk.features.model.service.ComponentNode; +import org.onap.ccsdk.features.model.service.ComponentNodeService; +import org.onap.ccsdk.features.model.service.ConfigModelService; +import org.onap.ccsdk.features.model.utils.ResourceAssignmentUtils; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.features.rest.adaptor.service.ConfigRestAdaptorService; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ConfigAssignmentProcessService { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentProcessService.class); + + private ComponentNodeService componentNodeService; + private ConfigResourceService configResourceService; + private ConfigModelService configModelService; + private ConfigRestAdaptorService configRestAdaptorService; + private ConfigGeneratorService configGeneratorService; + + public ConfigAssignmentProcessService(ConfigResourceService configResourceService, + ConfigRestAdaptorService configRestAdaptorService, ConfigModelService configModelService, + ComponentNodeService componentNodeService, ConfigGeneratorService configGeneratorService) { + this.componentNodeService = componentNodeService; + this.configResourceService = configResourceService; + this.configModelService = configModelService; + this.configRestAdaptorService = configRestAdaptorService; + this.configGeneratorService = configGeneratorService; + } + + @SuppressWarnings("squid:S1141") + public void resolveResources(ResourceAssignmentData resourceAssignmentData) throws SvcLogicException { + try { + validateInputParams(resourceAssignmentData); + + String serviceTemplateName = resourceAssignmentData.getServiceTemplateName(); + String serviceTemplateVersion = resourceAssignmentData.getServiceTemplateVersion(); + String actionName = resourceAssignmentData.getActionName(); + String inputData = resourceAssignmentData.getInputData(); + SvcLogicContext svcLogicContext = resourceAssignmentData.getSvcLogicContext(); + List templateNames = resourceAssignmentData.getTemplateNames(); + + if (resourceAssignmentData.isReloadModel()) { + Map context = new HashMap<>(); + context.put(ConfigModelConstant.PROPERTY_ACTION_NAME, actionName); + context = configModelService.prepareContext(context, inputData, serviceTemplateName, + serviceTemplateVersion); + context.forEach((key, value) -> svcLogicContext.setAttribute(key, value)); + logger.info("List of Resources provided in input: {}", svcLogicContext.toProperties()); + } + + Map componentContext = resourceAssignmentData.getContext(); + + if (CollectionUtils.isNotEmpty(templateNames)) { + // Get the Resource Assignments for templates and Validate the mappings + ResourceModelService resourceModelService = new ResourceModelService(configModelService); + + // Get the Resource Assignment + Map> templatesResourceAssignments = + resourceModelService.getTemplatesResourceAssignments(svcLogicContext, templateNames); + + // Get the Template Contents + Map templatesContents = + resourceModelService.getTemplatesContents(svcLogicContext, templateNames); + + // Process each template + for (String templateName : templateNames) { + List resourceAssignments = templatesResourceAssignments.get(templateName); + String templateContent = templatesContents.get(templateName); + if (resourceAssignments != null) { + String templateData = null; + try { + // Populate the Dictionary + ResourceDictionaryService resourceDictionaryService = + new ResourceDictionaryService(configRestAdaptorService); + Map dictionaries = + resourceDictionaryService.getDataDictionaryDefinitions(resourceAssignments); + + processResourceAssignments(resourceAssignmentData, svcLogicContext, componentContext, + templateName, resourceAssignments, dictionaries); + + logger.info("decrypting config data for templateName {}", templateName); + templateData = + ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments); + } finally { + saveResourceMapping(resourceAssignmentData, templateName, resourceAssignments); + } + + logger.info("generating config preview for templateName {}", templateName); + ConfigPreviewService configPreviewService = new ConfigPreviewService(configResourceService, + configModelService, configGeneratorService); + String mashedData = configPreviewService.generatePreview(templateContent, templateData); + resourceAssignmentData.getTemplatesMashedContents().put(templateName, mashedData); + resourceAssignmentData.getTemplatesData().put(templateName, templateData); + + } else { + // Do nothing for Mapping not found + logger.warn("No resource Assignment mappings to resolve for templateName {}", templateName); + } + } + } + + } catch (Exception e) { + throw new SvcLogicException(e.getMessage(), e); + } + } + + private void processResourceAssignments(ResourceAssignmentData resourceAssignmentData, SvcLogicContext ctx, + Map componentContext, String templateName, List resourceAssignments, + Map dictionaries) throws SvcLogicException { + + String recipeName = resourceAssignmentData.getActionName(); + + ResourceAssignmentProcessor resourceAssignmentProcessor = + new ResourceAssignmentProcessor(resourceAssignments, ctx); + List> sequenceBatchResourceAssignment = resourceAssignmentProcessor.process(); + + logger.debug("Resource dictionary Info ({})", dictionaries); + + if (sequenceBatchResourceAssignment != null) { + componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); + componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, templateName); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); + for (List batchResourceAssignment : sequenceBatchResourceAssignment) { + + processBatchResourceAssignments(resourceAssignmentData, ctx, componentContext, batchResourceAssignment); + + logger.debug("Batch Resource data status ({})", TransformationUtils.getJson(batchResourceAssignment)); + } + } + } + + private void processBatchResourceAssignments(ResourceAssignmentData resourceAssignmentData, SvcLogicContext ctx, + Map componentContext, List batchResourceAssignment) + throws SvcLogicException { + + if (CollectionUtils.isNotEmpty(batchResourceAssignment)) { + + ResourceAssignment batchFirstResourceAssignment = batchResourceAssignment.get(0); + if (batchFirstResourceAssignment != null + && StringUtils.isNotBlank(batchFirstResourceAssignment.getDictionarySource())) { + String source = batchFirstResourceAssignment.getDictionarySource(); + // Processing their Source + logger.info("Processing source ({}) with batch ({}) ", source, batchResourceAssignment); + componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); + + ProcessorFactory factory = + new ProcessorFactory(configResourceService, configRestAdaptorService, componentNodeService); + + ComponentNode processor = factory.getInstance(source); + + Map inParams = new HashMap<>(); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_REQUEST_ID, resourceAssignmentData.getRequestId()); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_ID, resourceAssignmentData.getResourceId()); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_TYPE, + resourceAssignmentData.getResourceType()); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_ACTION_NAME, resourceAssignmentData.getActionName()); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_TEMPLATE_NAMES, + resourceAssignmentData.getTemplateNames().toString()); + processor.process(inParams, ctx, componentContext); + } + } + } + + private void saveResourceMapping(ResourceAssignmentData resourceAssignmentData, String templateName, + List resourceAssignments) throws SvcLogicException { + if (resourceAssignmentData != null && StringUtils.isNotBlank(templateName)) { + + ConfigAssignmentPersistService configAssignmentPersistService = + new ConfigAssignmentPersistService(configResourceService); + configAssignmentPersistService.saveResourceMapping(resourceAssignmentData, templateName, + resourceAssignments); + } + } + + private void validateInputParams(ResourceAssignmentData resourceAssignmentData) throws SvcLogicException { + if (resourceAssignmentData == null) { + throw new SvcLogicException("Input parameters missing"); + } + + String requestId = resourceAssignmentData.getRequestId(); + if (StringUtils.isBlank(requestId)) { + throw new SvcLogicException("Request id parameters missing"); + } + String resourceId = resourceAssignmentData.getResourceId(); + if (StringUtils.isBlank(resourceId)) { + throw new SvcLogicException("Resource id parameter is missing"); + } + String resourceType = resourceAssignmentData.getResourceType(); + if (StringUtils.isBlank(resourceType)) { + throw new SvcLogicException("Resource type parameter is missing"); + } + String actionName = resourceAssignmentData.getActionName(); + if (StringUtils.isBlank(actionName)) { + throw new SvcLogicException("Action name is parameter is missing"); + } + + List templatesNames = resourceAssignmentData.getTemplateNames(); + if (CollectionUtils.isEmpty(templatesNames)) { + throw new SvcLogicException("Template names parameter missing"); + } + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentService.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentService.java new file mode 100644 index 000000000..969f84679 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentService.java @@ -0,0 +1,36 @@ +/* + * 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.features.assignment.service; + +import java.util.List; + +import org.onap.ccsdk.features.assignment.data.ResourceAssignmentData; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public interface ConfigAssignmentService { + + public void resolveResources(ResourceAssignmentData resourceAssignmentData) throws SvcLogicException; + + public void saveResourceMapping(ResourceAssignmentData resourceAssignmentData, String templateName, + List resourceAssignments) throws SvcLogicException; + + public ResourceAssignmentData generateTemplateResourceMash(ResourceAssignmentData resourceAssignmentData) + throws SvcLogicException; + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentServiceImpl.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentServiceImpl.java new file mode 100644 index 000000000..560d0b1ff --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentServiceImpl.java @@ -0,0 +1,80 @@ +/* + * 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.features.assignment.service; + +import java.util.List; + +import org.onap.ccsdk.features.assignment.data.ResourceAssignmentData; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.generator.service.ConfigGeneratorService; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.service.ComponentNodeService; +import org.onap.ccsdk.features.model.service.ConfigModelService; +import org.onap.ccsdk.features.rest.adaptor.service.ConfigRestAdaptorService; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ConfigAssignmentServiceImpl implements ConfigAssignmentService { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentServiceImpl.class); + + private ComponentNodeService componentNodeService; + private ConfigResourceService configResourceService; + private ConfigModelService configModelService; + private ConfigRestAdaptorService configRestAdaptorService; + private ConfigGeneratorService configGeneratorService; + + private static final String CLASS_NAME = "ConfigAssignmentServiceImpl"; + + public ConfigAssignmentServiceImpl(ConfigResourceService configResourceService, + ConfigRestAdaptorService configRestAdaptorService, ConfigModelService configModelService, + ComponentNodeService componentNodeService, ConfigGeneratorService configGeneratorService) { + logger.info("{} Constuctor Initated...", CLASS_NAME); + this.componentNodeService = componentNodeService; + this.configResourceService = configResourceService; + this.configModelService = configModelService; + this.configRestAdaptorService = configRestAdaptorService; + this.configGeneratorService = configGeneratorService; + } + + @Override + public void resolveResources(ResourceAssignmentData resourceAssignmentData) throws SvcLogicException { + ConfigAssignmentProcessService configAssignmentProcessService = + new ConfigAssignmentProcessService(configResourceService, configRestAdaptorService, configModelService, + componentNodeService, configGeneratorService); + configAssignmentProcessService.resolveResources(resourceAssignmentData); + } + + @Override + public void saveResourceMapping(ResourceAssignmentData resourceAssignmentData, String templateName, + List resourceAssignments) throws SvcLogicException { + ConfigAssignmentPersistService configAssignmentPersistService = + new ConfigAssignmentPersistService(configResourceService); + configAssignmentPersistService.saveResourceMapping(resourceAssignmentData, templateName, resourceAssignments); + } + + @Override + public ResourceAssignmentData generateTemplateResourceMash(ResourceAssignmentData resourceAssignmentData) + throws SvcLogicException { + ConfigPreviewService configPreviewService = + new ConfigPreviewService(configResourceService, configModelService, configGeneratorService); + return configPreviewService.generateTemplateResourceMash(resourceAssignmentData); + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentUtils.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentUtils.java new file mode 100644 index 000000000..1d7df6b58 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentUtils.java @@ -0,0 +1,305 @@ +/* + * 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.features.assignment.service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.IteratorUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.features.data.adaptor.domain.ResourceAssignmentData; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.ConfigModelException; +import org.onap.ccsdk.features.model.ValidTypes; +import org.onap.ccsdk.features.model.data.DataType; +import org.onap.ccsdk.features.model.data.EntrySchema; +import org.onap.ccsdk.features.model.data.PropertyDefinition; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.data.dict.ResourceDefinition; +import org.onap.ccsdk.features.model.domain.ResourceDictionary; +import org.onap.ccsdk.features.model.utils.JsonUtils; +import org.onap.ccsdk.features.model.utils.ResourceAssignmentUtils; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public class ConfigAssignmentUtils { + + private ConfigAssignmentUtils() { + + } + + private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentUtils.class); + + public static synchronized Object getContextKeyValue(SvcLogicContext context, String key) { + Object value = null; + if (context != null && key != null) { + if (context.getAttributeKeySet().contains(key)) { + String strValue = context.getAttribute(key); + if (StringUtils.isNotBlank(strValue)) { + value = strValue; + } + } else { + // Do Nothing + } + } + return value; + } + + /* + * Populate the Field property type for the Data type + */ + public static synchronized String getPropertyType(SvcLogicContext ctx, String dataTypeName, String propertyName) + throws SvcLogicException { + String type = ValidTypes.DATA_TYPE_STRING; + try { + if (ctx != null && StringUtils.isNotBlank(dataTypeName) && StringUtils.isNotBlank(propertyName)) { + String dataTypeContent = ctx.getAttribute(ConfigModelConstant.PROPERTY_DATA_TYPES_DOT + dataTypeName); + if (StringUtils.isNotBlank(dataTypeContent)) { + DataType dataType = TransformationUtils.readValue(dataTypeContent, DataType.class); + if (dataType != null && dataType.getProperties() != null + && dataType.getProperties().containsKey(propertyName)) { + PropertyDefinition propertyDefinition = dataType.getProperties().get(propertyName); + if (StringUtils.isNotBlank(propertyDefinition.getType())) { + type = propertyDefinition.getType(); + logger.trace("Data type({})'s property ({}) is ({})", dataTypeName, propertyName, type); + } else { + throw new SvcLogicException(String.format("Couldn't get data type (%s) ", dataTypeName)); + } + } + } else { + throw new SvcLogicException(String.format("Couldn't get data type (%s) content", dataTypeName)); + } + } + } catch (Exception e) { + logger.error("couldn't get data type({})'s property ({}), type ({}), error message ({}).", dataTypeName, + propertyName, type, e.getMessage()); + throw new SvcLogicException(e.getMessage()); + } + return type; + } + + /* + * Populate the Field property type for the Data type + */ + public static synchronized PropertyDefinition getPropertyDefinition(SvcLogicContext ctx, String dataTypeName, + String propertyName) throws SvcLogicException { + PropertyDefinition propertyDefinition = null; + try { + if (ctx != null && StringUtils.isNotBlank(dataTypeName) && StringUtils.isNotBlank(propertyName)) { + String dataTypeContent = ctx.getAttribute(ConfigModelConstant.PROPERTY_DATA_TYPES_DOT + dataTypeName); + if (StringUtils.isNotBlank(dataTypeContent)) { + DataType dataType = TransformationUtils.readValue(dataTypeContent, DataType.class); + if (dataType != null && dataType.getProperties() != null + && dataType.getProperties().containsKey(propertyName)) { + propertyDefinition = dataType.getProperties().get(propertyName); + if (propertyDefinition == null) { + throw new SvcLogicException(String.format("couldn't get data type (%s) ", dataTypeName)); + } + } + } else { + throw new SvcLogicException(String.format("couldn't get data type (%s) content.", dataTypeName)); + } + } + } catch (Exception e) { + throw new SvcLogicException(e.getMessage()); + } + return propertyDefinition; + } + + public static synchronized ResourceDefinition getDictionaryDefinition(Map dictionaries, + String dictionaryName) { + ResourceDefinition resourceDefinition = null; + if (dictionaries != null && StringUtils.isNotBlank(dictionaryName)) { + ResourceDictionary resourceDictionary = dictionaries.get(dictionaryName); + if (resourceDictionary != null && StringUtils.isNotBlank(resourceDictionary.getDefinition())) { + resourceDefinition = + TransformationUtils.readValue(resourceDictionary.getDefinition(), ResourceDefinition.class); + } + } + return resourceDefinition; + } + + @SuppressWarnings("squid:S3776") + public static synchronized void populateValueForOutputMapping(SvcLogicContext ctx, + Map componentContext, ResourceAssignment resourceAssignment, + Map outputKeyMapping, JsonNode responseNode) + throws ConfigModelException, SvcLogicException { + if (resourceAssignment == null) { + throw new SvcLogicException("resourceAssignment is null."); + } + + if (ctx == null) { + throw new SvcLogicException("service logic context is null."); + } + + if (componentContext == null) { + throw new SvcLogicException("component context is null."); + } + + logger.info("populating value for output mapping ({}), from json ({})", outputKeyMapping, responseNode); + String dictionaryName = resourceAssignment.getDictionaryName(); + String type = resourceAssignment.getProperty().getType(); + + String entrySchema = null; + if (ValidTypes.getPrimitivePropertType().contains(type)) { + ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, responseNode); + } else if (ValidTypes.getListPropertType().contains(type)) { + // Array Types + if (resourceAssignment.getProperty().getEntrySchema() != null) { + entrySchema = resourceAssignment.getProperty().getEntrySchema().getType(); + } + + if (StringUtils.isNotBlank(entrySchema)) { + ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode(); + if (ValidTypes.getPrimitivePropertType().contains(entrySchema)) { + arrayNode = (ArrayNode) responseNode; + } else if (MapUtils.isNotEmpty(outputKeyMapping)) { + List responseArrayNode = IteratorUtils.toList(responseNode.elements()); + for (JsonNode responseSingleJsonNode : responseArrayNode) { + if (responseSingleJsonNode != null) { + ObjectNode arrayChildNode = JsonNodeFactory.instance.objectNode(); + for (Map.Entry mapping : outputKeyMapping.entrySet()) { + JsonNode responseKeyValue = responseSingleJsonNode.get(mapping.getKey()); + + String propertyTypeForDataType = + ConfigAssignmentUtils.getPropertyType(ctx, entrySchema, mapping.getKey()); + logger.info("For List Type Resource: key ({}), value ({}), type ({})", + mapping.getKey(), responseKeyValue, propertyTypeForDataType); + JsonUtils.populateJsonNodeValues(mapping.getValue(), responseKeyValue, + propertyTypeForDataType, arrayChildNode); + } + arrayNode.add(arrayChildNode); + } + } + } else { + arrayNode = (ArrayNode) responseNode; + } + // Set the List of Complex Values + ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, arrayNode); + } else { + throw new SvcLogicException( + String.format("Entry schema is not defined for dictionary (%s) info", dictionaryName)); + } + } else { + // Complex Types + ObjectNode objectNode = null; + if (MapUtils.isNotEmpty(outputKeyMapping)) { + objectNode = JsonNodeFactory.instance.objectNode(); + for (Map.Entry mapping : outputKeyMapping.entrySet()) { + JsonNode responseKeyValue = responseNode.get(mapping.getKey()); + String propertyTypeForDataType = + ConfigAssignmentUtils.getPropertyType(ctx, entrySchema, mapping.getKey()); + logger.info("For Complex Type Resource: key ({}), value ({}), type ({})", mapping.getKey(), + responseKeyValue, propertyTypeForDataType); + JsonUtils.populateJsonNodeValues(mapping.getValue(), responseKeyValue, propertyTypeForDataType, + objectNode); + } + } else { + objectNode = (ObjectNode) responseNode; + } + ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, objectNode); + } + } + + @SuppressWarnings("squid:S3776") + public static synchronized List convertResoureAssignmentDataList( + List resourceAssignmentDataList) { + List assignments = new ArrayList<>(); + if (CollectionUtils.isNotEmpty(resourceAssignmentDataList)) { + for (ResourceAssignmentData resourceAssignmentData : resourceAssignmentDataList) { + if (resourceAssignmentData != null) { + ResourceAssignment resourceAssignment = new ResourceAssignment(); + resourceAssignment.setName(resourceAssignmentData.getTemplateKeyName()); + resourceAssignment.setVersion(resourceAssignmentData.getVersion()); + resourceAssignment.setUpdatedBy(resourceAssignmentData.getUpdatedBy()); + resourceAssignment.setUpdatedDate(resourceAssignmentData.getUpdatedDate()); + resourceAssignment.setDictionaryName(resourceAssignmentData.getResourceName()); + resourceAssignment.setDictionarySource(resourceAssignmentData.getSource()); + resourceAssignment.setStatus(resourceAssignmentData.getStatus()); + resourceAssignment.setMessage(resourceAssignmentData.getMessage()); + PropertyDefinition property = new PropertyDefinition(); + property.setType(resourceAssignmentData.getDataType()); + + if (StringUtils.isNotBlank(resourceAssignmentData.getResourceValue())) { + if (ValidTypes.getPrimitivePropertType().contains(resourceAssignmentData.getDataType())) { + property.setValue(resourceAssignmentData.getResourceValue()); + } else { + JsonNode valueNode = + TransformationUtils.getJsonNodeForString(resourceAssignmentData.getResourceValue()); + property.setValue(valueNode); + } + } + if (StringUtils.isNotBlank(resourceAssignmentData.getEntrySchema())) { + EntrySchema entrySchema = new EntrySchema(); + entrySchema.setType(resourceAssignmentData.getEntrySchema()); + property.setEntrySchema(entrySchema); + } else { + property.setEntrySchema(null); + } + resourceAssignment.setProperty(property); + assignments.add(resourceAssignment); + } + } + + } + return assignments; + } + + @SuppressWarnings("squid:S3776") + public static synchronized List convertResoureAssignmentList( + List assignments) { + List resourceAssignmentDataList = new ArrayList<>(); + if (CollectionUtils.isNotEmpty(assignments)) { + for (ResourceAssignment assignment : assignments) { + if (assignment != null) { + ResourceAssignmentData resourceAssignmentData = new ResourceAssignmentData(); + resourceAssignmentData.setTemplateKeyName(assignment.getName()); + resourceAssignmentData.setVersion(assignment.getVersion()); + resourceAssignmentData.setUpdatedBy(assignment.getUpdatedBy()); + resourceAssignmentData.setUpdatedDate(assignment.getUpdatedDate()); + if (assignment.getProperty() != null) { + resourceAssignmentData.setDataType(assignment.getProperty().getType()); + if (assignment.getProperty().getEntrySchema() != null) { + resourceAssignmentData.setEntrySchema(assignment.getProperty().getEntrySchema().getType()); + } + if (assignment.getProperty().getValue() != null) { + String valueContent = TransformationUtils.getJson(assignment.getProperty().getValue()); + resourceAssignmentData.setResourceValue(valueContent); + } + } + resourceAssignmentData.setResourceName(assignment.getDictionaryName()); + resourceAssignmentData.setSource(assignment.getDictionarySource()); + resourceAssignmentData.setStatus(assignment.getStatus()); + resourceAssignmentData.setMessage(assignment.getMessage()); + resourceAssignmentDataList.add(resourceAssignmentData); + } + } + } + return resourceAssignmentDataList; + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigPreviewService.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigPreviewService.java new file mode 100644 index 000000000..071b5a548 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ConfigPreviewService.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.features.assignment.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.features.assignment.data.ResourceAssignmentData; +import org.onap.ccsdk.features.data.adaptor.domain.ConfigResource; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.generator.data.ConfigGeneratorInfo; +import org.onap.ccsdk.features.generator.service.ConfigGeneratorService; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.service.ConfigModelService; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ConfigPreviewService { + private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentPersistService.class); + private ConfigResourceService configResourceService; + private ConfigModelService configModelService; + private ConfigGeneratorService configGeneratorService; + + public ConfigPreviewService(ConfigResourceService configResourceService, ConfigModelService configModelService, + ConfigGeneratorService configGeneratorService) { + this.configResourceService = configResourceService; + this.configModelService = configModelService; + this.configGeneratorService = configGeneratorService; + } + + public String generatePreview(String templateContent, String templateData) throws SvcLogicException { + String mashedData = ""; + ConfigGeneratorInfo configGeneratorInfo = + configGeneratorService.generateConfiguration(templateContent, templateData); + if (configGeneratorInfo != null) { + mashedData = configGeneratorInfo.getMashedData(); + } + return mashedData; + } + + public ResourceAssignmentData generateTemplateResourceMash(ResourceAssignmentData resourceAssignmentData) + throws SvcLogicException { + if (resourceAssignmentData == null) { + throw new SvcLogicException("Resource assignment data is missing"); + } + if (StringUtils.isBlank(resourceAssignmentData.getServiceTemplateName())) { + throw new SvcLogicException("Service template name is missing"); + } + if (StringUtils.isBlank(resourceAssignmentData.getServiceTemplateVersion())) { + throw new SvcLogicException("Service template version is missing"); + } + if (StringUtils.isBlank(resourceAssignmentData.getResourceType())) { + throw new SvcLogicException("Resource type is missing"); + } + if (StringUtils.isBlank(resourceAssignmentData.getResourceId())) { + throw new SvcLogicException("Resource Id is missing"); + } + if (StringUtils.isBlank(resourceAssignmentData.getActionName())) { + throw new SvcLogicException("Action name is missing"); + } + + String serviceTemplateName = resourceAssignmentData.getServiceTemplateName(); + String serviceTemplateVersion = resourceAssignmentData.getServiceTemplateVersion(); + String actionName = resourceAssignmentData.getActionName(); + String resourceId = resourceAssignmentData.getResourceId(); + String resourceType = resourceAssignmentData.getResourceType(); + String inputData = "{}"; + + Map context = new HashMap<>(); + context.put(ConfigModelConstant.PROPERTY_ACTION_NAME, actionName); + context = configModelService.prepareContext(context, inputData, serviceTemplateName, serviceTemplateVersion); + + ConfigResource configResourceQuery = new ConfigResource(); + configResourceQuery.setServiceTemplateVersion(serviceTemplateName); + configResourceQuery.setServiceTemplateVersion(serviceTemplateVersion); + configResourceQuery.setRecipeName(actionName); + configResourceQuery.setResourceId(resourceId); + configResourceQuery.setResourceType(resourceType); + + List configResources = configResourceService.getConfigResource(configResourceQuery); + if (CollectionUtils.isNotEmpty(configResources)) { + for (ConfigResource cr : configResources) { + String templateContent = context + .get(ConfigModelConstant.PROPERTY_NODE_TEMPLATES_DOT + cr.getTemplateName() + ".content"); + String templateData = cr.getResourceData(); + String previewContent = generatePreview(templateContent, templateData); + resourceAssignmentData.getTemplatesMashedContents().put(cr.getTemplateName(), previewContent); + logger.info("Preview generated for template name ({}) ", cr.getTemplateName()); + logger.trace("Preview generated for preview ({}) ", previewContent); + } + } else { + logger.info( + "Couldn't get config resource for service template name ({}) service template version ({})" + + " action ({}) resource id ({}) resource type ({})", + serviceTemplateName, serviceTemplateVersion, actionName, resourceId, resourceType); + } + return resourceAssignmentData; + + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ResourceDictionaryService.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ResourceDictionaryService.java new file mode 100644 index 000000000..ec586f493 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ResourceDictionaryService.java @@ -0,0 +1,112 @@ +/* + * 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.features.assignment.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.data.dict.ResourceDefinition; +import org.onap.ccsdk.features.model.domain.ResourceDictionary; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.features.rest.adaptor.ConfigRestAdaptorConstants; +import org.onap.ccsdk.features.rest.adaptor.ConfigRestAdaptorException; +import org.onap.ccsdk.features.rest.adaptor.service.ConfigRestAdaptorService; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ResourceDictionaryService { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(ResourceDictionaryService.class); + private ConfigRestAdaptorService configRestAdaptorService; + + public ResourceDictionaryService(ConfigRestAdaptorService configRestAdaptorService) { + this.configRestAdaptorService = configRestAdaptorService; + } + + @SuppressWarnings("squid:S3776") + public Map getDataDictionaryDefinitions(List resourceAssignments) + throws SvcLogicException { + try { + Map dictionaries = new HashMap<>(); + if (resourceAssignments != null) { + List names = new ArrayList<>(); + for (ResourceAssignment resourceAssignment : resourceAssignments) { + if (resourceAssignment != null && StringUtils.isNotBlank(resourceAssignment.getDictionaryName())) { + + if (!names.contains(resourceAssignment.getDictionaryName())) { + names.add(resourceAssignment.getDictionaryName()); + } + + if (resourceAssignment.getDependencies() != null + && !resourceAssignment.getDependencies().isEmpty()) { + List dependencieNames = resourceAssignment.getDependencies(); + for (String dependencieName : dependencieNames) { + if (StringUtils.isNotBlank(dependencieName) && !names.contains(dependencieName)) { + names.add(dependencieName); + } + } + } + } + } + queryResourceDictionaryDefinitions(dictionaries, names); + } + return dictionaries; + } catch (Exception e) { + throw new SvcLogicException("Failed in getting resource data dictionary : " + e.getMessage()); + } + + } + + @SuppressWarnings("squid:S3776") + private void queryResourceDictionaryDefinitions(Map dictionaries, List names) + throws SvcLogicException, ConfigRestAdaptorException { + logger.info("Getting resource dictionary definition for the names ({})", names); + if (!names.isEmpty()) { + + String dictionaryContents = configRestAdaptorService.postResource( + ConfigRestAdaptorConstants.SELECTOR_MODEL_SERVICE, "dictionarybynames", names, String.class); + + if (StringUtils.isNotBlank(dictionaryContents)) { + List dataDictionaries = + TransformationUtils.getListfromJson(dictionaryContents, ResourceDictionary.class); + if (dataDictionaries != null) { + for (ResourceDictionary dataDictionary : dataDictionaries) { + if (dataDictionary != null && StringUtils.isNotBlank(dataDictionary.getName()) + && StringUtils.isNotBlank(dataDictionary.getDefinition())) { + ResourceDefinition resourceDefinition = TransformationUtils + .readValue(dataDictionary.getDefinition(), ResourceDefinition.class); + if (resourceDefinition != null && StringUtils.isNotBlank(resourceDefinition.getName())) { + dictionaries.put(resourceDefinition.getName(), resourceDefinition); + } else { + throw new SvcLogicException( + "Failed in getting resource data dictionary definition for : " + + dataDictionary.getName()); + } + } + } + } + } else { + logger.warn("No resource dictionary definition found for the names ({})", names); + } + } + } +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ResourceModelService.java b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ResourceModelService.java new file mode 100644 index 000000000..befa36a34 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/main/java/org/onap/ccsdk/features/assignment/service/ResourceModelService.java @@ -0,0 +1,97 @@ +/* + * 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.features.assignment.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.service.ConfigModelService; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.features.model.validator.ResourceAssignmentValidator; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ResourceModelService { + private static EELFLogger logger = EELFManager.getInstance().getLogger(ResourceModelService.class); + + private ConfigModelService configModelService; + + public ResourceModelService(ConfigModelService configModelService) { + this.configModelService = configModelService; + } + + public Map getTemplatesContents(SvcLogicContext ctx, List templateNames) + throws SvcLogicException { + Map templatesContents = new HashMap<>(); + try { + if (CollectionUtils.isNotEmpty(templateNames)) { + for (String templateName : templateNames) { + String templateContent = this.configModelService.getNodeTemplateContent(ctx, templateName); + logger.trace("Processing template ({}) with content : {}", templateName, templateContent); + templatesContents.put(templateName, templateContent); + } + } + } catch (Exception e) { + throw new SvcLogicException(e.getMessage()); + } + return templatesContents; + } + + public Map> getTemplatesResourceAssignments(SvcLogicContext ctx, + List templateNames) throws SvcLogicException { + Map> templatesResourceAssignments = new HashMap<>(); + try { + if (CollectionUtils.isNotEmpty(templateNames)) { + for (String templateName : templateNames) { + String resourceMappingContent = this.configModelService.getNodeTemplateMapping(ctx, templateName); + logger.info("Processing template ({}) with resource assignment content : {}", templateName, + resourceMappingContent); + + if (StringUtils.isNotBlank(resourceMappingContent)) { + + List resourceAssignments = + TransformationUtils.getListfromJson(resourceMappingContent, ResourceAssignment.class); + + if (resourceAssignments != null) { + ResourceAssignmentValidator resourceAssignmentValidator = + new ResourceAssignmentValidator(resourceAssignments); + resourceAssignmentValidator.validateResourceAssignment(); + logger.info("Resource assignment validated successfully for the template ({})", + templateName); + templatesResourceAssignments.put(templateName, resourceAssignments); + } else { + throw new SvcLogicException(String.format( + "Failed to convert assignment content (%s) to object", resourceMappingContent)); + } + } else { + // Do nothing, because som e templates may not have mappings + } + } + } + } catch (Exception e) { + throw new SvcLogicException(e.getMessage()); + } + + return templatesResourceAssignments; + } +} diff --git a/blueprints-processor/plugin/assignment-provider/src/main/resources/org/opendaylight/blueprint/impl-blueprint.xml b/blueprints-processor/plugin/assignment-provider/src/main/resources/org/opendaylight/blueprint/impl-blueprint.xml index baa6bdbc5..f15429dfe 100644 --- a/blueprints-processor/plugin/assignment-provider/src/main/resources/org/opendaylight/blueprint/impl-blueprint.xml +++ b/blueprints-processor/plugin/assignment-provider/src/main/resources/org/opendaylight/blueprint/impl-blueprint.xml @@ -21,23 +21,23 @@ odl:use-default-for-reference-types="true"> + interface="org.onap.ccsdk.features.model.service.ComponentNodeService" /> + interface="org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService" /> + interface="org.onap.ccsdk.features.model.service.ConfigModelService" /> + interface="org.onap.ccsdk.features.rest.adaptor.service.ConfigRestAdaptorService" /> + interface="org.onap.ccsdk.features.generator.service.ConfigGeneratorService" /> + class="org.onap.ccsdk.features.assignment.service.ConfigAssignmentNode"> @@ -46,10 +46,10 @@ + interface="org.onap.ccsdk.features.assignment.service.ConfigAssignmentNode" /> + class="org.onap.ccsdk.features.assignment.service.ConfigAssignmentServiceImpl"> @@ -58,6 +58,6 @@ + interface="org.onap.ccsdk.features.assignment.service.ConfigAssignmentService" /> diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/DBResourceProcessorTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/DBResourceProcessorTest.java deleted file mode 100644 index 5a704e995..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/DBResourceProcessorTest.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * 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.assignment.processor; - -import static org.mockito.Matchers.any; -import java.io.File; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.io.FileUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; -import org.onap.ccsdk.config.assignment.service.ConfigResourceAssignmentTestUtils; -import org.onap.ccsdk.config.data.adaptor.domain.TransactionLog; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.data.dict.ResourceDefinition; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -@RunWith(MockitoJUnitRunner.class) -public class DBResourceProcessorTest { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(DBResourceProcessorTest.class); - - @Mock - private ConfigResourceService configResourceService; - - @SuppressWarnings("unchecked") - @Before - public void before() { - MockitoAnnotations.initMocks(this); - - try { - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - if (args != null) { - logger.trace("Transaction info " + Arrays.asList(args)); - } - return null; - } - }).when(configResourceService).save(any(TransactionLog.class)); - - } catch (SvcLogicException e) { - e.printStackTrace(); - } - } - - @Test - public void testDbSimpleProcess() throws Exception { - logger.info(" ******************************* testDbSimpleProcess ***************************"); - - Mockito.doAnswer(new Answer>>() { - @Override - public List> answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - List> results = new ArrayList<>(); - if (args != null) { - logger.info("Query " + Arrays.asList(args)); - Map record = new HashMap<>(); - record.put("country", "US"); - results.add(record); - } - return results; - } - }).when(configResourceService).query(Matchers.anyString(), Matchers.>any()); - - String recipeName = "sample-recipe"; - - String resourceassignmentContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/db/resource-assignments-simple.json"), Charset.defaultCharset()); - List batchResourceAssignment = - TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); - - String dictionaryContent = FileUtils.readFileToString(new File("src/test/resources/mapping/db/db-simple.json"), - Charset.defaultCharset()); - Map dictionaries = - ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); - DBResourceProcessor dbResourceProcessor = new DBResourceProcessor(configResourceService); - Map componentContext = new HashMap<>(); - componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); - componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); - componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); - - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); - - Map inParams = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - dbResourceProcessor.process(inParams, ctx, componentContext); - - logger.info(" Context " + componentContext); - - } - - @Test - public void testDbComplexProcess() throws Exception { - logger.info(" ******************************* testDbComplexProcess ***************************"); - - Mockito.doAnswer(new Answer>>() { - @Override - public List> answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - List> results = new ArrayList<>(); - if (args != null) { - logger.info("Query " + Arrays.asList(args)); - Map record = new HashMap<>(); - record.put("db-country", "US"); - record.put("db-state", "NJ"); - results.add(record); - } - return results; - } - }).when(configResourceService).query(Matchers.anyString(), Matchers.>any()); - - String recipeName = "sample-recipe"; - - String resourceassignmentContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/db/resource-assignments-complex.json"), Charset.defaultCharset()); - List batchResourceAssignment = - TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); - - String dictionaryContent = FileUtils.readFileToString(new File("src/test/resources/mapping/db/db-complex.json"), - Charset.defaultCharset()); - Map dictionaries = - ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); - DBResourceProcessor dbResourceProcessor = new DBResourceProcessor(configResourceService); - Map componentContext = new HashMap<>(); - componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); - componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); - componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); - - Map inParams = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - String datatypeContent = FileUtils.readFileToString(new File("src/test/resources/mapping/db/dt-location.json"), - Charset.defaultCharset()); - ctx.setAttribute("data_types.dt-location", datatypeContent); - dbResourceProcessor.process(inParams, ctx, componentContext); - - } - - @Test - public void testDbArrayComplexProcess() throws Exception { - logger.info(" ******************************* testDbArrayComplexProcess ***************************"); - Mockito.doAnswer(new Answer>>() { - @Override - public List> answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - List> results = new ArrayList<>(); - if (args != null) { - logger.info("Query " + Arrays.asList(args)); - Map record = new HashMap<>(); - record.put("db-country", "US"); - record.put("db-state", "NJ"); - results.add(record); - - Map record2 = new HashMap<>(); - record2.put("db-country", "INDIA"); - record2.put("db-state", "TN"); - results.add(record2); - } - return results; - } - }).when(configResourceService).query(Matchers.anyString(), Matchers.>any()); - - String recipeName = "sample-recipe"; - - String resourceassignmentContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/db/resource-assignments-array.json"), Charset.defaultCharset()); - List batchResourceAssignment = - TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); - - String dictionaryContent = FileUtils.readFileToString(new File("src/test/resources/mapping/db/db-array.json"), - Charset.defaultCharset()); - Map dictionaries = - ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); - DBResourceProcessor dbResourceProcessor = new DBResourceProcessor(configResourceService); - Map componentContext = new HashMap<>(); - componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); - componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); - componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); - - Map inParams = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - String datatypeContent = FileUtils.readFileToString(new File("src/test/resources/mapping/db/dt-location.json"), - Charset.defaultCharset()); - ctx.setAttribute("data_types.dt-location", datatypeContent); - dbResourceProcessor.process(inParams, ctx, componentContext); - logger.info("Component Context = ({})", componentContext); - Assert.assertNotNull("faile dto populate Array Complex response ", componentContext); - - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/DefaultResourceProcessorTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/DefaultResourceProcessorTest.java deleted file mode 100644 index 7e8d14201..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/DefaultResourceProcessorTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * 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.assignment.processor; - -import static org.mockito.Matchers.any; -import java.io.File; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.io.FileUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; -import org.onap.ccsdk.config.assignment.service.ConfigResourceAssignmentTestUtils; -import org.onap.ccsdk.config.data.adaptor.domain.TransactionLog; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.data.dict.ResourceDefinition; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -@RunWith(MockitoJUnitRunner.class) -public class DefaultResourceProcessorTest { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(DefaultResourceProcessorTest.class); - - @Mock - private ConfigResourceService configResourceService; - - @SuppressWarnings("unchecked") - @Before - public void before() { - MockitoAnnotations.initMocks(this); - - try { - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - if (args != null) { - logger.trace("Transaction info " + Arrays.asList(args)); - } - return null; - } - }).when(configResourceService).save(any(TransactionLog.class)); - - } catch (SvcLogicException e) { - e.printStackTrace(); - } - } - - @Test - public void testDefaultSimpleProcess() throws Exception { - logger.info(" ******************************* testDefaultSimpleProcess ***************************"); - - String recipeName = "sample-recipe"; - - String resourceassignmentContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/default/resource-assignments-simple.json"), - Charset.defaultCharset()); - List batchResourceAssignment = - TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); - - String dictionaryContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/default/default-simple.json"), Charset.defaultCharset()); - Map dictionaries = - ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); - - DefaultResourceProcessor defaultResourceProcessor = new DefaultResourceProcessor(configResourceService); - Map componentContext = new HashMap<>(); - componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); - componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); - componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); - - Map inParams = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - defaultResourceProcessor.process(inParams, ctx, componentContext); - logger.trace(" componentContext " + componentContext); - - Assert.assertEquals("Failed to populate default country value ", "US", - componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.country")); - Assert.assertEquals("Failed to populate default country value ", "US", - componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.country")); - - Assert.assertEquals("Failed to populate default port value ", 830, - componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.port")); - Assert.assertEquals("Failed to populate default port value ", 830, - componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.port")); - - Assert.assertEquals("Failed to populate default voip-enabled value ", true, - componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.voip-enabled")); - Assert.assertEquals("Failed to populate default voip-enabled value ", true, - componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.voip-enabled")); - - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/InputResourceProcessorTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/InputResourceProcessorTest.java deleted file mode 100644 index 2aabdb3d9..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/InputResourceProcessorTest.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * 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.assignment.processor; - -import static org.mockito.Matchers.any; -import java.io.File; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.io.FileUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; -import org.onap.ccsdk.config.assignment.service.ConfigResourceAssignmentTestUtils; -import org.onap.ccsdk.config.data.adaptor.domain.TransactionLog; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.data.dict.ResourceDefinition; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -@RunWith(MockitoJUnitRunner.class) -public class InputResourceProcessorTest { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(InputResourceProcessorTest.class); - - @Mock - private ConfigResourceService configResourceService; - - @SuppressWarnings("unchecked") - @Before - public void before() { - MockitoAnnotations.initMocks(this); - - try { - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - if (args != null) { - logger.trace("Transaction info " + Arrays.asList(args)); - } - return null; - } - }).when(configResourceService).save(any(TransactionLog.class)); - - } catch (SvcLogicException e) { - e.printStackTrace(); - } - } - - @Test - public void testInputSimpleProcess() throws Exception { - logger.info(" ******************************* testInputSimpleProcess ***************************"); - - String recipeName = "sample-recipe"; - - String resourceassignmentContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/input/resource-assignments-simple.json"), - Charset.defaultCharset()); - List batchResourceAssignment = - TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); - - String dictionaryContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/default/default-simple.json"), Charset.defaultCharset()); - Map dictionaries = - ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); - - InputResourceProcessor inputResourceProcessor = new InputResourceProcessor(configResourceService); - Map componentContext = new HashMap<>(); - componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); - componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); - componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); - - Map inParams = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - ctx.setAttribute("country", "US"); - ctx.setAttribute("port", "830"); - ctx.setAttribute("voip-enabled", "true"); - - inputResourceProcessor.process(inParams, ctx, componentContext); - logger.trace(" componentContext " + componentContext); - - Assert.assertEquals("Failed to populate default recipe country value ", "US", - componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.country")); - Assert.assertEquals("Failed to populate default dictionary country value ", "US", - componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.country")); - - Assert.assertEquals("Failed to populate default recipe port value ", 830, - componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.port")); - Assert.assertEquals("Failed to populate default dictionary port value ", 830, - componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.port")); - - Assert.assertEquals("Failed to populate default recipe voip-enabled value ", true, - componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.voip-enabled")); - Assert.assertEquals("Failed to populate default dictionary voip-enabled value ", true, - componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.voip-enabled")); - - } - - @Test - public void testInputComplexProcess() throws Exception { - logger.info(" ******************************* testInputComplexProcess ***************************"); - - String recipeName = "sample-recipe"; - - String resourceassignmentContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/input/resource-assignments-complex.json"), - Charset.defaultCharset()); - List batchResourceAssignment = - TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); - - String dictionaryContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/input/input-complex.json"), Charset.defaultCharset()); - Map dictionaries = - ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); - - InputResourceProcessor inputResourceProcessor = new InputResourceProcessor(configResourceService); - Map componentContext = new HashMap<>(); - componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); - componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); - componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); - - Map inParams = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - String datatypeContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/input/dt-location.json"), Charset.defaultCharset()); - ctx.setAttribute("data_types.dt-location", datatypeContent); - - String samplelocation = FileUtils.readFileToString( - new File("src/test/resources/mapping/input/sample-location.json"), Charset.defaultCharset()); - ctx.setAttribute("location", samplelocation); - - inputResourceProcessor.process(inParams, ctx, componentContext); - - logger.trace(" componentContext " + componentContext); - logger.trace(" Resource Mapping " + TransformationUtils.getJson(batchResourceAssignment, true)); - - Assert.assertNotNull("Failed to populate input recipe location value ", - componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.location")); - Assert.assertNotNull("Failed to populate input dictionary location value ", - componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.location")); - - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/MdsalResourceProcessorTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/MdsalResourceProcessorTest.java deleted file mode 100644 index 2d651c836..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/processor/MdsalResourceProcessorTest.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * 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.assignment.processor; - -import java.io.File; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.io.FileUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; -import org.onap.ccsdk.config.assignment.service.ConfigResourceAssignmentTestUtils; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.data.dict.ResourceDefinition; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.config.rest.adaptor.service.ConfigRestAdaptorService; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -@RunWith(MockitoJUnitRunner.class) -public class MdsalResourceProcessorTest { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(MdsalResourceProcessorTest.class); - - @Mock - private ConfigRestAdaptorService configRestAdaptorService; - - @SuppressWarnings("unchecked") - @Before - public void before() { - - } - - @Test - @SuppressWarnings("unchecked") - public void testMdsalSimpleProcess() throws Exception { - logger.info(" ******************************* testMdsalSimpleProcess ***************************"); - - Mockito.doAnswer(new Answer() { - @Override - public String answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - String response = null; - if (args != null) { - response = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/simple-response.json"), - Charset.defaultCharset()); - logger.info(" Returning response :" + response); - } - return response; - } - }).when(configRestAdaptorService).getResource(Matchers.anyString(), Matchers.anyString(), - Matchers.any(Class.class)); - - String recipeName = "sample-recipe"; - - String resourceassignmentContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/resource-assignments-simple.json"), - Charset.defaultCharset()); - List batchResourceAssignment = - TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); - - String dictionaryContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/mdsal-simple.json"), Charset.defaultCharset()); - Map dictionaries = - ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); - MdsalResourceProcessor mdsalResourceProcessor = new MdsalResourceProcessor(configRestAdaptorService); - Map componentContext = new HashMap<>(); - componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); - componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); - componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); - - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); - - Map inParams = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - mdsalResourceProcessor.process(inParams, ctx, componentContext); - - } - - @SuppressWarnings("unchecked") - @Test - public void testMDSALComplexProcess() throws Exception { - logger.info(" ******************************* testMDSALComplexProcess ***************************"); - - Mockito.doAnswer(new Answer() { - @Override - public String answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - String response = null; - if (args != null) { - response = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/complex-response.json"), - Charset.defaultCharset()); - } - return response; - } - }).when(configRestAdaptorService).getResource(Matchers.anyString(), Matchers.anyString(), - Matchers.any(Class.class)); - - String recipeName = "sample-recipe"; - - String resourceassignmentContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/resource-assignments-complex.json"), - Charset.defaultCharset()); - List batchResourceAssignment = - TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); - - String dictionaryContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/mdsal-complex.json"), Charset.defaultCharset()); - Map dictionaries = - ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); - MdsalResourceProcessor dbResourceProcessor = new MdsalResourceProcessor(configRestAdaptorService); - Map componentContext = new HashMap<>(); - componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); - componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); - componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); - - Map inParams = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - String datatypeContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/dt-location.json"), Charset.defaultCharset()); - ctx.setAttribute("data_types.dt-location", datatypeContent); - dbResourceProcessor.process(inParams, ctx, componentContext); - - } - - @Test - @SuppressWarnings("unchecked") - public void testMDSALArrayComplexProcess() throws Exception { - logger.info(" ******************************* testMDSALArrayComplexProcess ***************************"); - - Mockito.doAnswer(new Answer() { - @Override - public String answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - String response = null; - if (args != null) { - response = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/array-complex-response.json"), - Charset.defaultCharset()); - } - return response; - } - }).when(configRestAdaptorService).getResource(Matchers.anyString(), Matchers.anyString(), - Matchers.any(Class.class)); - - String recipeName = "sample-recipe"; - - String resourceassignmentContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/resource-assignments-array.json"), Charset.defaultCharset()); - List batchResourceAssignment = - TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); - - String dictionaryContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/mdsal-array.json"), Charset.defaultCharset()); - - Map dictionaries = - ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); - MdsalResourceProcessor dbResourceProcessor = new MdsalResourceProcessor(configRestAdaptorService); - Map componentContext = new HashMap<>(); - componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); - componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); - componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); - - Map inParams = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - String datatypeContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/dt-location.json"), Charset.defaultCharset()); - ctx.setAttribute("data_types.dt-location", datatypeContent); - dbResourceProcessor.process(inParams, ctx, componentContext); - logger.info("Component Context = ({})", componentContext); - Assert.assertNotNull("failed to populate Array Complex response ", componentContext); - - } - - @Test - @SuppressWarnings("unchecked") - public void testMDSALArraySimpleProcess() throws Exception { - logger.info(" ******************************* testMDSALArrayComplexProcess ***************************"); - - Mockito.doAnswer(new Answer() { - @Override - public String answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - String response = null; - if (args != null) { - response = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/array-complex-v4-assigned-response.json"), - Charset.defaultCharset()); - } - return response; - } - }).when(configRestAdaptorService).getResource(Matchers.anyString(), Matchers.anyString(), - Matchers.any(Class.class)); - - String recipeName = "sample-recipe"; - - String resourceassignmentContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/resource-assignments-complex-simple.json"), - Charset.defaultCharset()); - List batchResourceAssignment = - TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); - - String dictionaryContent = FileUtils.readFileToString( - new File("src/test/resources/mapping/Mdsal/mdsal-array-v4iplist.json"), Charset.defaultCharset()); - Map dictionaries = - ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); - MdsalResourceProcessor mdsalResourceProcessor = new MdsalResourceProcessor(configRestAdaptorService); - Map componentContext = new HashMap<>(); - componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); - componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); - componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".service-instance-id", - "3c8d5a63-a793-4206-a67c-4b2e8e648196"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".oam-network-role", - "sample"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".oam-ipv4-ip-type", - "sample"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); - componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".oam-vm-type", "sample"); - - Map inParams = new HashMap<>(); - SvcLogicContext ctx = new SvcLogicContext(); - // String datatypeContent = FileUtils.readFileToString(new - // File("src/test/resources/mapping/Mdsal/dt-v4-assigned-ip-list.json"), Charset.defaultCharset() ); - // ctx.setAttribute("data_types.dt-v4-assigned-ip-list", datatypeContent); - mdsalResourceProcessor.process(inParams, ctx, componentContext); - logger.info("Component Context = ({})", componentContext); - Assert.assertNotNull("failed to populate Array Complex response ", componentContext); - Assert.assertEquals("Compare String ", "10.66.1.152", - componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + recipeName + ".v4-ip-prefix")); - - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentNodeTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentNodeTest.java deleted file mode 100644 index 9ad94dcd0..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ConfigAssignmentNodeTest.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * 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.assignment.service; - -import java.io.File; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.sling.testing.mock.osgi.MockOsgi; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.runners.MockitoJUnitRunner; -import org.onap.ccsdk.config.assignment.ConfigAssignmentConstants; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.generator.service.ConfigGeneratorService; -import org.onap.ccsdk.config.generator.service.ConfigGeneratorServiceImpl; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.service.ComponentNodeDelegate; -import org.onap.ccsdk.config.model.service.ComponentNodeService; -import org.onap.ccsdk.config.model.service.ComponentNodeServiceImpl; -import org.onap.ccsdk.config.model.service.ConfigModelService; -import org.onap.ccsdk.config.model.service.ConfigModelServiceImpl; -import org.onap.ccsdk.config.rest.adaptor.service.ConfigRestAdaptorService; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.osgi.framework.BundleContext; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -@RunWith(MockitoJUnitRunner.class) -public class ConfigAssignmentNodeTest { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentNodeTest.class); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Mock - private ConfigResourceService configResourceService; - - @Mock - private ConfigRestAdaptorService configRestAdaptorService; - - private ConfigModelService configModelService; - - private ComponentNodeService componentNodeService; - - private ConfigGeneratorService configGeneratorService; - - BundleContext bundleContext = MockOsgi.newBundleContext(); - - @SuppressWarnings("unchecked") - @Before - public void before() throws Exception { - MockitoAnnotations.initMocks(this); - /* - * ConfigAssignmentNode configAssignmentNode = new ConfigAssignmentNode(componentNodeService, - * configResourceService, configModelService, configRestAdaptorService, configGeneratorService); - * bundleContext.registerService(ConfigAssignmentNode.class, configAssignmentNode, null); - */ - } - - @Test - public void testResourceAssignment() throws Exception { - ConfigResourceAssignmentTestUtils.injectTransactionLogSaveMock(configResourceService); - - ConfigResourceAssignmentTestUtils.injectConfigModelMock(configRestAdaptorService, "resource_assignment"); - - ConfigResourceAssignmentTestUtils.injectResourceDictionaryMock(configRestAdaptorService, - "assignments/empty-dictionary.json"); - - ConfigResourceAssignmentTestUtils.injectConfigResourceSaveMock(configResourceService); - - componentNodeService = - new ComponentNodeServiceImpl(bundleContext, configResourceService, configRestAdaptorService); - configModelService = new ConfigModelServiceImpl(configRestAdaptorService); - configGeneratorService = new ConfigGeneratorServiceImpl(configResourceService); - - ConfigAssignmentNode configAssignmentNode = new ConfigAssignmentNode(configResourceService, - configRestAdaptorService, configModelService, componentNodeService, configGeneratorService); - - String inputContent = FileUtils.readFileToString( - new File("src/test/resources/service_templates/input/input.json"), Charset.defaultCharset()); - - Map inParams = new HashMap<>(); - inParams.put(ConfigModelConstant.PROPERTY_SELECTOR, "test"); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_REQUEST_ID, "1234"); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_ID, "resourceid-1234"); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_TYPE, "vnf-type"); - inParams.put(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_NAME, "vpe-201802-baseconfig"); - inParams.put(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_VERSION, "1.0.0"); - inParams.put(ConfigModelConstant.PROPERTY_ACTION_NAME, "resource-assignment-action"); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_INPUT_DATA, inputContent); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_TEMPLATE_NAMES, "[\"base-config-template\"]"); - - // Populate the SvcContext ( Simulation) - SvcLogicContext svcLogicContext = new SvcLogicContext(); - Map context = new HashMap<>(); - context.put(ConfigModelConstant.PROPERTY_ACTION_NAME, "resource-assignment-action"); - context = configModelService.prepareContext(context, inputContent, "vpe-201802-baseconfig", "1.0.0"); - context.forEach((key, value) -> svcLogicContext.setAttribute(key, value)); - - Map componentContext = new HashMap<>(); - configAssignmentNode.process(inParams, svcLogicContext, componentContext); - Assert.assertNotNull("Failed to get response status", svcLogicContext.getAttribute("test.status")); - - } - - @Test - public void testSimplePreview() throws Exception { - ConfigResourceAssignmentTestUtils.injectTransactionLogSaveMock(configResourceService); - - ConfigResourceAssignmentTestUtils.injectConfigModelMock(configRestAdaptorService, "resource_assignment"); - - ConfigResourceAssignmentTestUtils.injectResourceDictionaryMock(configRestAdaptorService, - "assignments/empty-dictionary.json"); - - ConfigResourceAssignmentTestUtils.injectConfigResourceSaveMock(configResourceService); - - componentNodeService = - new ComponentNodeServiceImpl(bundleContext, configResourceService, configRestAdaptorService); - configModelService = new ConfigModelServiceImpl(configRestAdaptorService); - configGeneratorService = new ConfigGeneratorServiceImpl(configResourceService); - - ConfigAssignmentNode configAssignmentNode = new ConfigAssignmentNode(configResourceService, - configRestAdaptorService, configModelService, componentNodeService, configGeneratorService); - - String inputContent = FileUtils.readFileToString( - new File("src/test/resources/service_templates/input/input.json"), Charset.defaultCharset()); - - Map inParams = new HashMap<>(); - inParams.put(ConfigModelConstant.PROPERTY_SELECTOR, "test"); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_REQUEST_ID, "1234"); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_ID, "resourceid-1234"); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_TYPE, "vnf-type"); - inParams.put(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_NAME, "vpe-201802-baseconfig"); - inParams.put(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_VERSION, "1.0.0"); - inParams.put(ConfigModelConstant.PROPERTY_ACTION_NAME, "resource-assignment-action"); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_INPUT_DATA, inputContent); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_TEMPLATE_NAMES, "[\"base-config-template\"]"); - SvcLogicContext ctx = new SvcLogicContext(); - configAssignmentNode.process(inParams, ctx); - Assert.assertNotNull("Failed to get response mashed Content", - ctx.getAttribute("test.mashed-data.base-config-template")); - } - - @Test - public void testComplexPreview() throws Exception { - ConfigResourceAssignmentTestUtils.injectTransactionLogSaveMock(configResourceService); - - ConfigResourceAssignmentTestUtils.injectConfigModelMock(configRestAdaptorService, "vpe-201802-baseconfig"); - - ConfigResourceAssignmentTestUtils.injectResourceDictionaryMock(configRestAdaptorService, - "service_templates/vpe-201802-baseconfig/dict.json"); - - ConfigResourceAssignmentTestUtils.injectConfigResourceSaveMock(configResourceService); - - componentNodeService = - new ComponentNodeServiceImpl(bundleContext, configResourceService, configRestAdaptorService); - configModelService = new ConfigModelServiceImpl(configRestAdaptorService); - configGeneratorService = new ConfigGeneratorServiceImpl(configResourceService); - - ConfigAssignmentNode configAssignmentNode = new ConfigAssignmentNode(configResourceService, - configRestAdaptorService, configModelService, componentNodeService, configGeneratorService); - - String inputContent = FileUtils.readFileToString( - new File("src/test/resources/service_templates/vpe-201802-baseconfig/input-complex.json"), - Charset.defaultCharset()); - - Map inParams = new HashMap<>(); - inParams.put(ConfigModelConstant.PROPERTY_SELECTOR, "complex-test"); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_REQUEST_ID, "request-1234"); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_ID, "resourceid-1234"); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_TYPE, "vnf-type"); - inParams.put(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_NAME, "vpe-201802-baseconfig"); - inParams.put(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_VERSION, "1.0.0"); - inParams.put(ConfigModelConstant.PROPERTY_ACTION_NAME, "resource-assignment-action"); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_INPUT_DATA, inputContent); - inParams.put(ConfigAssignmentConstants.INPUT_PARAM_TEMPLATE_NAMES, "[\"base-config-template\"]"); - SvcLogicContext ctx = new SvcLogicContext(); - configAssignmentNode.process(inParams, ctx); - Assert.assertNotNull("Failed to get response mashed Content", - ctx.getAttribute("complex-test.mashed-data.base-config-template")); - - } - - @Test - public void inputValidator() { - SvcLogicContext ctx = new SvcLogicContext(); - try { - - logger.info(" ******************************* inputValidator ***************************"); - String serviceTemplateContent = FileUtils.readFileToString( - new File("src/test/resources/service_templates/resource_assignment.json"), - Charset.defaultCharset()); - - String inputcontent = FileUtils.readFileToString( - new File("src/test/resources/service_templates/input/inputValidateTest.json"), - Charset.defaultCharset()); - - Map context = new HashMap<>(); - configModelService.prepareContext(context, inputcontent, serviceTemplateContent); - - // TransformationUtils.printMap(context); - - context.forEach((name, value) -> { - if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(value)) { - ctx.setAttribute(name, value); - } - }); - - ComponentNodeDelegate componentNodeDelegate = new ComponentNodeDelegate(componentNodeService); - Map inParams = new HashMap<>(); - inParams.put(ConfigModelConstant.PROPERTY_SELECTOR, "resource-assignment"); - componentNodeDelegate.process(inParams, ctx); - Assert.fail(); - } catch (Exception e) { - logger.error("Failed in inputValidator" + e.getMessage()); - logger.info("** ctx.getAttribute Check for **" + ctx.getAttribute("resource-assignment.error-message")); - } - - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ConfigPreviewServiceTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ConfigPreviewServiceTest.java deleted file mode 100644 index 75b7f2e28..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ConfigPreviewServiceTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * 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.assignment.service; - -import java.io.File; -import java.nio.charset.Charset; -import org.apache.commons.io.FileUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.runners.MockitoJUnitRunner; -import org.onap.ccsdk.config.assignment.data.ResourceAssignmentData; -import org.onap.ccsdk.config.data.adaptor.domain.ConfigResource; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.generator.service.ConfigGeneratorService; -import org.onap.ccsdk.config.generator.service.ConfigGeneratorServiceImpl; -import org.onap.ccsdk.config.model.service.ConfigModelService; -import org.onap.ccsdk.config.model.service.ConfigModelServiceImpl; -import org.onap.ccsdk.config.rest.adaptor.service.ConfigRestAdaptorService; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -@RunWith(MockitoJUnitRunner.class) -public class ConfigPreviewServiceTest { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigPreviewServiceTest.class); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Mock - private ConfigResourceService configResourceService; - - @Mock - private ConfigRestAdaptorService configRestAdaptorService; - - private ConfigModelService configModelService; - private ConfigGeneratorService configGeneratorService; - - @SuppressWarnings("unchecked") - @Before - public void before() throws Exception { - MockitoAnnotations.initMocks(this); - } - - @Test - public void testGenerateTemplateResourceMash() throws Exception { - - ConfigResourceAssignmentTestUtils.injectTransactionLogSaveMock(configResourceService); - - ConfigResourceAssignmentTestUtils.injectConfigModelMock(configRestAdaptorService, "resource_assignment"); - - ConfigResourceAssignmentTestUtils.injectResourceDictionaryMock(configRestAdaptorService, - "assignments/empty-dictionary.json"); - - ConfigResource configResourceQuery = new ConfigResource(); - configResourceQuery.setServiceTemplateVersion("sample-serviceTemplateName"); - configResourceQuery.setServiceTemplateVersion("1.0.0"); - configResourceQuery.setRecipeName("sample-action"); - configResourceQuery.setResourceId("123-resourceId"); - configResourceQuery.setResourceType("sample-resourceType"); - configResourceQuery.setTemplateName("base-config-template"); - String inputContent = FileUtils.readFileToString( - new File("src/test/resources/service_templates/input/input.json"), Charset.defaultCharset()); - configResourceQuery.setResourceData(inputContent); - - ConfigResourceAssignmentTestUtils.injectGetConfigResourceMock(configResourceService, configResourceQuery); - - configModelService = new ConfigModelServiceImpl(configRestAdaptorService); - configGeneratorService = new ConfigGeneratorServiceImpl(configResourceService); - - ConfigPreviewService configPreviewService = - new ConfigPreviewService(configResourceService, configModelService, configGeneratorService); - - ResourceAssignmentData resourceAssignmentData = new ResourceAssignmentData(); - resourceAssignmentData.setResourceId("123-resourceId"); - resourceAssignmentData.setResourceType("sample-resourceType"); - resourceAssignmentData.setServiceTemplateName("sample-serviceTemplateName"); - resourceAssignmentData.setServiceTemplateVersion("1.0.0"); - resourceAssignmentData.setActionName("sample-action"); - - resourceAssignmentData = configPreviewService.generateTemplateResourceMash(resourceAssignmentData); - - Assert.assertNotNull("Failed to get GenerateTemplateResourceMash response.", resourceAssignmentData); - Assert.assertNotNull("Failed to get template mashed contents.", - resourceAssignmentData.getTemplatesMashedContents()); - - Assert.assertNotNull("Failed to get base-config template mashed contents.", - resourceAssignmentData.getTemplatesMashedContents().get("base-config-template")); - } -} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ConfigResourceAssignmentTestUtils.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ConfigResourceAssignmentTestUtils.java deleted file mode 100644 index ee1c076ae..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ConfigResourceAssignmentTestUtils.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * 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.assignment.service; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import java.io.File; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.onap.ccsdk.config.data.adaptor.domain.ConfigResource; -import org.onap.ccsdk.config.data.adaptor.domain.TransactionLog; -import org.onap.ccsdk.config.data.adaptor.service.ConfigResourceService; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.data.dict.ResourceDefinition; -import org.onap.ccsdk.config.model.domain.ConfigModel; -import org.onap.ccsdk.config.model.domain.ConfigModelContent; -import org.onap.ccsdk.config.rest.adaptor.service.ConfigRestAdaptorService; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class ConfigResourceAssignmentTestUtils { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigResourceAssignmentTestUtils.class); - - public static void injectTransactionLogSaveMock(ConfigResourceService configResourceService) throws Exception { - Mockito.doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - if (args != null) { - logger.trace("Transaction info " + Arrays.asList(args)); - } - return null; - } - }).when(configResourceService).save(any(TransactionLog.class)); - } - - public static void injectConfigModelMock(ConfigRestAdaptorService configRestAdaptorService, - String serviceTemplateName) throws Exception { - - Mockito.doAnswer(new Answer() { - @Override - public org.onap.ccsdk.config.model.domain.ConfigModel answer(InvocationOnMock invocationOnMock) - throws Throwable { - Object[] args = invocationOnMock.getArguments(); - org.onap.ccsdk.config.model.domain.ConfigModel serviceArtifact = null; - if (args != null && args.length == 3) { - - logger.info("Artifact info " + Arrays.asList(args)); - String modelContent = IOUtils.toString( - ConfigResourceAssignmentTestUtils.class.getClassLoader().getResourceAsStream( - "service_templates/" + serviceTemplateName + "/" + serviceTemplateName + ".json"), - Charset.defaultCharset()); - - ConfigModelContent configModelContent = new ConfigModelContent(); - configModelContent.setContent(modelContent); - configModelContent.setContentType(ConfigModelConstant.MODEL_CONTENT_TYPE_TOSCA_JSON); - - List configModelContents = new ArrayList<>(); - configModelContents.add(configModelContent); - - String velocityDir = ConfigResourceAssignmentTestUtils.class.getClassLoader() - .getResource("service_templates/" + serviceTemplateName + "/velocity").getPath(); - - Collection templateFiles = - FileUtils.listFiles(new File(velocityDir), new String[] {"vtl"}, true); - logger.info("Template Files info " + templateFiles); - for (File templateFile : templateFiles) { - String templateContent = FileUtils.readFileToString(templateFile, Charset.defaultCharset()); - ConfigModelContent configModelTemplateContent = new ConfigModelContent(); - configModelTemplateContent.setContent(templateContent); - configModelTemplateContent.setName(FilenameUtils.getBaseName(templateFile.getName())); - configModelTemplateContent.setContentType(ConfigModelConstant.MODEL_CONTENT_TYPE_TEMPLATE); - configModelContents.add(configModelTemplateContent); - } - - serviceArtifact = new org.onap.ccsdk.config.model.domain.ConfigModel(); - serviceArtifact.setArtifactName(String.valueOf(args[0])); - serviceArtifact.setArtifactVersion(String.valueOf(args[1])); - serviceArtifact.setPublished("Y"); - serviceArtifact.setConfigModelContents(configModelContents); - } - - return serviceArtifact; - } - }).when(configRestAdaptorService).getResource(anyString(), anyString(), Matchers.any(Class.class)); - } - - public static void injectResourceDictionaryMock(ConfigRestAdaptorService configRestAdaptorService, - String dictionaryFileName) throws Exception { - - Mockito.doAnswer(new Answer() { - @Override - public String answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - String dictionaties = "[]"; - if (args != null) { - logger.info("getResourceDictionaryByNames " + Arrays.asList(args)); - dictionaties = IOUtils.toString( - ConfigAssignmentNodeTest.class.getClassLoader().getResourceAsStream(dictionaryFileName), - Charset.defaultCharset()); - } - return dictionaties; - } - }).when(configRestAdaptorService).postResource(Matchers.any(), Matchers.any(), Matchers.any(), - Matchers.any(Class.class)); - } - - public static void injectConfigResourceSaveMock(ConfigResourceService configResourceService) throws Exception { - Mockito.doAnswer(new Answer() { - @Override - public ConfigResource answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - ConfigResource configResource = null; - if (args != null) { - configResource = (ConfigResource) args[0]; - logger.info("Config Resource Save info " + configResource); - return configResource; - } - return configResource; - } - }).when(configResourceService).saveConfigResource(any(ConfigResource.class)); - } - - public static void injectGetConfigResourceMock(ConfigResourceService configResourceService, - ConfigResource configResource) throws Exception { - Mockito.doAnswer(new Answer>() { - @Override - public List answer(InvocationOnMock invocationOnMock) throws Throwable { - Object[] args = invocationOnMock.getArguments(); - List configResources = new ArrayList<>(); - if (args != null) { - configResources.add(configResource); - } - return configResources; - } - }).when(configResourceService).getConfigResource(any(ConfigResource.class)); - } - - public static String getFileContent(String filePath) throws Exception { - return IOUtils.toString(ConfigResourceAssignmentTestUtils.class.getClassLoader().getResourceAsStream(filePath), - Charset.defaultCharset()); - } - - public static Map getMapfromJson(String content) { - try { - ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(content, new TypeReference>() {}); - } catch (Exception e) { - logger.info("getMapfromJson Exception ({})", e); - } - return null; - } -} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ResourceAssignmentGenerationTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ResourceAssignmentGenerationTest.java deleted file mode 100644 index 3dc7da7eb..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ResourceAssignmentGenerationTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * 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.assignment.service; - -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.commons.io.IOUtils; -import org.junit.Assert; -import org.junit.Test; -import org.onap.ccsdk.config.model.ConfigModelConstant; -import org.onap.ccsdk.config.model.ValidTypes; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.utils.ResourceAssignmentUtils; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; - -public class ResourceAssignmentGenerationTest { - - private static EELFLogger logger = EELFManager.getInstance().getLogger(ResourceAssignmentGenerationTest.class); - - @Test - public void testResourceDataSetting() { - try { - logger.info(" **************** testResourceDataSetting *****************"); - String resourceAssignmentContents = IOUtils.toString(TopologicalSortingTest.class.getClassLoader() - .getResourceAsStream("assignments/alltype-empty-value-mapping.json"), Charset.defaultCharset()); - - List assignments = - TransformationUtils.getListfromJson(resourceAssignmentContents, ResourceAssignment.class); - if (assignments != null) { - Map componentContext = new HashMap<>(); - componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, "sample-recipe"); - for (ResourceAssignment resourceAssignment : assignments) { - if (resourceAssignment != null && resourceAssignment.getProperty() != null) { - String type = resourceAssignment.getProperty().getType(); - Object value = null; - if (ValidTypes.DATA_TYPE_STRING.equals(type)) { - value = new String("abcdef"); - } else if (ValidTypes.DATA_TYPE_INTEGER.equals(type)) { - value = new Integer(1234); - } else if (ValidTypes.DATA_TYPE_BOOLEAN.equals(type)) { - value = new Boolean(true); - } else if (ValidTypes.DATA_TYPE_LIST.equals(type)) { - String entityType = resourceAssignment.getProperty().getEntrySchema().getType(); - if (ValidTypes.DATA_TYPE_STRING.equals(entityType)) { - value = "[\"abcd-array\"]"; - } else { - String content = "[{\"name\" : \"abcd-array-complex\"}]"; - JsonNode node = TransformationUtils.getJsonNodeForString(content); - value = node; - } - } else { - String content = "{\"name\" : \"abcd-complex\"}"; - JsonNode node = TransformationUtils.getJsonNodeForString(content); - value = node; - } - ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, value); - } - } - String generatedData = ResourceAssignmentUtils.generateResourceDataForAssignments(assignments); - logger.trace("Generated Data " + generatedData); - - Assert.assertNotNull("Failed to generate resource data", generatedData); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testGenerateResourceData() { - try { - logger.info(" **************** testGenerateResourceData *****************"); - String resourceAssignmentContents = IOUtils.toString(TopologicalSortingTest.class.getClassLoader() - .getResourceAsStream("assignments/alltype-mapping.json"), Charset.defaultCharset()); - - List assignments = - TransformationUtils.getListfromJson(resourceAssignmentContents, ResourceAssignment.class); - if (assignments != null) { - - String generatedData = ResourceAssignmentUtils.generateResourceDataForAssignments(assignments); - logger.trace("Generated Data " + generatedData); - - Assert.assertNotNull("Failed to generate resource data", generatedData); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ResourceAssignmentValidation.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ResourceAssignmentValidation.java deleted file mode 100644 index d708404f5..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/ResourceAssignmentValidation.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * 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.assignment.service; - -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.List; -import org.apache.commons.io.IOUtils; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.onap.ccsdk.config.model.ConfigModelException; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.config.model.validator.ResourceAssignmentValidator; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class ResourceAssignmentValidation { - private static EELFLogger logger = EELFManager.getInstance().getLogger(ResourceAssignmentValidation.class); - - @Rule - public final ExpectedException exception = ExpectedException.none(); - - @Test - public void testValidateSuccess() { - try { - logger.info(" **************** testValidateSuccess *****************"); - String resourceMapping = IOUtils.toString( - TopologicalSortingTest.class.getClassLoader().getResourceAsStream("validation/success.json"), - Charset.defaultCharset()); - - List assignments = - TransformationUtils.getListfromJson(resourceMapping, ResourceAssignment.class); - if (assignments != null) { - ResourceAssignmentValidator resourceAssignmentValidator = new ResourceAssignmentValidator(assignments); - - boolean result = resourceAssignmentValidator.validateResourceAssignment(); - Assert.assertTrue("Failed to Validate", result); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test(expected = ConfigModelException.class) - public void testValidateDuplicate() throws IOException, ConfigModelException { - logger.info(" **************** testValidateDuplicate *****************"); - String resourceMapping = IOUtils.toString( - TopologicalSortingTest.class.getClassLoader().getResourceAsStream("validation/duplicate.json"), - Charset.defaultCharset()); - - List assignments = - TransformationUtils.getListfromJson(resourceMapping, ResourceAssignment.class); - if (assignments != null) { - ResourceAssignmentValidator resourceAssignmentValidator = new ResourceAssignmentValidator(assignments); - resourceAssignmentValidator.validateResourceAssignment(); - } - - } - - @Test(expected = ConfigModelException.class) - public void testValidateCyclic() throws IOException, ConfigModelException { - logger.info(" **************** testValidateCyclic *****************"); - String resourceMapping = IOUtils.toString( - TopologicalSortingTest.class.getClassLoader().getResourceAsStream("validation/cyclic.json"), - Charset.defaultCharset()); - - List assignments = - TransformationUtils.getListfromJson(resourceMapping, ResourceAssignment.class); - if (assignments != null) { - ResourceAssignmentValidator resourceAssignmentValidator = new ResourceAssignmentValidator(assignments); - - resourceAssignmentValidator.validateResourceAssignment(); - } - - } -} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/TopologicalSortingTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/TopologicalSortingTest.java deleted file mode 100644 index e4b7f5dee..000000000 --- a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/config/assignment/service/TopologicalSortingTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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.assignment.service; - -import java.nio.charset.Charset; -import java.util.List; -import org.apache.commons.io.IOUtils; -import org.junit.Assert; -import org.junit.Test; -import org.onap.ccsdk.config.assignment.processor.ResourceAssignmentProcessor; -import org.onap.ccsdk.config.model.data.ResourceAssignment; -import org.onap.ccsdk.config.model.utils.TransformationUtils; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class TopologicalSortingTest { - private static EELFLogger logger = EELFManager.getInstance().getLogger(TopologicalSortingTest.class); - - @Test - public void testBulkSequencingMapping() { - try { - logger.info(" **************** Bulk Sequencing Default *****************"); - String resourceMapping = IOUtils.toString( - TopologicalSortingTest.class.getClassLoader().getResourceAsStream("mapping/dependency.json"), - Charset.defaultCharset()); - - List assignments = - TransformationUtils.getListfromJson(resourceMapping, ResourceAssignment.class); - if (assignments != null) { - SvcLogicContext ctx = new SvcLogicContext(); - ResourceAssignmentProcessor resourceAssignmentProcessor = - new ResourceAssignmentProcessor(assignments, ctx); - List> sequenceBatchResourceAssignment = resourceAssignmentProcessor.process(); - - Assert.assertNotNull("Failed to populate Sequence Bulk Mappings", sequenceBatchResourceAssignment); - Assert.assertNotEquals("Failed to populate Sequence Bulk Mappings size ", - (sequenceBatchResourceAssignment.size() > 0)); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - -} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/DBResourceProcessorTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/DBResourceProcessorTest.java new file mode 100644 index 000000000..43a4881d5 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/DBResourceProcessorTest.java @@ -0,0 +1,232 @@ +/* + * 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.features.assignment.processor; + +import static org.mockito.Matchers.any; +import java.io.File; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.io.FileUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; +import org.onap.ccsdk.features.assignment.processor.DBResourceProcessor; +import org.onap.ccsdk.features.assignment.service.ConfigResourceAssignmentTestUtils; +import org.onap.ccsdk.features.data.adaptor.domain.TransactionLog; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.data.dict.ResourceDefinition; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +@RunWith(MockitoJUnitRunner.class) +public class DBResourceProcessorTest { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(DBResourceProcessorTest.class); + + @Mock + private ConfigResourceService configResourceService; + + @SuppressWarnings("unchecked") + @Before + public void before() { + MockitoAnnotations.initMocks(this); + + try { + Mockito.doAnswer(new Answer() { + @Override + public Void answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + if (args != null) { + logger.trace("Transaction info " + Arrays.asList(args)); + } + return null; + } + }).when(configResourceService).save(any(TransactionLog.class)); + + } catch (SvcLogicException e) { + e.printStackTrace(); + } + } + + @Test + public void testDbSimpleProcess() throws Exception { + logger.info(" ******************************* testDbSimpleProcess ***************************"); + + Mockito.doAnswer(new Answer>>() { + @Override + public List> answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + List> results = new ArrayList<>(); + if (args != null) { + logger.info("Query " + Arrays.asList(args)); + Map record = new HashMap<>(); + record.put("country", "US"); + results.add(record); + } + return results; + } + }).when(configResourceService).query(Matchers.anyString(), Matchers.>any()); + + String recipeName = "sample-recipe"; + + String resourceassignmentContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/db/resource-assignments-simple.json"), Charset.defaultCharset()); + List batchResourceAssignment = + TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); + + String dictionaryContent = FileUtils.readFileToString(new File("src/test/resources/mapping/db/db-simple.json"), + Charset.defaultCharset()); + Map dictionaries = + ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); + DBResourceProcessor dbResourceProcessor = new DBResourceProcessor(configResourceService); + Map componentContext = new HashMap<>(); + componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); + componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); + componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); + + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); + + Map inParams = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + dbResourceProcessor.process(inParams, ctx, componentContext); + + logger.info(" Context " + componentContext); + + } + + @Test + public void testDbComplexProcess() throws Exception { + logger.info(" ******************************* testDbComplexProcess ***************************"); + + Mockito.doAnswer(new Answer>>() { + @Override + public List> answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + List> results = new ArrayList<>(); + if (args != null) { + logger.info("Query " + Arrays.asList(args)); + Map record = new HashMap<>(); + record.put("db-country", "US"); + record.put("db-state", "NJ"); + results.add(record); + } + return results; + } + }).when(configResourceService).query(Matchers.anyString(), Matchers.>any()); + + String recipeName = "sample-recipe"; + + String resourceassignmentContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/db/resource-assignments-complex.json"), Charset.defaultCharset()); + List batchResourceAssignment = + TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); + + String dictionaryContent = FileUtils.readFileToString(new File("src/test/resources/mapping/db/db-complex.json"), + Charset.defaultCharset()); + Map dictionaries = + ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); + DBResourceProcessor dbResourceProcessor = new DBResourceProcessor(configResourceService); + Map componentContext = new HashMap<>(); + componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); + componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); + componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); + + Map inParams = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + String datatypeContent = FileUtils.readFileToString(new File("src/test/resources/mapping/db/dt-location.json"), + Charset.defaultCharset()); + ctx.setAttribute("data_types.dt-location", datatypeContent); + dbResourceProcessor.process(inParams, ctx, componentContext); + + } + + @Test + public void testDbArrayComplexProcess() throws Exception { + logger.info(" ******************************* testDbArrayComplexProcess ***************************"); + Mockito.doAnswer(new Answer>>() { + @Override + public List> answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + List> results = new ArrayList<>(); + if (args != null) { + logger.info("Query " + Arrays.asList(args)); + Map record = new HashMap<>(); + record.put("db-country", "US"); + record.put("db-state", "NJ"); + results.add(record); + + Map record2 = new HashMap<>(); + record2.put("db-country", "INDIA"); + record2.put("db-state", "TN"); + results.add(record2); + } + return results; + } + }).when(configResourceService).query(Matchers.anyString(), Matchers.>any()); + + String recipeName = "sample-recipe"; + + String resourceassignmentContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/db/resource-assignments-array.json"), Charset.defaultCharset()); + List batchResourceAssignment = + TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); + + String dictionaryContent = FileUtils.readFileToString(new File("src/test/resources/mapping/db/db-array.json"), + Charset.defaultCharset()); + Map dictionaries = + ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); + DBResourceProcessor dbResourceProcessor = new DBResourceProcessor(configResourceService); + Map componentContext = new HashMap<>(); + componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); + componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); + componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); + + Map inParams = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + String datatypeContent = FileUtils.readFileToString(new File("src/test/resources/mapping/db/dt-location.json"), + Charset.defaultCharset()); + ctx.setAttribute("data_types.dt-location", datatypeContent); + dbResourceProcessor.process(inParams, ctx, componentContext); + logger.info("Component Context = ({})", componentContext); + Assert.assertNotNull("faile dto populate Array Complex response ", componentContext); + + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/DefaultResourceProcessorTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/DefaultResourceProcessorTest.java new file mode 100644 index 000000000..df3800387 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/DefaultResourceProcessorTest.java @@ -0,0 +1,128 @@ +/* + * 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.features.assignment.processor; + +import static org.mockito.Matchers.any; +import java.io.File; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.io.FileUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; +import org.onap.ccsdk.features.assignment.processor.DefaultResourceProcessor; +import org.onap.ccsdk.features.assignment.service.ConfigResourceAssignmentTestUtils; +import org.onap.ccsdk.features.data.adaptor.domain.TransactionLog; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.data.dict.ResourceDefinition; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +@RunWith(MockitoJUnitRunner.class) +public class DefaultResourceProcessorTest { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(DefaultResourceProcessorTest.class); + + @Mock + private ConfigResourceService configResourceService; + + @SuppressWarnings("unchecked") + @Before + public void before() { + MockitoAnnotations.initMocks(this); + + try { + Mockito.doAnswer(new Answer() { + @Override + public Void answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + if (args != null) { + logger.trace("Transaction info " + Arrays.asList(args)); + } + return null; + } + }).when(configResourceService).save(any(TransactionLog.class)); + + } catch (SvcLogicException e) { + e.printStackTrace(); + } + } + + @Test + public void testDefaultSimpleProcess() throws Exception { + logger.info(" ******************************* testDefaultSimpleProcess ***************************"); + + String recipeName = "sample-recipe"; + + String resourceassignmentContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/default/resource-assignments-simple.json"), + Charset.defaultCharset()); + List batchResourceAssignment = + TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); + + String dictionaryContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/default/default-simple.json"), Charset.defaultCharset()); + Map dictionaries = + ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); + + DefaultResourceProcessor defaultResourceProcessor = new DefaultResourceProcessor(configResourceService); + Map componentContext = new HashMap<>(); + componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); + componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); + componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); + + Map inParams = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + defaultResourceProcessor.process(inParams, ctx, componentContext); + logger.trace(" componentContext " + componentContext); + + Assert.assertEquals("Failed to populate default country value ", "US", + componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.country")); + Assert.assertEquals("Failed to populate default country value ", "US", + componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.country")); + + Assert.assertEquals("Failed to populate default port value ", 830, + componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.port")); + Assert.assertEquals("Failed to populate default port value ", 830, + componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.port")); + + Assert.assertEquals("Failed to populate default voip-enabled value ", true, + componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.voip-enabled")); + Assert.assertEquals("Failed to populate default voip-enabled value ", true, + componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.voip-enabled")); + + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/InputResourceProcessorTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/InputResourceProcessorTest.java new file mode 100644 index 000000000..cd0b7828e --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/InputResourceProcessorTest.java @@ -0,0 +1,179 @@ +/* + * 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.features.assignment.processor; + +import static org.mockito.Matchers.any; +import java.io.File; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.io.FileUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; +import org.onap.ccsdk.features.assignment.processor.InputResourceProcessor; +import org.onap.ccsdk.features.assignment.service.ConfigResourceAssignmentTestUtils; +import org.onap.ccsdk.features.data.adaptor.domain.TransactionLog; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.data.dict.ResourceDefinition; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +@RunWith(MockitoJUnitRunner.class) +public class InputResourceProcessorTest { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(InputResourceProcessorTest.class); + + @Mock + private ConfigResourceService configResourceService; + + @SuppressWarnings("unchecked") + @Before + public void before() { + MockitoAnnotations.initMocks(this); + + try { + Mockito.doAnswer(new Answer() { + @Override + public Void answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + if (args != null) { + logger.trace("Transaction info " + Arrays.asList(args)); + } + return null; + } + }).when(configResourceService).save(any(TransactionLog.class)); + + } catch (SvcLogicException e) { + e.printStackTrace(); + } + } + + @Test + public void testInputSimpleProcess() throws Exception { + logger.info(" ******************************* testInputSimpleProcess ***************************"); + + String recipeName = "sample-recipe"; + + String resourceassignmentContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/input/resource-assignments-simple.json"), + Charset.defaultCharset()); + List batchResourceAssignment = + TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); + + String dictionaryContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/default/default-simple.json"), Charset.defaultCharset()); + Map dictionaries = + ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); + + InputResourceProcessor inputResourceProcessor = new InputResourceProcessor(configResourceService); + Map componentContext = new HashMap<>(); + componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); + componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); + componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); + + Map inParams = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + ctx.setAttribute("country", "US"); + ctx.setAttribute("port", "830"); + ctx.setAttribute("voip-enabled", "true"); + + inputResourceProcessor.process(inParams, ctx, componentContext); + logger.trace(" componentContext " + componentContext); + + Assert.assertEquals("Failed to populate default recipe country value ", "US", + componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.country")); + Assert.assertEquals("Failed to populate default dictionary country value ", "US", + componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.country")); + + Assert.assertEquals("Failed to populate default recipe port value ", 830, + componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.port")); + Assert.assertEquals("Failed to populate default dictionary port value ", 830, + componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.port")); + + Assert.assertEquals("Failed to populate default recipe voip-enabled value ", true, + componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.voip-enabled")); + Assert.assertEquals("Failed to populate default dictionary voip-enabled value ", true, + componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.voip-enabled")); + + } + + @Test + public void testInputComplexProcess() throws Exception { + logger.info(" ******************************* testInputComplexProcess ***************************"); + + String recipeName = "sample-recipe"; + + String resourceassignmentContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/input/resource-assignments-complex.json"), + Charset.defaultCharset()); + List batchResourceAssignment = + TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); + + String dictionaryContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/input/input-complex.json"), Charset.defaultCharset()); + Map dictionaries = + ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); + + InputResourceProcessor inputResourceProcessor = new InputResourceProcessor(configResourceService); + Map componentContext = new HashMap<>(); + componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); + componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); + componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); + + Map inParams = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + String datatypeContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/input/dt-location.json"), Charset.defaultCharset()); + ctx.setAttribute("data_types.dt-location", datatypeContent); + + String samplelocation = FileUtils.readFileToString( + new File("src/test/resources/mapping/input/sample-location.json"), Charset.defaultCharset()); + ctx.setAttribute("location", samplelocation); + + inputResourceProcessor.process(inParams, ctx, componentContext); + + logger.trace(" componentContext " + componentContext); + logger.trace(" Resource Mapping " + TransformationUtils.getJson(batchResourceAssignment, true)); + + Assert.assertNotNull("Failed to populate input recipe location value ", + componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + "sample-recipe.location")); + Assert.assertNotNull("Failed to populate input dictionary location value ", + componentContext.get(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + "sample-recipe.location")); + + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/MdsalResourceProcessorTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/MdsalResourceProcessorTest.java new file mode 100644 index 000000000..5f73f32e3 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/processor/MdsalResourceProcessorTest.java @@ -0,0 +1,269 @@ +/* + * 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.features.assignment.processor; + +import java.io.File; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.io.FileUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.stubbing.Answer; +import org.onap.ccsdk.features.assignment.processor.MdsalResourceProcessor; +import org.onap.ccsdk.features.assignment.service.ConfigResourceAssignmentTestUtils; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.data.dict.ResourceDefinition; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.features.rest.adaptor.service.ConfigRestAdaptorService; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +@RunWith(MockitoJUnitRunner.class) +public class MdsalResourceProcessorTest { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(MdsalResourceProcessorTest.class); + + @Mock + private ConfigRestAdaptorService configRestAdaptorService; + + @SuppressWarnings("unchecked") + @Before + public void before() { + + } + + @Test + @SuppressWarnings("unchecked") + public void testMdsalSimpleProcess() throws Exception { + logger.info(" ******************************* testMdsalSimpleProcess ***************************"); + + Mockito.doAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + String response = null; + if (args != null) { + response = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/simple-response.json"), + Charset.defaultCharset()); + logger.info(" Returning response :" + response); + } + return response; + } + }).when(configRestAdaptorService).getResource(Matchers.anyString(), Matchers.anyString(), + Matchers.any(Class.class)); + + String recipeName = "sample-recipe"; + + String resourceassignmentContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/resource-assignments-simple.json"), + Charset.defaultCharset()); + List batchResourceAssignment = + TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); + + String dictionaryContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/mdsal-simple.json"), Charset.defaultCharset()); + Map dictionaries = + ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); + MdsalResourceProcessor mdsalResourceProcessor = new MdsalResourceProcessor(configRestAdaptorService); + Map componentContext = new HashMap<>(); + componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); + componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); + componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); + + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); + + Map inParams = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + mdsalResourceProcessor.process(inParams, ctx, componentContext); + + } + + @SuppressWarnings("unchecked") + @Test + public void testMDSALComplexProcess() throws Exception { + logger.info(" ******************************* testMDSALComplexProcess ***************************"); + + Mockito.doAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + String response = null; + if (args != null) { + response = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/complex-response.json"), + Charset.defaultCharset()); + } + return response; + } + }).when(configRestAdaptorService).getResource(Matchers.anyString(), Matchers.anyString(), + Matchers.any(Class.class)); + + String recipeName = "sample-recipe"; + + String resourceassignmentContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/resource-assignments-complex.json"), + Charset.defaultCharset()); + List batchResourceAssignment = + TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); + + String dictionaryContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/mdsal-complex.json"), Charset.defaultCharset()); + Map dictionaries = + ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); + MdsalResourceProcessor dbResourceProcessor = new MdsalResourceProcessor(configRestAdaptorService); + Map componentContext = new HashMap<>(); + componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); + componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); + componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); + + Map inParams = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + String datatypeContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/dt-location.json"), Charset.defaultCharset()); + ctx.setAttribute("data_types.dt-location", datatypeContent); + dbResourceProcessor.process(inParams, ctx, componentContext); + + } + + @Test + @SuppressWarnings("unchecked") + public void testMDSALArrayComplexProcess() throws Exception { + logger.info(" ******************************* testMDSALArrayComplexProcess ***************************"); + + Mockito.doAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + String response = null; + if (args != null) { + response = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/array-complex-response.json"), + Charset.defaultCharset()); + } + return response; + } + }).when(configRestAdaptorService).getResource(Matchers.anyString(), Matchers.anyString(), + Matchers.any(Class.class)); + + String recipeName = "sample-recipe"; + + String resourceassignmentContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/resource-assignments-array.json"), Charset.defaultCharset()); + List batchResourceAssignment = + TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); + + String dictionaryContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/mdsal-array.json"), Charset.defaultCharset()); + + Map dictionaries = + ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); + MdsalResourceProcessor dbResourceProcessor = new MdsalResourceProcessor(configRestAdaptorService); + Map componentContext = new HashMap<>(); + componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); + componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); + componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); + + Map inParams = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + String datatypeContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/dt-location.json"), Charset.defaultCharset()); + ctx.setAttribute("data_types.dt-location", datatypeContent); + dbResourceProcessor.process(inParams, ctx, componentContext); + logger.info("Component Context = ({})", componentContext); + Assert.assertNotNull("failed to populate Array Complex response ", componentContext); + + } + + @Test + @SuppressWarnings("unchecked") + public void testMDSALArraySimpleProcess() throws Exception { + logger.info(" ******************************* testMDSALArrayComplexProcess ***************************"); + + Mockito.doAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + String response = null; + if (args != null) { + response = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/array-complex-v4-assigned-response.json"), + Charset.defaultCharset()); + } + return response; + } + }).when(configRestAdaptorService).getResource(Matchers.anyString(), Matchers.anyString(), + Matchers.any(Class.class)); + + String recipeName = "sample-recipe"; + + String resourceassignmentContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/resource-assignments-complex-simple.json"), + Charset.defaultCharset()); + List batchResourceAssignment = + TransformationUtils.getListfromJson(resourceassignmentContent, ResourceAssignment.class); + + String dictionaryContent = FileUtils.readFileToString( + new File("src/test/resources/mapping/Mdsal/mdsal-array-v4iplist.json"), Charset.defaultCharset()); + Map dictionaries = + ConfigResourceAssignmentTestUtils.getMapfromJson(dictionaryContent); + MdsalResourceProcessor mdsalResourceProcessor = new MdsalResourceProcessor(configRestAdaptorService); + Map componentContext = new HashMap<>(); + componentContext.put(ConfigModelConstant.PROPERTY_RESOURCE_ASSIGNMENTS, batchResourceAssignment); + componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, recipeName); + componentContext.put(ConfigModelConstant.PROPERTY_TEMPLATE_NAME, "sample-template"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARIES, dictionaries); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".service-instance-id", + "3c8d5a63-a793-4206-a67c-4b2e8e648196"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".oam-network-role", + "sample"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".oam-ipv4-ip-type", + "sample"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".profile_name", "sample"); + componentContext.put(ConfigModelConstant.PROPERTY_DICTIONARY_KEY_DOT + recipeName + ".oam-vm-type", "sample"); + + Map inParams = new HashMap<>(); + SvcLogicContext ctx = new SvcLogicContext(); + // String datatypeContent = FileUtils.readFileToString(new + // File("src/test/resources/mapping/Mdsal/dt-v4-assigned-ip-list.json"), Charset.defaultCharset() ); + // ctx.setAttribute("data_types.dt-v4-assigned-ip-list", datatypeContent); + mdsalResourceProcessor.process(inParams, ctx, componentContext); + logger.info("Component Context = ({})", componentContext); + Assert.assertNotNull("failed to populate Array Complex response ", componentContext); + Assert.assertEquals("Compare String ", "10.66.1.152", + componentContext.get(ConfigModelConstant.PROPERTY_RECIPE_KEY_DOT + recipeName + ".v4-ip-prefix")); + + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentNodeTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentNodeTest.java new file mode 100644 index 000000000..41911e91d --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ConfigAssignmentNodeTest.java @@ -0,0 +1,247 @@ +/* + * 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.features.assignment.service; + +import java.io.File; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.sling.testing.mock.osgi.MockOsgi; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.ccsdk.features.assignment.ConfigAssignmentConstants; +import org.onap.ccsdk.features.assignment.service.ConfigAssignmentNode; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.generator.service.ConfigGeneratorService; +import org.onap.ccsdk.features.generator.service.ConfigGeneratorServiceImpl; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.service.ComponentNodeDelegate; +import org.onap.ccsdk.features.model.service.ComponentNodeService; +import org.onap.ccsdk.features.model.service.ComponentNodeServiceImpl; +import org.onap.ccsdk.features.model.service.ConfigModelService; +import org.onap.ccsdk.features.model.service.ConfigModelServiceImpl; +import org.onap.ccsdk.features.rest.adaptor.service.ConfigRestAdaptorService; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.osgi.framework.BundleContext; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +@RunWith(MockitoJUnitRunner.class) +public class ConfigAssignmentNodeTest { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigAssignmentNodeTest.class); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Mock + private ConfigResourceService configResourceService; + + @Mock + private ConfigRestAdaptorService configRestAdaptorService; + + private ConfigModelService configModelService; + + private ComponentNodeService componentNodeService; + + private ConfigGeneratorService configGeneratorService; + + BundleContext bundleContext = MockOsgi.newBundleContext(); + + @SuppressWarnings("unchecked") + @Before + public void before() throws Exception { + MockitoAnnotations.initMocks(this); + /* + * ConfigAssignmentNode configAssignmentNode = new ConfigAssignmentNode(componentNodeService, + * configResourceService, configModelService, configRestAdaptorService, configGeneratorService); + * bundleContext.registerService(ConfigAssignmentNode.class, configAssignmentNode, null); + */ + } + + @Test + public void testResourceAssignment() throws Exception { + ConfigResourceAssignmentTestUtils.injectTransactionLogSaveMock(configResourceService); + + ConfigResourceAssignmentTestUtils.injectConfigModelMock(configRestAdaptorService, "resource_assignment"); + + ConfigResourceAssignmentTestUtils.injectResourceDictionaryMock(configRestAdaptorService, + "assignments/empty-dictionary.json"); + + ConfigResourceAssignmentTestUtils.injectConfigResourceSaveMock(configResourceService); + + componentNodeService = + new ComponentNodeServiceImpl(bundleContext, configResourceService, configRestAdaptorService); + configModelService = new ConfigModelServiceImpl(configRestAdaptorService); + configGeneratorService = new ConfigGeneratorServiceImpl(configResourceService); + + ConfigAssignmentNode configAssignmentNode = new ConfigAssignmentNode(configResourceService, + configRestAdaptorService, configModelService, componentNodeService, configGeneratorService); + + String inputContent = FileUtils.readFileToString( + new File("src/test/resources/service_templates/input/input.json"), Charset.defaultCharset()); + + Map inParams = new HashMap<>(); + inParams.put(ConfigModelConstant.PROPERTY_SELECTOR, "test"); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_REQUEST_ID, "1234"); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_ID, "resourceid-1234"); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_TYPE, "vnf-type"); + inParams.put(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_NAME, "vpe-201802-baseconfig"); + inParams.put(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_VERSION, "1.0.0"); + inParams.put(ConfigModelConstant.PROPERTY_ACTION_NAME, "resource-assignment-action"); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_INPUT_DATA, inputContent); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_TEMPLATE_NAMES, "[\"base-config-template\"]"); + + // Populate the SvcContext ( Simulation) + SvcLogicContext svcLogicContext = new SvcLogicContext(); + Map context = new HashMap<>(); + context.put(ConfigModelConstant.PROPERTY_ACTION_NAME, "resource-assignment-action"); + context = configModelService.prepareContext(context, inputContent, "vpe-201802-baseconfig", "1.0.0"); + context.forEach((key, value) -> svcLogicContext.setAttribute(key, value)); + + Map componentContext = new HashMap<>(); + configAssignmentNode.process(inParams, svcLogicContext, componentContext); + Assert.assertNotNull("Failed to get response status", svcLogicContext.getAttribute("test.status")); + + } + + @Test + public void testSimplePreview() throws Exception { + ConfigResourceAssignmentTestUtils.injectTransactionLogSaveMock(configResourceService); + + ConfigResourceAssignmentTestUtils.injectConfigModelMock(configRestAdaptorService, "resource_assignment"); + + ConfigResourceAssignmentTestUtils.injectResourceDictionaryMock(configRestAdaptorService, + "assignments/empty-dictionary.json"); + + ConfigResourceAssignmentTestUtils.injectConfigResourceSaveMock(configResourceService); + + componentNodeService = + new ComponentNodeServiceImpl(bundleContext, configResourceService, configRestAdaptorService); + configModelService = new ConfigModelServiceImpl(configRestAdaptorService); + configGeneratorService = new ConfigGeneratorServiceImpl(configResourceService); + + ConfigAssignmentNode configAssignmentNode = new ConfigAssignmentNode(configResourceService, + configRestAdaptorService, configModelService, componentNodeService, configGeneratorService); + + String inputContent = FileUtils.readFileToString( + new File("src/test/resources/service_templates/input/input.json"), Charset.defaultCharset()); + + Map inParams = new HashMap<>(); + inParams.put(ConfigModelConstant.PROPERTY_SELECTOR, "test"); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_REQUEST_ID, "1234"); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_ID, "resourceid-1234"); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_TYPE, "vnf-type"); + inParams.put(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_NAME, "vpe-201802-baseconfig"); + inParams.put(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_VERSION, "1.0.0"); + inParams.put(ConfigModelConstant.PROPERTY_ACTION_NAME, "resource-assignment-action"); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_INPUT_DATA, inputContent); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_TEMPLATE_NAMES, "[\"base-config-template\"]"); + SvcLogicContext ctx = new SvcLogicContext(); + configAssignmentNode.process(inParams, ctx); + Assert.assertNotNull("Failed to get response mashed Content", + ctx.getAttribute("test.mashed-data.base-config-template")); + } + + @Test + public void testComplexPreview() throws Exception { + ConfigResourceAssignmentTestUtils.injectTransactionLogSaveMock(configResourceService); + + ConfigResourceAssignmentTestUtils.injectConfigModelMock(configRestAdaptorService, "vpe-201802-baseconfig"); + + ConfigResourceAssignmentTestUtils.injectResourceDictionaryMock(configRestAdaptorService, + "service_templates/vpe-201802-baseconfig/dict.json"); + + ConfigResourceAssignmentTestUtils.injectConfigResourceSaveMock(configResourceService); + + componentNodeService = + new ComponentNodeServiceImpl(bundleContext, configResourceService, configRestAdaptorService); + configModelService = new ConfigModelServiceImpl(configRestAdaptorService); + configGeneratorService = new ConfigGeneratorServiceImpl(configResourceService); + + ConfigAssignmentNode configAssignmentNode = new ConfigAssignmentNode(configResourceService, + configRestAdaptorService, configModelService, componentNodeService, configGeneratorService); + + String inputContent = FileUtils.readFileToString( + new File("src/test/resources/service_templates/vpe-201802-baseconfig/input-complex.json"), + Charset.defaultCharset()); + + Map inParams = new HashMap<>(); + inParams.put(ConfigModelConstant.PROPERTY_SELECTOR, "complex-test"); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_REQUEST_ID, "request-1234"); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_ID, "resourceid-1234"); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_RESOURCE_TYPE, "vnf-type"); + inParams.put(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_NAME, "vpe-201802-baseconfig"); + inParams.put(ConfigModelConstant.SERVICE_TEMPLATE_KEY_ARTIFACT_VERSION, "1.0.0"); + inParams.put(ConfigModelConstant.PROPERTY_ACTION_NAME, "resource-assignment-action"); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_INPUT_DATA, inputContent); + inParams.put(ConfigAssignmentConstants.INPUT_PARAM_TEMPLATE_NAMES, "[\"base-config-template\"]"); + SvcLogicContext ctx = new SvcLogicContext(); + configAssignmentNode.process(inParams, ctx); + Assert.assertNotNull("Failed to get response mashed Content", + ctx.getAttribute("complex-test.mashed-data.base-config-template")); + + } + + @Test + public void inputValidator() { + SvcLogicContext ctx = new SvcLogicContext(); + try { + + logger.info(" ******************************* inputValidator ***************************"); + String serviceTemplateContent = FileUtils.readFileToString( + new File("src/test/resources/service_templates/resource_assignment.json"), + Charset.defaultCharset()); + + String inputcontent = FileUtils.readFileToString( + new File("src/test/resources/service_templates/input/inputValidateTest.json"), + Charset.defaultCharset()); + + Map context = new HashMap<>(); + configModelService.prepareContext(context, inputcontent, serviceTemplateContent); + + // TransformationUtils.printMap(context); + + context.forEach((name, value) -> { + if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(value)) { + ctx.setAttribute(name, value); + } + }); + + ComponentNodeDelegate componentNodeDelegate = new ComponentNodeDelegate(componentNodeService); + Map inParams = new HashMap<>(); + inParams.put(ConfigModelConstant.PROPERTY_SELECTOR, "resource-assignment"); + componentNodeDelegate.process(inParams, ctx); + Assert.fail(); + } catch (Exception e) { + logger.error("Failed in inputValidator" + e.getMessage()); + logger.info("** ctx.getAttribute Check for **" + ctx.getAttribute("resource-assignment.error-message")); + } + + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ConfigPreviewServiceTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ConfigPreviewServiceTest.java new file mode 100644 index 000000000..1e0b4a299 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ConfigPreviewServiceTest.java @@ -0,0 +1,113 @@ +/* + * 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.features.assignment.service; + +import java.io.File; +import java.nio.charset.Charset; +import org.apache.commons.io.FileUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.ccsdk.features.assignment.data.ResourceAssignmentData; +import org.onap.ccsdk.features.assignment.service.ConfigPreviewService; +import org.onap.ccsdk.features.data.adaptor.domain.ConfigResource; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.generator.service.ConfigGeneratorService; +import org.onap.ccsdk.features.generator.service.ConfigGeneratorServiceImpl; +import org.onap.ccsdk.features.model.service.ConfigModelService; +import org.onap.ccsdk.features.model.service.ConfigModelServiceImpl; +import org.onap.ccsdk.features.rest.adaptor.service.ConfigRestAdaptorService; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +@RunWith(MockitoJUnitRunner.class) +public class ConfigPreviewServiceTest { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigPreviewServiceTest.class); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Mock + private ConfigResourceService configResourceService; + + @Mock + private ConfigRestAdaptorService configRestAdaptorService; + + private ConfigModelService configModelService; + private ConfigGeneratorService configGeneratorService; + + @SuppressWarnings("unchecked") + @Before + public void before() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testGenerateTemplateResourceMash() throws Exception { + + ConfigResourceAssignmentTestUtils.injectTransactionLogSaveMock(configResourceService); + + ConfigResourceAssignmentTestUtils.injectConfigModelMock(configRestAdaptorService, "resource_assignment"); + + ConfigResourceAssignmentTestUtils.injectResourceDictionaryMock(configRestAdaptorService, + "assignments/empty-dictionary.json"); + + ConfigResource configResourceQuery = new ConfigResource(); + configResourceQuery.setServiceTemplateVersion("sample-serviceTemplateName"); + configResourceQuery.setServiceTemplateVersion("1.0.0"); + configResourceQuery.setRecipeName("sample-action"); + configResourceQuery.setResourceId("123-resourceId"); + configResourceQuery.setResourceType("sample-resourceType"); + configResourceQuery.setTemplateName("base-config-template"); + String inputContent = FileUtils.readFileToString( + new File("src/test/resources/service_templates/input/input.json"), Charset.defaultCharset()); + configResourceQuery.setResourceData(inputContent); + + ConfigResourceAssignmentTestUtils.injectGetConfigResourceMock(configResourceService, configResourceQuery); + + configModelService = new ConfigModelServiceImpl(configRestAdaptorService); + configGeneratorService = new ConfigGeneratorServiceImpl(configResourceService); + + ConfigPreviewService configPreviewService = + new ConfigPreviewService(configResourceService, configModelService, configGeneratorService); + + ResourceAssignmentData resourceAssignmentData = new ResourceAssignmentData(); + resourceAssignmentData.setResourceId("123-resourceId"); + resourceAssignmentData.setResourceType("sample-resourceType"); + resourceAssignmentData.setServiceTemplateName("sample-serviceTemplateName"); + resourceAssignmentData.setServiceTemplateVersion("1.0.0"); + resourceAssignmentData.setActionName("sample-action"); + + resourceAssignmentData = configPreviewService.generateTemplateResourceMash(resourceAssignmentData); + + Assert.assertNotNull("Failed to get GenerateTemplateResourceMash response.", resourceAssignmentData); + Assert.assertNotNull("Failed to get template mashed contents.", + resourceAssignmentData.getTemplatesMashedContents()); + + Assert.assertNotNull("Failed to get base-config template mashed contents.", + resourceAssignmentData.getTemplatesMashedContents().get("base-config-template")); + } +} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ConfigResourceAssignmentTestUtils.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ConfigResourceAssignmentTestUtils.java new file mode 100644 index 000000000..5ce2c9a1d --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ConfigResourceAssignmentTestUtils.java @@ -0,0 +1,183 @@ +/* + * 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.features.assignment.service; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import java.io.File; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.IOUtils; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.onap.ccsdk.features.data.adaptor.domain.ConfigResource; +import org.onap.ccsdk.features.data.adaptor.domain.TransactionLog; +import org.onap.ccsdk.features.data.adaptor.service.ConfigResourceService; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.data.dict.ResourceDefinition; +import org.onap.ccsdk.features.model.domain.ConfigModel; +import org.onap.ccsdk.features.model.domain.ConfigModelContent; +import org.onap.ccsdk.features.rest.adaptor.service.ConfigRestAdaptorService; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ConfigResourceAssignmentTestUtils { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(ConfigResourceAssignmentTestUtils.class); + + public static void injectTransactionLogSaveMock(ConfigResourceService configResourceService) throws Exception { + Mockito.doAnswer(new Answer() { + @Override + public Void answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + if (args != null) { + logger.trace("Transaction info " + Arrays.asList(args)); + } + return null; + } + }).when(configResourceService).save(any(TransactionLog.class)); + } + + public static void injectConfigModelMock(ConfigRestAdaptorService configRestAdaptorService, + String serviceTemplateName) throws Exception { + + Mockito.doAnswer(new Answer() { + @Override + public org.onap.ccsdk.features.model.domain.ConfigModel answer(InvocationOnMock invocationOnMock) + throws Throwable { + Object[] args = invocationOnMock.getArguments(); + org.onap.ccsdk.features.model.domain.ConfigModel serviceArtifact = null; + if (args != null && args.length == 3) { + + logger.info("Artifact info " + Arrays.asList(args)); + String modelContent = IOUtils.toString( + ConfigResourceAssignmentTestUtils.class.getClassLoader().getResourceAsStream( + "service_templates/" + serviceTemplateName + "/" + serviceTemplateName + ".json"), + Charset.defaultCharset()); + + ConfigModelContent configModelContent = new ConfigModelContent(); + configModelContent.setContent(modelContent); + configModelContent.setContentType(ConfigModelConstant.MODEL_CONTENT_TYPE_TOSCA_JSON); + + List configModelContents = new ArrayList<>(); + configModelContents.add(configModelContent); + + String velocityDir = ConfigResourceAssignmentTestUtils.class.getClassLoader() + .getResource("service_templates/" + serviceTemplateName + "/velocity").getPath(); + + Collection templateFiles = + FileUtils.listFiles(new File(velocityDir), new String[] {"vtl"}, true); + logger.info("Template Files info " + templateFiles); + for (File templateFile : templateFiles) { + String templateContent = FileUtils.readFileToString(templateFile, Charset.defaultCharset()); + ConfigModelContent configModelTemplateContent = new ConfigModelContent(); + configModelTemplateContent.setContent(templateContent); + configModelTemplateContent.setName(FilenameUtils.getBaseName(templateFile.getName())); + configModelTemplateContent.setContentType(ConfigModelConstant.MODEL_CONTENT_TYPE_TEMPLATE); + configModelContents.add(configModelTemplateContent); + } + + serviceArtifact = new org.onap.ccsdk.features.model.domain.ConfigModel(); + serviceArtifact.setArtifactName(String.valueOf(args[0])); + serviceArtifact.setArtifactVersion(String.valueOf(args[1])); + serviceArtifact.setPublished("Y"); + serviceArtifact.setConfigModelContents(configModelContents); + } + + return serviceArtifact; + } + }).when(configRestAdaptorService).getResource(anyString(), anyString(), Matchers.any(Class.class)); + } + + public static void injectResourceDictionaryMock(ConfigRestAdaptorService configRestAdaptorService, + String dictionaryFileName) throws Exception { + + Mockito.doAnswer(new Answer() { + @Override + public String answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + String dictionaties = "[]"; + if (args != null) { + logger.info("getResourceDictionaryByNames " + Arrays.asList(args)); + dictionaties = IOUtils.toString( + ConfigAssignmentNodeTest.class.getClassLoader().getResourceAsStream(dictionaryFileName), + Charset.defaultCharset()); + } + return dictionaties; + } + }).when(configRestAdaptorService).postResource(Matchers.any(), Matchers.any(), Matchers.any(), + Matchers.any(Class.class)); + } + + public static void injectConfigResourceSaveMock(ConfigResourceService configResourceService) throws Exception { + Mockito.doAnswer(new Answer() { + @Override + public ConfigResource answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + ConfigResource configResource = null; + if (args != null) { + configResource = (ConfigResource) args[0]; + logger.info("Config Resource Save info " + configResource); + return configResource; + } + return configResource; + } + }).when(configResourceService).saveConfigResource(any(ConfigResource.class)); + } + + public static void injectGetConfigResourceMock(ConfigResourceService configResourceService, + ConfigResource configResource) throws Exception { + Mockito.doAnswer(new Answer>() { + @Override + public List answer(InvocationOnMock invocationOnMock) throws Throwable { + Object[] args = invocationOnMock.getArguments(); + List configResources = new ArrayList<>(); + if (args != null) { + configResources.add(configResource); + } + return configResources; + } + }).when(configResourceService).getConfigResource(any(ConfigResource.class)); + } + + public static String getFileContent(String filePath) throws Exception { + return IOUtils.toString(ConfigResourceAssignmentTestUtils.class.getClassLoader().getResourceAsStream(filePath), + Charset.defaultCharset()); + } + + public static Map getMapfromJson(String content) { + try { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(content, new TypeReference>() {}); + } catch (Exception e) { + logger.info("getMapfromJson Exception ({})", e); + } + return null; + } +} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ResourceAssignmentGenerationTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ResourceAssignmentGenerationTest.java new file mode 100644 index 000000000..04147d90f --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ResourceAssignmentGenerationTest.java @@ -0,0 +1,111 @@ +/* + * 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.features.assignment.service; + +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.commons.io.IOUtils; +import org.junit.Assert; +import org.junit.Test; +import org.onap.ccsdk.features.model.ConfigModelConstant; +import org.onap.ccsdk.features.model.ValidTypes; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.utils.ResourceAssignmentUtils; +import org.onap.ccsdk.features.model.utils.TransformationUtils; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; + +public class ResourceAssignmentGenerationTest { + + private static EELFLogger logger = EELFManager.getInstance().getLogger(ResourceAssignmentGenerationTest.class); + + @Test + public void testResourceDataSetting() { + try { + logger.info(" **************** testResourceDataSetting *****************"); + String resourceAssignmentContents = IOUtils.toString(TopologicalSortingTest.class.getClassLoader() + .getResourceAsStream("assignments/alltype-empty-value-mapping.json"), Charset.defaultCharset()); + + List assignments = + TransformationUtils.getListfromJson(resourceAssignmentContents, ResourceAssignment.class); + if (assignments != null) { + Map componentContext = new HashMap<>(); + componentContext.put(ConfigModelConstant.PROPERTY_ACTION_NAME, "sample-recipe"); + for (ResourceAssignment resourceAssignment : assignments) { + if (resourceAssignment != null && resourceAssignment.getProperty() != null) { + String type = resourceAssignment.getProperty().getType(); + Object value = null; + if (ValidTypes.DATA_TYPE_STRING.equals(type)) { + value = new String("abcdef"); + } else if (ValidTypes.DATA_TYPE_INTEGER.equals(type)) { + value = new Integer(1234); + } else if (ValidTypes.DATA_TYPE_BOOLEAN.equals(type)) { + value = new Boolean(true); + } else if (ValidTypes.DATA_TYPE_LIST.equals(type)) { + String entityType = resourceAssignment.getProperty().getEntrySchema().getType(); + if (ValidTypes.DATA_TYPE_STRING.equals(entityType)) { + value = "[\"abcd-array\"]"; + } else { + String content = "[{\"name\" : \"abcd-array-complex\"}]"; + JsonNode node = TransformationUtils.getJsonNodeForString(content); + value = node; + } + } else { + String content = "{\"name\" : \"abcd-complex\"}"; + JsonNode node = TransformationUtils.getJsonNodeForString(content); + value = node; + } + ResourceAssignmentUtils.setResourceDataValue(componentContext, resourceAssignment, value); + } + } + String generatedData = ResourceAssignmentUtils.generateResourceDataForAssignments(assignments); + logger.trace("Generated Data " + generatedData); + + Assert.assertNotNull("Failed to generate resource data", generatedData); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testGenerateResourceData() { + try { + logger.info(" **************** testGenerateResourceData *****************"); + String resourceAssignmentContents = IOUtils.toString(TopologicalSortingTest.class.getClassLoader() + .getResourceAsStream("assignments/alltype-mapping.json"), Charset.defaultCharset()); + + List assignments = + TransformationUtils.getListfromJson(resourceAssignmentContents, ResourceAssignment.class); + if (assignments != null) { + + String generatedData = ResourceAssignmentUtils.generateResourceDataForAssignments(assignments); + logger.trace("Generated Data " + generatedData); + + Assert.assertNotNull("Failed to generate resource data", generatedData); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ResourceAssignmentValidation.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ResourceAssignmentValidation.java new file mode 100644 index 000000000..a3be02920 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/ResourceAssignmentValidation.java @@ -0,0 +1,95 @@ +/* + * 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.features.assignment.service; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.List; +import org.apache.commons.io.IOUtils; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.ccsdk.features.model.ConfigModelException; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.features.model.validator.ResourceAssignmentValidator; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ResourceAssignmentValidation { + private static EELFLogger logger = EELFManager.getInstance().getLogger(ResourceAssignmentValidation.class); + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Test + public void testValidateSuccess() { + try { + logger.info(" **************** testValidateSuccess *****************"); + String resourceMapping = IOUtils.toString( + TopologicalSortingTest.class.getClassLoader().getResourceAsStream("validation/success.json"), + Charset.defaultCharset()); + + List assignments = + TransformationUtils.getListfromJson(resourceMapping, ResourceAssignment.class); + if (assignments != null) { + ResourceAssignmentValidator resourceAssignmentValidator = new ResourceAssignmentValidator(assignments); + + boolean result = resourceAssignmentValidator.validateResourceAssignment(); + Assert.assertTrue("Failed to Validate", result); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test(expected = ConfigModelException.class) + public void testValidateDuplicate() throws IOException, ConfigModelException { + logger.info(" **************** testValidateDuplicate *****************"); + String resourceMapping = IOUtils.toString( + TopologicalSortingTest.class.getClassLoader().getResourceAsStream("validation/duplicate.json"), + Charset.defaultCharset()); + + List assignments = + TransformationUtils.getListfromJson(resourceMapping, ResourceAssignment.class); + if (assignments != null) { + ResourceAssignmentValidator resourceAssignmentValidator = new ResourceAssignmentValidator(assignments); + resourceAssignmentValidator.validateResourceAssignment(); + } + + } + + @Test(expected = ConfigModelException.class) + public void testValidateCyclic() throws IOException, ConfigModelException { + logger.info(" **************** testValidateCyclic *****************"); + String resourceMapping = IOUtils.toString( + TopologicalSortingTest.class.getClassLoader().getResourceAsStream("validation/cyclic.json"), + Charset.defaultCharset()); + + List assignments = + TransformationUtils.getListfromJson(resourceMapping, ResourceAssignment.class); + if (assignments != null) { + ResourceAssignmentValidator resourceAssignmentValidator = new ResourceAssignmentValidator(assignments); + + resourceAssignmentValidator.validateResourceAssignment(); + } + + } +} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/TopologicalSortingTest.java b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/TopologicalSortingTest.java new file mode 100644 index 000000000..f6e8871a6 --- /dev/null +++ b/blueprints-processor/plugin/assignment-provider/src/test/java/org/onap/ccsdk/features/assignment/service/TopologicalSortingTest.java @@ -0,0 +1,60 @@ +/* + * 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.features.assignment.service; + +import java.nio.charset.Charset; +import java.util.List; +import org.apache.commons.io.IOUtils; +import org.junit.Assert; +import org.junit.Test; +import org.onap.ccsdk.features.assignment.processor.ResourceAssignmentProcessor; +import org.onap.ccsdk.features.model.data.ResourceAssignment; +import org.onap.ccsdk.features.model.utils.TransformationUtils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class TopologicalSortingTest { + private static EELFLogger logger = EELFManager.getInstance().getLogger(TopologicalSortingTest.class); + + @Test + public void testBulkSequencingMapping() { + try { + logger.info(" **************** Bulk Sequencing Default *****************"); + String resourceMapping = IOUtils.toString( + TopologicalSortingTest.class.getClassLoader().getResourceAsStream("mapping/dependency.json"), + Charset.defaultCharset()); + + List assignments = + TransformationUtils.getListfromJson(resourceMapping, ResourceAssignment.class); + if (assignments != null) { + SvcLogicContext ctx = new SvcLogicContext(); + ResourceAssignmentProcessor resourceAssignmentProcessor = + new ResourceAssignmentProcessor(assignments, ctx); + List> sequenceBatchResourceAssignment = resourceAssignmentProcessor.process(); + + Assert.assertNotNull("Failed to populate Sequence Bulk Mappings", sequenceBatchResourceAssignment); + Assert.assertNotEquals("Failed to populate Sequence Bulk Mappings size ", + (sequenceBatchResourceAssignment.size() > 0)); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/blueprints-processor/plugin/assignment-provider/src/test/resources/service_templates/resource_assignment.json b/blueprints-processor/plugin/assignment-provider/src/test/resources/service_templates/resource_assignment.json index 0e29fe160..cbea6a82c 100644 --- a/blueprints-processor/plugin/assignment-provider/src/test/resources/service_templates/resource_assignment.json +++ b/blueprints-processor/plugin/assignment-provider/src/test/resources/service_templates/resource_assignment.json @@ -139,7 +139,7 @@ "resource-assignment": { "type": "component-resource-assignment", "interfaces": { - "org-onap-ccsdk-config-assignment-service-ConfigAssignmentNode": { + "org-onap-ccsdk-features-assignment-service-ConfigAssignmentNode": { "operations": { "process": { "inputs": { @@ -243,7 +243,7 @@ } }, "interfaces": { - "org-onap-ccsdk-config-assignment-service-ConfigAssignmentNode": { + "org-onap-ccsdk-features-assignment-service-ConfigAssignmentNode": { "operations": { "process": { "inputs": { diff --git a/blueprints-processor/plugin/assignment-provider/src/test/resources/service_templates/resource_assignment/resource_assignment.json b/blueprints-processor/plugin/assignment-provider/src/test/resources/service_templates/resource_assignment/resource_assignment.json index 6347f4223..4cbb8fa25 100644 --- a/blueprints-processor/plugin/assignment-provider/src/test/resources/service_templates/resource_assignment/resource_assignment.json +++ b/blueprints-processor/plugin/assignment-provider/src/test/resources/service_templates/resource_assignment/resource_assignment.json @@ -139,7 +139,7 @@ "resource-assignment": { "type": "component-resource-assignment", "interfaces": { - "org-onap-ccsdk-config-assignment-service-ConfigAssignmentNode": { + "org-onap-ccsdk-features-assignment-service-ConfigAssignmentNode": { "operations": { "process": { "inputs": { @@ -245,7 +245,7 @@ } }, "interfaces": { - "org-onap-ccsdk-config-assignment-service-ConfigAssignmentNode": { + "org-onap-ccsdk-features-assignment-service-ConfigAssignmentNode": { "operations": { "process": { "inputs": { diff --git a/blueprints-processor/plugin/assignment-provider/src/test/resources/service_templates/vpe-201802-baseconfig/vpe-201802-baseconfig.json b/blueprints-processor/plugin/assignment-provider/src/test/resources/service_templates/vpe-201802-baseconfig/vpe-201802-baseconfig.json index 20207a87b..7113b70c2 100644 --- a/blueprints-processor/plugin/assignment-provider/src/test/resources/service_templates/vpe-201802-baseconfig/vpe-201802-baseconfig.json +++ b/blueprints-processor/plugin/assignment-provider/src/test/resources/service_templates/vpe-201802-baseconfig/vpe-201802-baseconfig.json @@ -224,7 +224,7 @@ "resource-assignment": { "type": "component-resource-assignment", "interfaces": { - "org-onap-ccsdk-config-assignment-service-ConfigAssignmentNode": { + "org-onap-ccsdk-features-assignment-service-ConfigAssignmentNode": { "operations": { "process": { "inputs": { @@ -328,7 +328,7 @@ } }, "interfaces": { - "org-onap-ccsdk-config-assignment-service-ConfigAssignmentNode": { + "org-onap-ccsdk-features-assignment-service-ConfigAssignmentNode": { "operations": { "process": { "inputs": { -- cgit 1.2.3-korg