diff options
author | Sébastien Determe <sd378r@intl.att.com> | 2018-08-30 13:24:46 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2018-08-30 13:24:46 +0000 |
commit | 38cf246b1dae28d8a7d52d35f4d0f0cf90f31bec (patch) | |
tree | a7df23232166f09f6b448834992ccba31181810d | |
parent | 38e1bd367fd7764b3d2b01ffb1f49dddf9dbdc94 (diff) | |
parent | 0636411a4915a462d2cf6698ecb9c68c478f6ef5 (diff) |
Merge "Fix for sonar issue"
-rw-r--r-- | src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java | 26 | ||||
-rw-r--r-- | src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructor.java | 158 | ||||
-rw-r--r-- | src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyYamlFormatter.java (renamed from src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyReq.java) | 220 | ||||
-rw-r--r-- | src/main/java/org/onap/clamp/clds/util/ClampTimer.java | 3 | ||||
-rw-r--r-- | src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructorTest.java | 164 | ||||
-rw-r--r-- | src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyYamlFormatterTest.java (renamed from src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyReqTest.java) | 36 | ||||
-rw-r--r-- | src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java | 8 | ||||
-rw-r--r-- | src/test/java/org/onap/clamp/clds/it/PolicyClientItCase.java | 12 | ||||
-rw-r--r-- | src/test/resources/example/operational-policy/json-policy-chain.json | 63 |
9 files changed, 478 insertions, 212 deletions
diff --git a/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java index e324b2d99..ddadb55cc 100644 --- a/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java @@ -17,6 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ + * Modifications copyright (c) 2018 Nokia * =================================================================== * */ @@ -31,7 +32,7 @@ import java.util.Map; import org.apache.camel.Exchange; import org.apache.camel.Handler; -import org.onap.clamp.clds.client.req.policy.OperationalPolicyReq; +import org.onap.clamp.clds.client.req.policy.OperationalPolicyAttributesConstructor; import org.onap.clamp.clds.client.req.policy.PolicyClient; import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.model.properties.ModelProperties; @@ -52,16 +53,17 @@ public class OperationalPolicyDelegate { protected static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicyDelegate.class); protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - /** - * Automatically injected by Spring, define in CldsConfiguration as a bean. - */ - @Autowired - private PolicyClient policyClient; - /** - * Automatically injected by Spring, define in CldsConfiguration as a bean. - */ + private final PolicyClient policyClient; + private final ClampProperties refProp; + private final OperationalPolicyAttributesConstructor attributesConstructor; + @Autowired - private ClampProperties refProp; + public OperationalPolicyDelegate(PolicyClient policyClient, ClampProperties refProp, + OperationalPolicyAttributesConstructor attributesConstructor) { + this.policyClient = policyClient; + this.refProp = refProp; + this.attributesConstructor = attributesConstructor; + } /** * Perform activity. Send Operational Policy info to policy api. @@ -69,7 +71,7 @@ public class OperationalPolicyDelegate { * @param camelExchange * The Camel Exchange object containing the properties * @throws BuilderException - * In case of issues with OperationalPolicyReq + * In case of issues with OperationalPolicyRequestAttributesConstructor * @throws UnsupportedEncodingException * In case of issues with the Charset encoding */ @@ -80,7 +82,7 @@ public class OperationalPolicyDelegate { Policy policy = prop.getType(Policy.class); if (policy.isFound()) { for (PolicyChain policyChain : prop.getType(Policy.class).getPolicyChains()) { - Map<AttributeType, Map<String, String>> attributes = OperationalPolicyReq.formatAttributes(refProp, + Map<AttributeType, Map<String, String>> attributes = attributesConstructor.formatAttributes(refProp, prop, prop.getType(Policy.class).getId(), policyChain); responseMessage = policyClient.sendBrmsPolicy(attributes, prop, LoggingUtils.getRequestId()); } diff --git a/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructor.java b/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructor.java new file mode 100644 index 000000000..09f98f19a --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructor.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * Modifications copyright (c) 2018 Nokia + * =================================================================== + * + */ + +package org.onap.clamp.clds.client.req.policy; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.clds.model.properties.ModelProperties; +import org.onap.clamp.clds.model.properties.PolicyChain; +import org.onap.clamp.clds.model.properties.PolicyItem; +import org.onap.policy.api.AttributeType; +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; + +@Component +public class OperationalPolicyAttributesConstructor { + + private static final EELFLogger logger = EELFManager.getInstance() + .getLogger(OperationalPolicyAttributesConstructor.class); + static final String TEMPLATE_NAME = "templateName"; + static final String CLOSED_LOOP_CONTROL_NAME = "closedLoopControlName"; + static final String NOTIFICATION_TOPIC = "notificationTopic"; + static final String OPERATION_TOPIC = "operationTopic"; + static final String CONTROL_LOOP_YAML = "controlLoopYaml"; + static final String CONTROLLER = "controller"; + static final String RECIPE = "Recipe"; + static final String MAX_RETRIES = "MaxRetries"; + static final String RETRY_TIME_LIMIT = "RetryTimeLimit"; + static final String RESOURCE_ID = "ResourceId"; + static final String RECIPE_TOPIC = "RecipeTopic"; + private OperationalPolicyYamlFormatter policyYamlFormatter; + + @Autowired + protected OperationalPolicyAttributesConstructor(OperationalPolicyYamlFormatter policyYamlFormatter) { + this.policyYamlFormatter = policyYamlFormatter; + } + + public Map<AttributeType, Map<String, String>> formatAttributes(ClampProperties refProp, + ModelProperties modelProperties, + String modelElementId, PolicyChain policyChain) + throws BuilderException, UnsupportedEncodingException { + modelProperties.setCurrentModelElementId(modelElementId); + modelProperties.setPolicyUniqueId(policyChain.getPolicyId()); + + String globalService = modelProperties.getGlobal().getService(); + + Map<String, String> ruleAttributes = prepareRuleAttributes(refProp, modelProperties, modelElementId, + policyChain, globalService); + Map<String, String> matchingAttributes = prepareMatchingAttributes(refProp, globalService); + + return createAttributesMap(matchingAttributes, ruleAttributes); + } + + private Map<String, String> prepareRuleAttributes(ClampProperties clampProperties, ModelProperties modelProperties, + String modelElementId, PolicyChain policyChain, String globalService) + throws BuilderException, UnsupportedEncodingException { + logger.info("Preparing rule attributes..."); + String templateName = clampProperties.getStringValue("op.templateName", globalService); + String operationTopic = clampProperties.getStringValue("op.operationTopic", globalService); + String notificationTopic = clampProperties.getStringValue("op.notificationTopic", globalService); + + Map<String, String> ruleAttributes = new HashMap<>(); + ruleAttributes.put(TEMPLATE_NAME, templateName); + ruleAttributes.put(CLOSED_LOOP_CONTROL_NAME, modelProperties.getControlNameAndPolicyUniqueId()); + ruleAttributes.put(NOTIFICATION_TOPIC, notificationTopic); + + ImmutableMap<String, String> attributes = createRuleAttributesFromPolicy(clampProperties, modelProperties, + modelElementId, policyChain, globalService, operationTopic); + ruleAttributes.putAll(attributes); + logger.info("Prepared: " + ruleAttributes); + return ruleAttributes; + } + + private Map<String, String> prepareMatchingAttributes(ClampProperties refProp, String globalService) { + logger.info("Preparing matching attributes..."); + String controller = refProp.getStringValue("op.controller", globalService); + Map<String, String> matchingAttributes = new HashMap<>(); + matchingAttributes.put(CONTROLLER, controller); + logger.info("Prepared: " + matchingAttributes); + return matchingAttributes; + } + + private Map<AttributeType, Map<String, String>> createAttributesMap(Map<String, String> matchingAttributes, + Map<String, String> ruleAttributes) { + Map<AttributeType, Map<String, String>> attributes = new HashMap<>(); + attributes.put(AttributeType.RULE, ruleAttributes); + attributes.put(AttributeType.MATCHING, matchingAttributes); + return attributes; + } + + private ImmutableMap<String, String> createRuleAttributesFromPolicy(ClampProperties refProp, ModelProperties modelProperties, + String modelElementId, PolicyChain policyChain, + String globalService, String operationTopic) + throws BuilderException, UnsupportedEncodingException { + if (Strings.isNullOrEmpty(operationTopic)) { + // if no operationTopic, then don't format yaml - use first policy + String recipeTopic = refProp.getStringValue("op.recipeTopic", globalService); + return createRuleAttributesFromPolicyItem( + policyChain.getPolicyItems().get(0), recipeTopic); + } else { + return createRuleAttributesFromPolicyChain(policyChain, modelProperties, + modelElementId, operationTopic); + } + } + + private ImmutableMap<String, String> createRuleAttributesFromPolicyItem(PolicyItem policyItem, String recipeTopic) { + logger.info("recipeTopic=" + recipeTopic); + return ImmutableMap.<String, String>builder() + .put(RECIPE_TOPIC, recipeTopic) + .put(RECIPE, policyItem.getRecipe()) + .put(MAX_RETRIES, String.valueOf(policyItem.getMaxRetries())) + .put(RETRY_TIME_LIMIT, String.valueOf(policyItem.getRetryTimeLimit())) + .put(RESOURCE_ID, String.valueOf(policyItem.getTargetResourceId())) + .build(); + } + + private ImmutableMap<String, String> createRuleAttributesFromPolicyChain(PolicyChain policyChain, + ModelProperties modelProperties, + String modelElementId, + String operationTopic) + throws BuilderException, UnsupportedEncodingException { + logger.info("operationTopic=" + operationTopic); + String yaml = policyYamlFormatter.formatYaml(modelProperties, modelElementId, policyChain); + return ImmutableMap.<String, String>builder() + .put(OPERATION_TOPIC, operationTopic) + .put(CONTROL_LOOP_YAML, yaml) + .build(); + } +}
\ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyReq.java b/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyYamlFormatter.java index f062dfca6..550c4dccd 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyReq.java +++ b/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyYamlFormatter.java @@ -21,28 +21,14 @@ * =================================================================== * */ - package org.onap.clamp.clds.client.req.policy; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.BadRequestException; - -import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.model.properties.Global; import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.model.properties.PolicyChain; import org.onap.clamp.clds.model.properties.PolicyItem; -import org.onap.policy.api.AttributeType; import org.onap.policy.controlloop.policy.Policy; import org.onap.policy.controlloop.policy.PolicyResult; import org.onap.policy.controlloop.policy.Target; @@ -54,137 +40,38 @@ import org.onap.policy.controlloop.policy.builder.Results; import org.onap.policy.sdc.Resource; import org.onap.policy.sdc.ResourceType; import org.onap.policy.sdc.Service; +import org.springframework.stereotype.Component; -/** - * Construct an Operational Policy request given CLDS objects. - */ -public class OperationalPolicyReq { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicyReq.class); +import javax.ws.rs.BadRequestException; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; - protected OperationalPolicyReq() { - } +@Component +class OperationalPolicyYamlFormatter { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicyYamlFormatter.class); - /** - * Format Operational Policy attributes. - * - * @param refProp - * @param prop - * @param modelElementId - * @param policyChain - * @return - * @throws BuilderException - * @throws UnsupportedEncodingException - */ - public static Map<AttributeType, Map<String, String>> formatAttributes(ClampProperties refProp, - ModelProperties prop, String modelElementId, PolicyChain policyChain) - throws BuilderException, UnsupportedEncodingException { - Global global = prop.getGlobal(); - prop.setCurrentModelElementId(modelElementId); - prop.setPolicyUniqueId(policyChain.getPolicyId()); - String templateName = refProp.getStringValue("op.templateName", global.getService()); - String operationTopic = refProp.getStringValue("op.operationTopic", global.getService()); - String notificationTopic = refProp.getStringValue("op.notificationTopic", global.getService()); - String controller = refProp.getStringValue("op.controller", global.getService()); - String recipeTopic = refProp.getStringValue("op.recipeTopic", global.getService()); - // ruleAttributes - logger.info("templateName=" + templateName); - logger.info("notificationTopic=" + notificationTopic); - Map<String, String> ruleAttributes = new HashMap<>(); - ruleAttributes.put("templateName", templateName); - ruleAttributes.put("closedLoopControlName", prop.getControlNameAndPolicyUniqueId()); - ruleAttributes.put("notificationTopic", notificationTopic); - if (operationTopic == null || operationTopic.isEmpty()) { - logger.info("recipeTopic=" + recipeTopic); - // if no operationTopic, then don't format yaml - use first policy - // from list - PolicyItem policyItem = policyChain.getPolicyItems().get(0); - ruleAttributes.put("RecipeTopic", recipeTopic); - String recipe = policyItem.getRecipe(); - String maxRetries = String.valueOf(policyItem.getMaxRetries()); - String retryTimeLimit = String.valueOf(policyItem.getRetryTimeLimit()); - String targetResourceId = String.valueOf(policyItem.getTargetResourceId()); - logger.info("recipe=" + recipe); - logger.info("maxRetries=" + maxRetries); - logger.info("retryTimeLimit=" + retryTimeLimit); - logger.info("targetResourceId=" + targetResourceId); - ruleAttributes.put("Recipe", recipe); - ruleAttributes.put("MaxRetries", maxRetries); - ruleAttributes.put("RetryTimeLimit", retryTimeLimit); - ruleAttributes.put("ResourceId", targetResourceId); - } else { - logger.info("operationTopic=" + operationTopic); - // format yaml - String yaml = formatYaml(refProp, prop, modelElementId, policyChain); - ruleAttributes.put("operationTopic", operationTopic); - ruleAttributes.put("controlLoopYaml", yaml); - } - // matchingAttributes - Map<String, String> matchingAttributes = new HashMap<>(); - matchingAttributes.put("controller", controller); - Map<AttributeType, Map<String, String>> attributes = new HashMap<>(); - attributes.put(AttributeType.RULE, ruleAttributes); - attributes.put(AttributeType.MATCHING, matchingAttributes); - return attributes; - } - /** - * Format Operational OpenLoop Policy yaml. - * - * @param refProp - * @param prop - * @param modelElementId - * @param policyChain - * @return - * @throws BuilderException - * @throws UnsupportedEncodingException - */ - protected static String formatOpenLoopYaml(ClampProperties refProp, ModelProperties prop, String modelElementId, - PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException { + String formatYaml(ModelProperties prop, String modelElementId, + PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException { // get property objects Global global = prop.getGlobal(); prop.setCurrentModelElementId(modelElementId); prop.setPolicyUniqueId(policyChain.getPolicyId()); // convert values to SDC objects Service service = new Service(global.getService()); - Resource[] vfResources = convertToResource(global.getResourceVf(), ResourceType.VF); + Resource[] vfResources = convertToResources(global.getResourceVf(), ResourceType.VF); + Resource[] vfcResources = convertToResources(global.getResourceVfc(), ResourceType.VFC); // create builder ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(), - policyChain.getTimeout(), service, vfResources); - // builder.setTriggerPolicy(refProp.getStringValue("op.openloop.policy")); - // Build the specification - Results results = builder.buildSpecification(); - validate(results); - return URLEncoder.encode(results.getSpecification(), "UTF-8"); - } - - /** - * Format Operational Policy yaml. - * - * @param refProp - * @param prop - * @param modelElementId - * @param policyChain - * @return - * @throws BuilderException - * @throws UnsupportedEncodingException - */ - protected static String formatYaml(ClampProperties refProp, ModelProperties prop, String modelElementId, - PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException { - // get property objects - Global global = prop.getGlobal(); - prop.setCurrentModelElementId(modelElementId); - prop.setPolicyUniqueId(policyChain.getPolicyId()); - // convert values to SDC objects - Service service = new Service(global.getService()); - Resource[] vfResources = convertToResource(global.getResourceVf(), ResourceType.VF); - Resource[] vfcResources = convertToResource(global.getResourceVfc(), ResourceType.VFC); - // create builder - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(), - policyChain.getTimeout(), service, vfResources); + policyChain.getTimeout(), service, vfResources); builder.addResource(vfcResources); // process each policy - Map<String, Policy> policyObjMap = new HashMap<>(); + Map<String, Policy> policyObjMap = new HashMap<String, Policy>(); List<PolicyItem> policyItemList = orderParentFirst(policyChain.getPolicyItems()); for (PolicyItem policyItem : policyItemList) { String policyName = policyItem.getRecipe() + " Policy"; @@ -200,16 +87,16 @@ public class OperationalPolicyReq { Policy policyObj; if (policyItemList.indexOf(policyItem) == 0) { String policyDescription = policyItem.getRecipe() - + " Policy - the trigger (no parent) policy - created by CLDS"; + + " Policy - the trigger (no parent) policy - created by CLDS"; policyObj = builder.setTriggerPolicy(policyName, policyDescription, actor, target, - policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit()); + policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit()); } else { Policy parentPolicyObj = policyObjMap.get(policyItem.getParentPolicy()); String policyDescription = policyItem.getRecipe() + " Policy - triggered conditionally by " - + parentPolicyObj.getName() + " - created by CLDS"; + + parentPolicyObj.getName() + " - created by CLDS"; policyObj = builder.setPolicyForPolicyResult(policyName, policyDescription, actor, target, - policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit(), - parentPolicyObj.getId(), convertToPolicyResult(policyItem.getParentPolicyConditions())); + policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit(), + parentPolicyObj.getId(), convertToPolicyResults(policyItem.getParentPolicyConditions())); logger.info("policyObj.id=" + policyObj.getId() + "; parentPolicyObj.id=" + parentPolicyObj.getId()); } policyObjMap.put(policyItem.getId(), policyObj); @@ -220,29 +107,7 @@ public class OperationalPolicyReq { return URLEncoder.encode(results.getSpecification(), "UTF-8"); } - protected static void validate(Results results) { - if (results.isValid()) { - logger.info("results.getSpecification()=" + results.getSpecification()); - } else { - // throw exception with error info - StringBuilder sb = new StringBuilder(); - sb.append("Operation Policy validation problem: ControlLoopPolicyBuilder failed with following messages: "); - for (Message message : results.getMessages()) { - sb.append(message.getMessage()); - sb.append("; "); - } - throw new BadRequestException(sb.toString()); - } - } - - /** - * Order list of PolicyItems so that parents come before any of their - * children - * - * @param inOrigList - * @return - */ - private static List<PolicyItem> orderParentFirst(List<PolicyItem> inOrigList) { + private List<PolicyItem> orderParentFirst(List<PolicyItem> inOrigList) { List<PolicyItem> inList = new ArrayList<>(); inList.addAll(inOrigList); List<PolicyItem> outList = new ArrayList<>(); @@ -264,7 +129,7 @@ public class OperationalPolicyReq { if (parent == null || parent.length() == 0) { if (!outList.isEmpty()) { throw new BadRequestException( - "Operation Policy validation problem: more than one trigger policy"); + "Operation Policy validation problem: more than one trigger policy"); } else { outList.add(inItem); inListItr.remove(); @@ -286,31 +151,34 @@ public class OperationalPolicyReq { return outList; } - /** - * Convert a List of resource strings to an array of Resource objects. - * - * @param stringList - * @param resourceType - * @return - */ - protected static Resource[] convertToResource(List<String> stringList, ResourceType resourceType) { + private void validate(Results results) { + if (results.isValid()) { + logger.info("results.getSpecification()=" + results.getSpecification()); + } else { + // throw exception with error info + StringBuilder sb = new StringBuilder(); + sb.append("Operation Policy validation problem: ControlLoopPolicyBuilder failed with following messages: "); + for (Message message : results.getMessages()) { + sb.append(message.getMessage()); + sb.append("; "); + } + throw new BadRequestException(sb.toString()); + } + } + + + Resource[] convertToResources(List<String> stringList, ResourceType resourceType) { if (stringList == null || stringList.isEmpty()) { return new Resource[0]; } return stringList.stream().map(stringElem -> new Resource(stringElem, resourceType)).toArray(Resource[]::new); } - /** - * Convert a List of policy result strings to an array of PolicyResult - * objects. - * - * @param prList - * @return - */ - protected static PolicyResult[] convertToPolicyResult(List<String> prList) { + PolicyResult[] convertToPolicyResults(List<String> prList) { if (prList == null || prList.isEmpty()) { return new PolicyResult[0]; } return prList.stream().map(PolicyResult::toResult).toArray(PolicyResult[]::new); } + }
\ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/util/ClampTimer.java b/src/main/java/org/onap/clamp/clds/util/ClampTimer.java index 794e2b486..d08e73a4a 100644 --- a/src/main/java/org/onap/clamp/clds/util/ClampTimer.java +++ b/src/main/java/org/onap/clamp/clds/util/ClampTimer.java @@ -17,6 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ + * Modifications copyright (c) 2018 Nokia * =================================================================== * */ @@ -39,7 +40,7 @@ public class ClampTimer { public ClampTimer(int seconds) { timer = new Timer(); - timer.schedule(new CleanupTask(), seconds*1000); + timer.schedule(new CleanupTask(), seconds*1000L); } class CleanupTask extends TimerTask { diff --git a/src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructorTest.java b/src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructorTest.java new file mode 100644 index 000000000..c257ec3fd --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructorTest.java @@ -0,0 +1,164 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2018 Nokia Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ + +package org.onap.clamp.clds.client.req.policy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import org.assertj.core.api.Assertions; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.clds.model.properties.ModelProperties; +import org.onap.clamp.clds.model.properties.PolicyChain; +import org.onap.clamp.clds.util.ResourceFileUtil; +import org.onap.policy.api.AttributeType; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.policy.Target; +import org.onap.policy.controlloop.policy.TargetType; +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.yaml.snakeyaml.Yaml; + +import java.io.IOException; +import java.net.URLDecoder; +import java.util.Map; + +public class OperationalPolicyAttributesConstructorTest { + + private static final String CONTROL_NAME = "ClosedLoop-d4629aee-970f-11e8-86c9-02552dda865e"; + private ModelProperties modelProperties; + private PolicyChain policyChain; + + private OperationalPolicyYamlFormatter operationalPolicyYamlFormatter = new OperationalPolicyYamlFormatter(); + private OperationalPolicyAttributesConstructor operationalPolicyAttributesConstructor = + new OperationalPolicyAttributesConstructor(operationalPolicyYamlFormatter); + + @Before + public void setUp() throws Exception { + String modelProp = ResourceFileUtil + .getResourceAsString("example/model-properties/policy/modelBpmnProperties.json"); + modelProperties = new ModelProperties("CLAMPDemoVFW_v1_0_3af8daec-6f10-4027-a3540", + CONTROL_NAME, "PUT", false, "{}", modelProp); + policyChain = readPolicyChainFromResources(); + } + + + @Test + public void shouldFormatRequestAttributes() throws IOException, BuilderException { + // given + ClampProperties mockClampProperties = createMockClampProperties(ImmutableMap.<String, String>builder() + .put("op.templateName", "ClosedLoopControlName") + .put("op.notificationTopic", "POLICY-CL-MGT") + .put("op.controller", "amsterdam") + .put("op.recipeTopic", "APPC") + .build()); + + //when + Map<AttributeType, Map<String, String>> requestAttributes + = operationalPolicyAttributesConstructor.formatAttributes(mockClampProperties, modelProperties, + "789875c1-e788-432f-9a76-eac8ed889734", policyChain); + //then + Assertions.assertThat(requestAttributes).containsKeys(AttributeType.MATCHING, AttributeType.RULE); + Assertions.assertThat(requestAttributes.get(AttributeType.MATCHING)) + .contains(Assertions.entry(OperationalPolicyAttributesConstructor.CONTROLLER, "amsterdam")); + + Map<String, String> ruleParameters = requestAttributes.get(AttributeType.RULE); + Assertions.assertThat(ruleParameters).containsExactly( + Assertions.entry(OperationalPolicyAttributesConstructor.MAX_RETRIES, "3"), + Assertions.entry(OperationalPolicyAttributesConstructor.TEMPLATE_NAME, "ClosedLoopControlName"), + Assertions.entry(OperationalPolicyAttributesConstructor.NOTIFICATION_TOPIC, "POLICY-CL-MGT"), + Assertions.entry(OperationalPolicyAttributesConstructor.RECIPE_TOPIC, "APPC"), + Assertions.entry(OperationalPolicyAttributesConstructor.RECIPE, "healthCheck"), + Assertions.entry(OperationalPolicyAttributesConstructor.RESOURCE_ID, + "cdb69724-57d5-4a22-b96c-4c345150fd0e"), + Assertions.entry(OperationalPolicyAttributesConstructor.RETRY_TIME_LIMIT, "180"), + Assertions.entry(OperationalPolicyAttributesConstructor.CLOSED_LOOP_CONTROL_NAME, CONTROL_NAME + "_1") + ); + } + + @Test + public void shouldFormatRequestAttributesWithProperControlLoopYaml() throws IOException, BuilderException { + //given + ClampProperties mockClampProperties = createMockClampProperties(ImmutableMap.<String, String>builder() + .put("op.templateName", "ClosedLoopControlName") + .put("op.operationTopic", "APPP-CL") + .put("op.notificationTopic", "POLICY-CL-MGT") + .put("op.controller", "amsterdam") + .put("op.recipeTopic", "APPC") + .build()); + + Policy expectedPolicy = new Policy("6f76ad0b-ea9d-4a92-8d7d-6a6367ce2c77", "healthCheck Policy", + "healthCheck Policy - the trigger (no parent) policy - created by CLDS", "APPC", + null, new Target(TargetType.VM, "cdb69724-57d5-4a22-b96c-4c345150fd0e"), + "healthCheck", 3, 180); + + //when + Map<AttributeType, Map<String, String>> requestAttributes = operationalPolicyAttributesConstructor + .formatAttributes(mockClampProperties, modelProperties, + "789875c1-e788-432f-9a76-eac8ed889734", policyChain); + + //then + Assertions.assertThat(requestAttributes) + .containsKeys(AttributeType.MATCHING, AttributeType.RULE); + Assertions.assertThat(requestAttributes + .get(AttributeType.MATCHING)) + .contains(Assertions.entry("controller", "amsterdam")); + + Map<String, String> ruleParameters = requestAttributes.get(AttributeType.RULE); + Assertions.assertThat(ruleParameters).contains( + Assertions.entry(OperationalPolicyAttributesConstructor.OPERATION_TOPIC, "APPP-CL"), + Assertions.entry(OperationalPolicyAttributesConstructor.TEMPLATE_NAME, "ClosedLoopControlName"), + Assertions.entry(OperationalPolicyAttributesConstructor.NOTIFICATION_TOPIC, "POLICY-CL-MGT"), + Assertions.entry(OperationalPolicyAttributesConstructor.CLOSED_LOOP_CONTROL_NAME, CONTROL_NAME + "_1") + ); + + String controlLoopYaml = URLDecoder.decode( + ruleParameters.get(OperationalPolicyAttributesConstructor.CONTROL_LOOP_YAML), "UTF-8"); + ControlLoopPolicy controlLoopPolicy = new Yaml().load(controlLoopYaml); + + Assertions.assertThat(controlLoopPolicy.getControlLoop().getControlLoopName()).isEqualTo(CONTROL_NAME); + Assertions.assertThat(controlLoopPolicy.getPolicies()) + .usingElementComparatorIgnoringFields("id") + .containsExactly(expectedPolicy); + } + + + private ClampProperties createMockClampProperties(ImmutableMap<String, String> propertiesMap) { + ClampProperties props = Mockito.mock(ClampProperties.class); + propertiesMap.forEach((property, value) -> + Mockito.when(props.getStringValue(Matchers.matches(property), Matchers.any())).thenReturn(value) + ); + return props; + } + + private PolicyChain readPolicyChainFromResources() throws IOException { + String policyChainText = ResourceFileUtil + .getResourceAsString("example/operational-policy/json-policy-chain.json"); + JsonNode policyChainNode = new ObjectMapper().readTree(policyChainText); + return new PolicyChain(policyChainNode); + } +} diff --git a/src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyReqTest.java b/src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyYamlFormatterTest.java index d5e3069b2..046d7394d 100644 --- a/src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyReqTest.java +++ b/src/test/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyYamlFormatterTest.java @@ -17,53 +17,55 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ + * Modifications copyright (c) 2018 Nokia * =================================================================== - * + * */ package org.onap.clamp.clds.client.req.policy; -import static org.assertj.core.api.Assertions.assertThat; - -import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.List; + +import org.assertj.core.api.Assertions; import org.junit.Test; import org.onap.policy.controlloop.policy.PolicyResult; import org.onap.policy.sdc.Resource; import org.onap.policy.sdc.ResourceType; -public class OperationalPolicyReqTest { +public class OperationalPolicyYamlFormatterTest { + + private OperationalPolicyYamlFormatter policyYamlFormatter = new OperationalPolicyYamlFormatter(); @Test public void shouldConvertGivenStringsToResourceObjects() - throws NoSuchMethodException, SecurityException, IllegalAccessException, - IllegalArgumentException, InvocationTargetException { + throws SecurityException, + IllegalArgumentException { //given List<String> stringList = Arrays.asList("test1", "test2", "test3", "test4"); //when - Resource[] resources = OperationalPolicyReq.convertToResource(stringList, ResourceType.VF); + Resource[] resources = policyYamlFormatter.convertToResources(stringList, ResourceType.VF); //then - assertThat(resources).extracting(Resource::getResourceName) - .containsExactly("test1", "test2", "test3", "test4"); + Assertions.assertThat(resources).extracting(Resource::getResourceName) + .containsExactly("test1", "test2", "test3", "test4"); } @Test public void shouldConvertGivenStringsToPolicyResults() - throws NoSuchMethodException, SecurityException, IllegalAccessException, - IllegalArgumentException, InvocationTargetException { + throws SecurityException, + IllegalArgumentException { //given List<String> stringList = Arrays.asList("FAILURE", "SUCCESS", "FAILURE_GUARD", "FAILURE_TIMEOUT"); //when - PolicyResult[] policyResults = OperationalPolicyReq.convertToPolicyResult(stringList); + PolicyResult[] policyResults = policyYamlFormatter.convertToPolicyResults(stringList); //then - assertThat(policyResults) - .containsExactly(PolicyResult.FAILURE, PolicyResult.SUCCESS, - PolicyResult.FAILURE_GUARD, PolicyResult.FAILURE_TIMEOUT); + Assertions.assertThat(policyResults) + .containsExactly(PolicyResult.FAILURE, PolicyResult.SUCCESS, + PolicyResult.FAILURE_GUARD, PolicyResult.FAILURE_TIMEOUT); } -} +}
\ No newline at end of file diff --git a/src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java b/src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java index 69dad53ec..ad58ea1e4 100644 --- a/src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/OperationPolicyReqItCase.java @@ -17,6 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ + * Modifications copyright (c) 2018 Nokia * =================================================================== * */ @@ -35,7 +36,7 @@ import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; -import org.onap.clamp.clds.client.req.policy.OperationalPolicyReq; +import org.onap.clamp.clds.client.req.policy.OperationalPolicyAttributesConstructor; import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.model.CldsEvent; import org.onap.clamp.clds.model.properties.ModelProperties; @@ -55,6 +56,9 @@ public class OperationPolicyReqItCase { @Autowired private ClampProperties refProp; + @Autowired + private OperationalPolicyAttributesConstructor operationalPolicyAttributesConstructor; + @Test public void formatAttributesTest() throws IOException, BuilderException { String modelBpmnProp = ResourceFileUtil @@ -65,7 +69,7 @@ public class OperationPolicyReqItCase { List<Map<AttributeType, Map<String, String>>> attributes = new ArrayList<>(); if (modelProperties.getType(Policy.class).isFound()) { for (PolicyChain policyChain : modelProperties.getType(Policy.class).getPolicyChains()) { - attributes.add(OperationalPolicyReq.formatAttributes(refProp, modelProperties, + attributes.add(operationalPolicyAttributesConstructor.formatAttributes(refProp, modelProperties, modelProperties.getType(Policy.class).getId(), policyChain)); } } diff --git a/src/test/java/org/onap/clamp/clds/it/PolicyClientItCase.java b/src/test/java/org/onap/clamp/clds/it/PolicyClientItCase.java index c6fc09dbb..2400d4ab6 100644 --- a/src/test/java/org/onap/clamp/clds/it/PolicyClientItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/PolicyClientItCase.java @@ -17,6 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ + * Modifications copyright (c) 2018 Nokia * =================================================================== * */ @@ -35,7 +36,7 @@ import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.onap.clamp.clds.client.req.policy.OperationalPolicyReq; +import org.onap.clamp.clds.client.req.policy.OperationalPolicyAttributesConstructor; import org.onap.clamp.clds.client.req.policy.PolicyClient; import org.onap.clamp.clds.client.req.tca.TcaRequestFormatter; import org.onap.clamp.clds.config.ClampProperties; @@ -64,7 +65,10 @@ public class PolicyClientItCase { @Autowired private ClampProperties refProp; @Autowired - protected PolicyClient policyClient; + private PolicyClient policyClient; + @Autowired + private OperationalPolicyAttributesConstructor operationalPolicyAttributesConstructor; + String modelProp; String modelBpmnProp; String modelName; @@ -87,8 +91,8 @@ public class PolicyClientItCase { if (policy.isFound()) { for (PolicyChain policyChain : policy.getPolicyChains()) { String operationalPolicyRequestUuid = UUID.randomUUID().toString(); - Map<AttributeType, Map<String, String>> attributes = OperationalPolicyReq.formatAttributes(refProp, - prop, policy.getId(), policyChain); + Map<AttributeType, Map<String, String>> attributes = operationalPolicyAttributesConstructor + .formatAttributes(refProp, prop, policy.getId(), policyChain); policyClient.sendBrmsPolicy(attributes, prop, operationalPolicyRequestUuid); } } diff --git a/src/test/resources/example/operational-policy/json-policy-chain.json b/src/test/resources/example/operational-policy/json-policy-chain.json new file mode 100644 index 000000000..037b4d656 --- /dev/null +++ b/src/test/resources/example/operational-policy/json-policy-chain.json @@ -0,0 +1,63 @@ +[ + { + "name": "pname", + "value": "healthCheck Policy" + }, + { + "name": "pid", + "value": "1" + }, + { + "name": "timeout", + "value": "180" + }, + { + "policyConfigurations": [ + [ + { + "name": "recipe", + "value": [ + "healthCheck" + ] + }, + { + "name": "maxRetries", + "value": [ + "3" + ] + }, + { + "name": "retryTimeLimit", + "value": [ + "180" + ] + }, + { + "name": "_id", + "value": [ + "789875c1-e788-432f-9a76-eac8ed889734" + ] + }, + { + "name": "parentPolicy", + "value": [ + "" + ] + }, + { + "name": "actor", + "value": [ + "APPC" + ] + }, + { + "name": "targetResourceId", + "value": [ + "cdb69724-57d5-4a22-b96c-4c345150fd0e" + ] + } + + ] + ] + } +]
\ No newline at end of file |