From: Sébastien Determe Date: Tue, 11 Sep 2018 09:10:44 +0000 (+0000) Subject: Merge "logstash input" X-Git-Tag: 3.0.0~16 X-Git-Url: https://gerrit.onap.org/r/gitweb?a=commitdiff_plain;h=23c4c2752564b7ec967b3176600578be5a1cb08b;hp=67ca7eb7e7f193c178c6a3d1337e539faf7e9c81;p=clamp.git Merge "logstash input" --- diff --git a/extra/sql/bulkload/clds-create-db-objects.sql b/extra/sql/bulkload/clds-create-db-objects.sql index 78a1f7a6..38cc466f 100644 --- a/extra/sql/bulkload/clds-create-db-objects.sql +++ b/extra/sql/bulkload/clds-create-db-objects.sql @@ -114,6 +114,53 @@ CREATE TABLE clds_service_cache ( PRIMARY KEY (invariant_service_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_bin; +CREATE TABLE IF NOT EXISTS tosca_model ( + tosca_model_id VARCHAR(36) NOT NULL, + tosca_model_name VARCHAR(80) NOT NULL, + policy_type VARCHAR(80) NULL, + user_id VARCHAR(80), + timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (tosca_model_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_bin; + +CREATE TABLE IF NOT EXISTS tosca_model_revision ( + tosca_model_revision_id VARCHAR(36) NOT NULL, + tosca_model_id VARCHAR(36) NOT NULL, + version DOUBLE NOT NULL DEFAULT 1, + tosca_model_yaml MEDIUMTEXT NULL, + tosca_model_json MEDIUMTEXT NULL, + user_id VARCHAR(80), + createdTimestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + lastUpdatedTimestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (tosca_model_revision_id), + CONSTRAINT tosca_model_revision_ukey UNIQUE KEY (tosca_model_id, version), + CONSTRAINT tosca_model_revision_fkey01 FOREIGN KEY (tosca_model_id) REFERENCES tosca_model (tosca_model_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_bin; + +CREATE TABLE IF NOT EXISTS dictionary ( + dictionary_id VARCHAR(36) NOT NULL, + dictionary_name VARCHAR(80) NOT NULL, + created_by VARCHAR(80), + modified_by VARCHAR(80), + timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (dictionary_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_bin; + +CREATE TABLE IF NOT EXISTS dictionary_elements ( + dict_element_id VARCHAR(36) NOT NULL, + dictionary_id VARCHAR(36) NOT NULL, + dict_element_name VARCHAR(250) NOT NULL, + dict_element_short_name VARCHAR(80) NOT NULL, + dict_element_description VARCHAR(250), + dict_element_type VARCHAR(80) NOT NULL, + created_by VARCHAR(80), + modified_by VARCHAR(80), + timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (dict_element_id), + CONSTRAINT dictionary_elements_ukey UNIQUE KEY (dict_element_name, dict_element_short_name), + CONSTRAINT dictionary_elements_ukey_fkey01 FOREIGN KEY (dictionary_id) REFERENCES dictionary (dictionary_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_bin; + ALTER TABLE template ADD CONSTRAINT template_bpmn_id_fkey01 FOREIGN KEY (template_bpmn_id) diff --git a/extra/sql/bulkload/clds-stored-procedures.sql b/extra/sql/bulkload/clds-stored-procedures.sql index d09d3fc8..10771745 100644 --- a/extra/sql/bulkload/clds-stored-procedures.sql +++ b/extra/sql/bulkload/clds-stored-procedures.sql @@ -15,6 +15,10 @@ DROP PROCEDURE IF EXISTS get_model_template; DROP PROCEDURE IF EXISTS set_template; DROP PROCEDURE IF EXISTS get_template; DROP PROCEDURE IF EXISTS del_model; +DROP PROCEDURE IF EXISTS set_new_tosca_model_version; +DROP PROCEDURE IF EXISTS set_tosca_model; +DROP PROCEDURE IF EXISTS set_dictionary; +DROP PROCEDURE IF EXISTS set_dictionary_elements; DELIMITER // CREATE PROCEDURE get_template (IN v_template_name VARCHAR(80), @@ -456,5 +460,65 @@ BEGIN DELETE from model_properties where model_id = v_model_id; DELETE from model where model_id = v_model_id; END + +CREATE PROCEDURE set_new_tosca_model_version + (IN v_tosca_model_id VARCHAR(36), + IN v_version DOUBLE, + IN v_tosca_model_yaml MEDIUMTEXT, + IN v_tosca_model_json MEDIUMTEXT, + IN v_user_id VARCHAR(80), + OUT v_revision_id VARCHAR(36)) +BEGIN + SET v_revision_id = UUID(); + INSERT INTO tosca_model_revision + (tosca_model_revision_id, tosca_model_id, version, tosca_model_yaml, tosca_model_json, user_id) + VALUES (v_revision_id, v_tosca_model_id, v_version, v_tosca_model_yaml, v_tosca_model_json, v_user_id); +END; + +CREATE PROCEDURE set_tosca_model + (IN v_tosca_model_name VARCHAR(80), + IN v_policy_type VARCHAR(80), + IN v_user_id VARCHAR(80), + IN v_tosca_model_yaml MEDIUMTEXT, + IN v_tosca_model_json MEDIUMTEXT, + IN v_version DOUBLE, + OUT v_tosca_model_id VARCHAR(36), + OUT v_revision_id VARCHAR(36)) +BEGIN + SET v_tosca_model_id = UUID(); + INSERT INTO tosca_model + (tosca_model_id, tosca_model_name, policy_type, user_id) + VALUES (v_tosca_model_id, v_tosca_model_name, v_policy_type, v_user_id); + SET v_revision_id = UUID(); + INSERT INTO tosca_model_revision + (tosca_model_revision_id, tosca_model_id, version, tosca_model_yaml, tosca_model_json, user_id) + VALUES (v_revision_id, v_tosca_model_id, v_version, v_tosca_model_yaml, v_tosca_model_json, v_user_id); +END; + +CREATE PROCEDURE set_dictionary + (IN v_dictionary_name VARCHAR(80), + IN v_user_id VARCHAR(80), + OUT v_dictionary_id VARCHAR(36)) +BEGIN + SET v_dictionary_id = UUID(); + INSERT INTO dictionary + (dictionary_id, dictionary_name, created_by, modified_by) + VALUES (v_dictionary_id, v_dictionary_name, v_user_id, v_user_id); +END; + +CREATE PROCEDURE set_dictionary_elements + (IN v_dictionary_id VARCHAR(36), + IN v_dict_element_name VARCHAR(250), + IN v_dict_element_short_name VARCHAR(80), + IN v_dict_element_description VARCHAR(250), + IN v_dict_element_type VARCHAR(80), + IN v_user_id VARCHAR(80), + OUT v_dict_element_id VARCHAR(36)) +BEGIN + SET v_dict_element_id = UUID(); + INSERT INTO dictionary_elements + (dict_element_id, dictionary_id, dict_element_name, dict_element_short_name, dict_element_description, dict_element_type, created_by, modified_by) + VALUES (v_dict_element_id, v_dictionary_id, v_dict_element_name, v_dict_element_short_name, v_dict_element_description, v_dict_element_type, v_user_id, v_user_id); +END; // DELIMITER ; diff --git a/extra/sql/drop/clds-drop-db-objects.sql b/extra/sql/drop/clds-drop-db-objects.sql index 478eaf0e..1c173a41 100644 --- a/extra/sql/drop/clds-drop-db-objects.sql +++ b/extra/sql/drop/clds-drop-db-objects.sql @@ -31,3 +31,9 @@ DROP TABLE template_doc; DROP TABLE template_image; DROP TABLE template_bpmn; DROP TABLE template; + +DROP TABLE dictionary_elements; +DROP TABLE dictionary; +DROP TABLE tosca_model_revision; +DROP TABLE tosca_model; + diff --git a/pom.xml b/pom.xml index 2f4818c7..68b80ab8 100644 --- a/pom.xml +++ b/pom.xml @@ -20,9 +20,7 @@ ============LICENSE_END============================================ =================================================================== --> - - + 4.0.0 org.onap.clamp clds @@ -32,7 +30,7 @@ org.onap.oparent oparent - 1.1.0 + 1.2.0 @@ -85,7 +83,7 @@ true true false - + 8.5.32 @@ -393,7 +391,7 @@ org.onap.policy.engine PolicyEngineAPI - 1.2.0 + 1.2.3 com.google.guava @@ -448,7 +446,7 @@ org.onap.policy.common ONAP-Logging - 1.1.3 + 1.2.3 log4j @@ -465,9 +463,9 @@ - org.onap.policy.drools-applications + org.onap.policy.drools-applications.controlloop.common policy-yaml - 1.1.3 + 1.2.3 log4j @@ -484,9 +482,9 @@ - org.onap.policy.drools-applications + org.onap.policy.drools-applications.controlloop.common.model-impl sdc - 1.1.3 + 1.2.3 log4j @@ -503,9 +501,9 @@ - org.onap.policy.drools-applications + org.onap.policy.drools-applications.controlloop.common.model-impl aai - 1.1.3 + 1.2.3 log4j @@ -545,7 +543,7 @@ com.google.guava guava - 25.1-jre + @@ -711,10 +709,10 @@ book left 3 - - - - + + + + ${project.build.directory}/asciidoc/generated diff --git a/src/main/java/org/onap/clamp/clds/ClampServlet.java b/src/main/java/org/onap/clamp/clds/ClampServlet.java index 549b12f9..516325cb 100644 --- a/src/main/java/org/onap/clamp/clds/ClampServlet.java +++ b/src/main/java/org/onap/clamp/clds/ClampServlet.java @@ -36,9 +36,10 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.camel.component.servlet.CamelHttpTransportServlet; +import org.onap.aaf.cadi.principal.X509Principal; import org.onap.clamp.clds.service.SecureServicePermission; -import org.onap.clamp.clds.util.ClampTimer; import org.springframework.context.ApplicationContext; +import org.springframework.http.HttpStatus; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; @@ -49,62 +50,79 @@ import org.springframework.web.context.support.WebApplicationContextUtils; public class ClampServlet extends CamelHttpTransportServlet { + /** + * + */ + private static final long serialVersionUID = -4198841134910211542L; + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(ClampServlet.class); public static final String PERM_INSTANCE = "clamp.config.security.permission.instance"; public static final String PERM_CL = "clamp.config.security.permission.type.cl"; public static final String PERM_TEMPLATE = "clamp.config.security.permission.type.template"; public static final String PERM_VF = "clamp.config.security.permission.type.filter.vf"; public static final String PERM_MANAGE = "clamp.config.security.permission.type.cl.manage"; + public static final String PERM_TOSCA = "clamp.config.security.permission.type.tosca"; + private static List permissionList; - @Override - protected void doService(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - List permissionList = new ArrayList<>(); - - // Get Principal info and translate it into Spring Authentication If - // authenticataion is null: a) the authentication info was set manually - // in the previous thread b) handled by Spring automatically for the 2 - // cases above, no need for the translation, just skip the following - // step - if (null == authentication) { - logger.debug("Populate Spring Authenticataion info manually."); + private synchronized List getPermissionList() { + if (permissionList == null) { + permissionList=new ArrayList<>(); ApplicationContext applicationContext = WebApplicationContextUtils - .getWebApplicationContext(this.getServletContext()); - // Start a timer to clear the authentication after 5 mins, so that - // the authentication will be reinitialized with AAF DB - new ClampTimer(300); - String cldsPersmissionTypeCl = applicationContext.getEnvironment().getProperty(PERM_CL); - String cldsPermissionTypeTemplate = applicationContext.getEnvironment().getProperty(PERM_TEMPLATE); + .getWebApplicationContext(getServletContext()); String cldsPermissionInstance = applicationContext.getEnvironment().getProperty(PERM_INSTANCE); - String cldsPermissionTypeFilterVf = applicationContext.getEnvironment().getProperty(PERM_VF); - String cldsPermissionTypeClManage = applicationContext.getEnvironment().getProperty(PERM_MANAGE); - - // set the stragety to Mode_Global, so that all thread is able to - // see the authentication - SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL); - Principal p = request.getUserPrincipal(); + permissionList.add(SecureServicePermission.create(applicationContext.getEnvironment().getProperty(PERM_CL), + cldsPermissionInstance, "read")); + permissionList.add(SecureServicePermission.create(applicationContext.getEnvironment().getProperty(PERM_CL), + cldsPermissionInstance, "update")); + permissionList.add(SecureServicePermission.create( + applicationContext.getEnvironment().getProperty(PERM_TEMPLATE), cldsPermissionInstance, "read")); + permissionList.add(SecureServicePermission.create( + applicationContext.getEnvironment().getProperty(PERM_TEMPLATE), cldsPermissionInstance, "update")); + permissionList.add(SecureServicePermission.create(applicationContext.getEnvironment().getProperty(PERM_VF), + cldsPermissionInstance, "*")); + permissionList.add(SecureServicePermission + .create(applicationContext.getEnvironment().getProperty(PERM_MANAGE), cldsPermissionInstance, "*")); + permissionList.add(SecureServicePermission + .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, "read")); + permissionList.add(SecureServicePermission + .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, "update")); + } + return permissionList; + } - permissionList.add(SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "read")); - permissionList.add(SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "update")); - permissionList - .add(SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance, "read")); - permissionList - .add(SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance, "update")); - permissionList.add(SecureServicePermission.create(cldsPermissionTypeFilterVf, cldsPermissionInstance, "*")); - permissionList.add(SecureServicePermission.create(cldsPermissionTypeClManage, cldsPermissionInstance, "*")); + /** + * When AAF is enabled, request object will contain a cadi Wrapper, so queries + * to isUserInRole will invoke a http call to AAF server. + */ + @Override + protected void doService(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + Principal p = request.getUserPrincipal(); + if (p instanceof X509Principal) { + // When AAF is enabled, there is a need to provision the permissions to Spring + // system List grantedAuths = new ArrayList<>(); - for (SecureServicePermission perm : permissionList) { + for (SecureServicePermission perm : getPermissionList()) { String permString = perm.toString(); if (request.isUserInRole(permString)) { grantedAuths.add(new SimpleGrantedAuthority(permString)); } } Authentication auth = new UsernamePasswordAuthenticationToken(new User(p.getName(), "", grantedAuths), "", - grantedAuths); + grantedAuths); SecurityContextHolder.getContext().setAuthentication(auth); } - super.doService(request, response); + try { + super.doService(request, response); + } catch (ServletException | IOException ioe) { + logger.error("Exception caught when executing doService in servlet", ioe); + try { + response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value()); + } catch (IOException e) { + logger.error("Exception caught when executing HTTP sendError in servlet", e); + } + } + } } \ No newline at end of file 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 e324b2d9..39377d4a 100644 --- a/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java @@ -17,8 +17,9 @@ * 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; @@ -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,14 @@ 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; + @Autowired - private ClampProperties refProp; + public OperationalPolicyDelegate(PolicyClient policyClient, ClampProperties refProp) { + this.policyClient = policyClient; + this.refProp = refProp; + } /** * Perform activity. Send Operational Policy info to policy api. @@ -69,7 +68,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,8 +79,8 @@ public class OperationalPolicyDelegate { Policy policy = prop.getType(Policy.class); if (policy.isFound()) { for (PolicyChain policyChain : prop.getType(Policy.class).getPolicyChains()) { - Map> attributes = OperationalPolicyReq.formatAttributes(refProp, - prop, prop.getType(Policy.class).getId(), policyChain); + Map> attributes = OperationalPolicyAttributesConstructor.formatAttributes(refProp, + prop, prop.getType(Policy.class).getId(), policyChain); responseMessage = policyClient.sendBrmsPolicy(attributes, prop, LoggingUtils.getRequestId()); } if (responseMessage != null) { diff --git a/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegate.java b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegate.java index 08cfba14..87299935 100644 --- a/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegate.java @@ -18,7 +18,7 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds.client; @@ -43,7 +43,7 @@ import org.springframework.stereotype.Component; public class OperationalPolicyDeleteDelegate { protected static final EELFLogger logger = EELFManager.getInstance() - .getLogger(OperationalPolicyDeleteDelegate.class); + .getLogger(OperationalPolicyDeleteDelegate.class); protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); @Autowired private PolicyClient policyClient; 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 00000000..c28f700b --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructor.java @@ -0,0 +1,153 @@ +/*- + * ============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 java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; + +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; + +public class OperationalPolicyAttributesConstructor { + + private static final EELFLogger logger = EELFManager.getInstance() + .getLogger(OperationalPolicyAttributesConstructor.class); + public static final String TEMPLATE_NAME = "templateName"; + public static final String CLOSED_LOOP_CONTROL_NAME = "closedLoopControlName"; + public static final String NOTIFICATION_TOPIC = "notificationTopic"; + public static final String OPERATION_TOPIC = "operationTopic"; + public static final String CONTROL_LOOP_YAML = "controlLoopYaml"; + public static final String CONTROLLER = "controller"; + public static final String RECIPE = "Recipe"; + public static final String MAX_RETRIES = "MaxRetries"; + public static final String RETRY_TIME_LIMIT = "RetryTimeLimit"; + public static final String RESOURCE_ID = "ResourceId"; + public static final String RECIPE_TOPIC = "RecipeTopic"; + + private OperationalPolicyAttributesConstructor() { + } + + public static Map> 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 ruleAttributes = prepareRuleAttributes(refProp, modelProperties, modelElementId, + policyChain, globalService); + Map matchingAttributes = prepareMatchingAttributes(refProp, globalService); + + return createAttributesMap(matchingAttributes, ruleAttributes); + } + + private static Map 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 ruleAttributes = new HashMap<>(); + ruleAttributes.put(TEMPLATE_NAME, templateName); + ruleAttributes.put(CLOSED_LOOP_CONTROL_NAME, modelProperties.getControlNameAndPolicyUniqueId()); + ruleAttributes.put(NOTIFICATION_TOPIC, notificationTopic); + + ImmutableMap attributes = createRuleAttributesFromPolicy(clampProperties, modelProperties, + modelElementId, policyChain, globalService, operationTopic); + ruleAttributes.putAll(attributes); + logger.info("Prepared: " + ruleAttributes); + return ruleAttributes; + } + + private static Map prepareMatchingAttributes(ClampProperties refProp, String globalService) { + logger.info("Preparing matching attributes..."); + String controller = refProp.getStringValue("op.controller", globalService); + Map matchingAttributes = new HashMap<>(); + matchingAttributes.put(CONTROLLER, controller); + logger.info("Prepared: " + matchingAttributes); + return matchingAttributes; + } + + private static Map> createAttributesMap(Map matchingAttributes, + Map ruleAttributes) { + Map> attributes = new HashMap<>(); + attributes.put(AttributeType.RULE, ruleAttributes); + attributes.put(AttributeType.MATCHING, matchingAttributes); + return attributes; + } + + private static ImmutableMap 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 static ImmutableMap createRuleAttributesFromPolicyItem(PolicyItem policyItem, String recipeTopic) { + logger.info("recipeTopic=" + recipeTopic); + return ImmutableMap.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 static ImmutableMap createRuleAttributesFromPolicyChain(PolicyChain policyChain, + ModelProperties modelProperties, + String modelElementId, + String operationTopic) + throws BuilderException, UnsupportedEncodingException { + logger.info("operationTopic=" + operationTopic); + String yaml = OperationalPolicyYamlFormatter.formatYaml(modelProperties, modelElementId, policyChain); + return ImmutableMap.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 similarity index 64% rename from src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyReq.java rename to src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyYamlFormatter.java index f062dfca..1fc36082 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,7 +21,6 @@ * =================================================================== * */ - package org.onap.clamp.clds.client.req.policy; import com.att.eelf.configuration.EELFLogger; @@ -37,12 +36,10 @@ 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; @@ -55,83 +52,14 @@ import org.onap.policy.sdc.Resource; import org.onap.policy.sdc.ResourceType; import org.onap.policy.sdc.Service; -/** - * Construct an Operational Policy request given CLDS objects. - */ -public class OperationalPolicyReq { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicyReq.class); +public class OperationalPolicyYamlFormatter { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicyYamlFormatter.class); - protected OperationalPolicyReq() { + protected OperationalPolicyYamlFormatter() { } - - /** - * Format Operational Policy attributes. - * - * @param refProp - * @param prop - * @param modelElementId - * @param policyChain - * @return - * @throws BuilderException - * @throws UnsupportedEncodingException - */ - public static Map> 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 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 matchingAttributes = new HashMap<>(); - matchingAttributes.put("controller", controller); - Map> 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 @@ -139,7 +67,7 @@ public class OperationalPolicyReq { * @throws BuilderException * @throws UnsupportedEncodingException */ - protected static String formatOpenLoopYaml(ClampProperties refProp, ModelProperties prop, String modelElementId, + public static String formatOpenLoopYaml(ModelProperties prop, String modelElementId, PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException { // get property objects Global global = prop.getGlobal(); @@ -147,7 +75,7 @@ public class OperationalPolicyReq { 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); // create builder ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(), policyChain.getTimeout(), service, vfResources); @@ -158,18 +86,7 @@ public class OperationalPolicyReq { 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, + public static String formatYaml(ModelProperties prop, String modelElementId, PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException { // get property objects Global global = prop.getGlobal(); @@ -177,8 +94,8 @@ public class OperationalPolicyReq { 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); + 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); @@ -209,7 +126,7 @@ public class OperationalPolicyReq { + parentPolicyObj.getName() + " - created by CLDS"; policyObj = builder.setPolicyForPolicyResult(policyName, policyDescription, actor, target, policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit(), - parentPolicyObj.getId(), convertToPolicyResult(policyItem.getParentPolicyConditions())); + parentPolicyObj.getId(), convertToPolicyResults(policyItem.getParentPolicyConditions())); logger.info("policyObj.id=" + policyObj.getId() + "; parentPolicyObj.id=" + parentPolicyObj.getId()); } policyObjMap.put(policyItem.getId(), policyObj); @@ -220,29 +137,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 orderParentFirst(List inOrigList) { + protected static List orderParentFirst(List inOrigList) { List inList = new ArrayList<>(); inList.addAll(inOrigList); List outList = new ArrayList<>(); @@ -286,31 +181,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 stringList, ResourceType resourceType) { + 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()); + } + } + + + protected static Resource[] convertToResources(List 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 prList) { + protected static PolicyResult[] convertToPolicyResults(List 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/client/req/policy/PolicyClient.java b/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java index cc97a7ce..cd387b3c 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java +++ b/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java @@ -18,7 +18,7 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds.client.req.policy; @@ -26,11 +26,8 @@ package org.onap.clamp.clds.client.req.policy; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.Date; -import java.util.List; import java.util.Map; import java.util.UUID; @@ -46,7 +43,6 @@ import org.onap.policy.api.ConfigRequestParameters; import org.onap.policy.api.DeletePolicyCondition; import org.onap.policy.api.DeletePolicyParameters; import org.onap.policy.api.PolicyChangeResponse; -import org.onap.policy.api.PolicyConfig; import org.onap.policy.api.PolicyConfigException; import org.onap.policy.api.PolicyConfigType; import org.onap.policy.api.PolicyEngine; @@ -95,7 +91,7 @@ public class PolicyClient { * @return The response message of policy */ public String sendBrmsPolicy(Map> attributes, ModelProperties prop, - String policyRequestUuid) { + String policyRequestUuid) { PolicyParameters policyParameters = new PolicyParameters(); // Set Policy Type(Mandatory) policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); @@ -160,7 +156,7 @@ public class PolicyClient { * @return The answer from policy call */ public String sendBasePolicyInOther(String configBody, String configPolicyName, ModelProperties prop, - String policyRequestUuid) { + String policyRequestUuid) { PolicyParameters policyParameters = new PolicyParameters(); // Set Policy Type policyParameters.setPolicyConfigType(PolicyConfigType.Base); @@ -181,7 +177,7 @@ public class PolicyClient { /** * Perform send of Microservice policy in OTHER type. - * + * * @param configBody * The config policy string body * @param prop @@ -224,8 +220,7 @@ public class PolicyClient { String responseMessage = ""; Date startTime = new Date(); try { - List versions = getVersions(policyNamePrefix, prop); - if (versions.isEmpty()) { + if (!checkPolicyExists(policyNamePrefix, prop)) { LoggingUtils.setTargetContext("Policy", "createPolicy"); logger.info("Attempting to create policy for action=" + prop.getActionCd()); response = getPolicyEngine().createPolicy(policyParameters); @@ -313,8 +308,8 @@ public class PolicyClient { } /** - * Use Get Config Policy API to retrieve the versions for a policy. Return - * versions in sorted order. Return empty list if none found. + * Use list Policy API to retrieve the policy. Return true if policy exists + * otherwise return false. * * @param policyNamePrefix * The Policy Name Prefix @@ -324,8 +319,8 @@ public class PolicyClient { * @throws PolicyConfigException * In case of issues with policy engine */ - protected List getVersions(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException { - ArrayList versions = new ArrayList<>(); + protected boolean checkPolicyExists(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException { + boolean policyexists = false; ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); String policyName = ""; if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) { @@ -336,27 +331,20 @@ public class PolicyClient { logger.info("Search in Policy Engine for policyName=" + policyName); configRequestParameters.setPolicyName(policyName); try { - Collection response = getPolicyEngine().getConfig(configRequestParameters); - for (PolicyConfig policyConfig : response) { - if (policyConfig.getPolicyVersion() != null) { - Integer version = Integer.valueOf(policyConfig.getPolicyVersion()); - versions.add(version); - } else { - logger.warn("Policy version was null, unable to convert it to Integer"); - } + Collection response = getPolicyEngine().listConfig(configRequestParameters); + if (response != null && !response.isEmpty()) { + policyexists = true; } - Collections.sort(versions); - logger.info("Policy versions.size()=" + versions.size()); } catch (PolicyConfigException e) { // just print warning - if no policy version found logger.warn("policy not found...policy name - " + policyName, e); } - return versions; + return policyexists; } /** * This method create a new policy engine. - * + * * @return A new policy engine */ private synchronized PolicyEngine getPolicyEngine() { @@ -381,8 +369,7 @@ public class PolicyClient { String deletePolicyResponse = ""; try { String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME); - List versions = getVersions(policyNamePrefix, prop); - if (!versions.isEmpty()) { + if (checkPolicyExists(policyNamePrefix, prop)) { String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME); deletePolicyResponse = deletePolicy(prop, policyType); } @@ -415,8 +402,7 @@ public class PolicyClient { String deletePolicyResponse = ""; try { String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME); - List versions = getVersions(policyNamePrefix, prop); - if (!versions.isEmpty()) { + if (checkPolicyExists(policyNamePrefix, prop)) { String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME); deletePolicyResponse = deletePolicy(prop, policyType); } diff --git a/src/main/java/org/onap/clamp/clds/config/AAFConfiguration.java b/src/main/java/org/onap/clamp/clds/config/AAFConfiguration.java index 13dccdac..8bc6f69d 100644 --- a/src/main/java/org/onap/clamp/clds/config/AAFConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/AAFConfiguration.java @@ -29,7 +29,6 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; -import org.springframework.stereotype.Component; @Configuration @Profile("clamp-aaf-authentication") @@ -54,7 +53,11 @@ public class AAFConfiguration { public FilterRegistrationBean cadiFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(cadiFilter()); - registration.addUrlPatterns("/restservices/*"); + registration.addUrlPatterns("/restservices/clds/v1/clds/*"); + registration.addUrlPatterns("/restservices/clds/v1/cldsTempate/*"); + registration.addUrlPatterns("/restservices/clds/v1/tosca/*"); + registration.addUrlPatterns("/restservices/clds/v1/dictionary/*"); + registration.addUrlPatterns("/restservices/clds/v1/user/*"); //registration.addUrlPatterns("*"); registration.setName("cadiFilter"); registration.setOrder(0); diff --git a/src/main/java/org/onap/clamp/clds/dao/CldsDao.java b/src/main/java/org/onap/clamp/clds/dao/CldsDao.java index a3771aa5..54a5196c 100644 --- a/src/main/java/org/onap/clamp/clds/dao/CldsDao.java +++ b/src/main/java/org/onap/clamp/clds/dao/CldsDao.java @@ -18,7 +18,7 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds.dao; @@ -29,13 +29,19 @@ import com.att.eelf.configuration.EELFManager; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; import javax.sql.DataSource; import org.onap.clamp.clds.model.CldsDbServiceCache; +import org.onap.clamp.clds.model.CldsDictionary; +import org.onap.clamp.clds.model.CldsDictionaryItem; import org.onap.clamp.clds.model.CldsEvent; import org.onap.clamp.clds.model.CldsModel; import org.onap.clamp.clds.model.CldsModelInstance; @@ -43,6 +49,7 @@ import org.onap.clamp.clds.model.CldsModelProp; import org.onap.clamp.clds.model.CldsMonitoringDetails; import org.onap.clamp.clds.model.CldsServiceData; import org.onap.clamp.clds.model.CldsTemplate; +import org.onap.clamp.clds.model.CldsToscaModel; import org.onap.clamp.clds.model.ValueItem; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; @@ -72,7 +79,13 @@ public class CldsDao { private static final String HEALTHCHECK = "Select 1"; private static final String V_CONTROL_NAME_PREFIX = "v_control_name_prefix"; private static final String V_CONTROL_NAME_UUID = "v_control_name_uuid"; - + + private SimpleJdbcCall procInsertToscaModel; + private SimpleJdbcCall procInsertNewToscaModelVersion; + private SimpleJdbcCall procInsertDictionary; + private SimpleJdbcCall procInsertDictionaryElement; + + private static final String DATE_FORMAT = "MM-dd-yyyy HH:mm:ss"; /** * Log message when instantiating */ @@ -95,6 +108,11 @@ public class CldsDao { this.procInsModelInstance = new SimpleJdbcCall(dataSource).withProcedureName("ins_model_instance"); this.procDelAllModelInstances = new SimpleJdbcCall(dataSource).withProcedureName("del_all_model_instances"); this.procDeleteModel = new SimpleJdbcCall(dataSource).withProcedureName("del_model"); + this.procInsertToscaModel = new SimpleJdbcCall(dataSource).withProcedureName("set_tosca_model"); + this.procInsertNewToscaModelVersion = new SimpleJdbcCall(dataSource) + .withProcedureName("set_new_tosca_model_version"); + this.procInsertDictionary = new SimpleJdbcCall(dataSource).withProcedureName("set_dictionary"); + this.procInsertDictionaryElement = new SimpleJdbcCall(dataSource).withProcedureName("set_dictionary_elements"); } /** @@ -116,15 +134,14 @@ public class CldsDao { CldsModel model = new CldsModel(); model.setName(modelName); SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName) - .addValue(V_CONTROL_NAME_UUID, controlNameUuid); + .addValue(V_CONTROL_NAME_UUID, controlNameUuid); Map out = logSqlExecution(procGetModel, in); populateModelProperties(model, out); return model; } /** - * Get a model and template information from the database given the model - * name. + * Get a model and template information from the database given the model name. * * @param modelName * @return model @@ -134,14 +151,12 @@ public class CldsDao { model.setName(modelName); SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName); Map out = logSqlExecution(procGetModelTemplate, in); - // todo : rationalize populateModelProperties(model, out); Map modelResults = logSqlExecution(procGetModel, in); Object modelResultObject = modelResults.get("#result-set-1"); - if (modelResultObject != null && modelResultObject instanceof ArrayList) { - List modelInstanceRs = (List) modelResultObject; - for (Object currModelInstance : modelInstanceRs) { - if (currModelInstance != null && currModelInstance instanceof HashMap) { + if (modelResultObject instanceof ArrayList) { + for (Object currModelInstance : (List) modelResultObject) { + if (currModelInstance instanceof HashMap) { HashMap modelInstanceMap = (HashMap) currModelInstance; CldsModelInstance modelInstance = new CldsModelInstance(); modelInstance.setModelInstanceId(modelInstanceMap.get("model_instance_id")); @@ -156,8 +171,8 @@ public class CldsDao { } /** - * Update model in the database using parameter values and return updated - * model object. + * Update model in the database using parameter values and return updated model + * object. * * @param model * @param userid @@ -165,12 +180,12 @@ public class CldsDao { */ public CldsModel setModel(CldsModel model, String userid) { SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", model.getName()) - .addValue("v_template_id", model.getTemplateId()).addValue("v_user_id", userid) - .addValue("v_model_prop_text", model.getPropText()) - .addValue("v_model_blueprint_text", model.getBlueprintText()) - .addValue("v_service_type_id", model.getTypeId()).addValue("v_deployment_id", model.getDeploymentId()) - .addValue("v_control_name_prefix", model.getControlNamePrefix()) - .addValue(V_CONTROL_NAME_UUID, model.getControlNameUuid()); + .addValue("v_template_id", model.getTemplateId()).addValue("v_user_id", userid) + .addValue("v_model_prop_text", model.getPropText()) + .addValue("v_model_blueprint_text", model.getBlueprintText()) + .addValue("v_service_type_id", model.getTypeId()).addValue("v_deployment_id", model.getDeploymentId()) + .addValue("v_control_name_prefix", model.getControlNamePrefix()) + .addValue(V_CONTROL_NAME_UUID, model.getControlNameUuid()); Map out = logSqlExecution(procSetModel, in); model.setControlNamePrefix((String) out.get(V_CONTROL_NAME_PREFIX)); model.setControlNameUuid((String) out.get(V_CONTROL_NAME_UUID)); @@ -184,8 +199,8 @@ public class CldsDao { } /** - * Inserts new modelInstance in the database using parameter values and - * return updated model object. + * Inserts new modelInstance in the database using parameter values and return + * updated model object. * * @param model * @param modelInstancesList @@ -203,9 +218,9 @@ public class CldsDao { logger.debug("v_vm_name={}", currModelInstance.getVmName()); logger.debug("v_location={}", currModelInstance.getLocation()); SqlParameterSource in = new MapSqlParameterSource() - .addValue(V_CONTROL_NAME_UUID, model.getControlNameUuid()) - .addValue("v_vm_name", currModelInstance.getVmName()) - .addValue("v_location", currModelInstance.getLocation()); + .addValue(V_CONTROL_NAME_UUID, model.getControlNameUuid()) + .addValue("v_vm_name", currModelInstance.getVmName()) + .addValue("v_location", currModelInstance.getLocation()); Map out = logSqlExecution(procInsModelInstance, in); model.setId((String) (out.get("v_model_id"))); CldsModelInstance modelInstance = new CldsModelInstance(); @@ -230,10 +245,10 @@ public class CldsDao { public CldsEvent insEvent(String modelName, String controlNamePrefix, String controlNameUuid, CldsEvent cldsEvent) { CldsEvent event = new CldsEvent(); SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName) - .addValue(V_CONTROL_NAME_PREFIX, controlNamePrefix).addValue(V_CONTROL_NAME_UUID, controlNameUuid) - .addValue("v_user_id", cldsEvent.getUserid()).addValue("v_action_cd", cldsEvent.getActionCd()) - .addValue("v_action_state_cd", cldsEvent.getActionStateCd()) - .addValue("v_process_instance_id", cldsEvent.getProcessInstanceId()); + .addValue(V_CONTROL_NAME_PREFIX, controlNamePrefix).addValue(V_CONTROL_NAME_UUID, controlNameUuid) + .addValue("v_user_id", cldsEvent.getUserid()).addValue("v_action_cd", cldsEvent.getActionCd()) + .addValue("v_action_state_cd", cldsEvent.getActionStateCd()) + .addValue("v_process_instance_id", cldsEvent.getProcessInstanceId()); Map out = logSqlExecution(procInsEvent, in); event.setId((String) (out.get("v_event_id"))); return event; @@ -253,7 +268,7 @@ public class CldsDao { */ public void updEvent(String eventId, String processInstanceId) { SqlParameterSource in = new MapSqlParameterSource().addValue("v_event_id", eventId) - .addValue("v_process_instance_id", processInstanceId); + .addValue("v_process_instance_id", processInstanceId); logSqlExecution(procUpdEvent, in); } @@ -276,9 +291,9 @@ public class CldsDao { */ public void setTemplate(CldsTemplate template, String userid) { SqlParameterSource in = new MapSqlParameterSource().addValue("v_template_name", template.getName()) - .addValue("v_user_id", userid).addValue("v_template_bpmn_text", template.getBpmnText()) - .addValue("v_template_image_text", template.getImageText()) - .addValue("v_template_doc_text", template.getPropText()); + .addValue("v_user_id", userid).addValue("v_template_bpmn_text", template.getBpmnText()) + .addValue("v_template_image_text", template.getImageText()) + .addValue("v_template_doc_text", template.getPropText()); Map out = logSqlExecution(procSetTemplate, in); template.setId((String) (out.get("v_template_id"))); template.setBpmnUserid((String) (out.get("v_template_bpmn_user_id"))); @@ -333,10 +348,10 @@ public class CldsDao { try { String getCldsServiceSQL = "SELECT * , TIMESTAMPDIFF(SECOND, timestamp, CURRENT_TIMESTAMP()) FROM clds_service_cache where invariant_service_id = ? "; cldsServiceData = jdbcTemplateObject.queryForObject(getCldsServiceSQL, new Object[] { invariantUUID }, - new CldsServiceDataMapper()); + new CldsServiceDataMapper()); if (cldsServiceData != null) { logger.info("CldsServiceData found in cache for Service Invariant ID:" - + cldsServiceData.getServiceInvariantUUID()); + + cldsServiceData.getServiceInvariantUUID()); return cldsServiceData; } else { logger.warn("CldsServiceData not found in cache for Service Invariant ID:" + invariantUUID); @@ -351,13 +366,13 @@ public class CldsDao { public void setCldsServiceCache(CldsDbServiceCache cldsDBServiceCache) { if (cldsDBServiceCache != null && cldsDBServiceCache.getInvariantId() != null - && cldsDBServiceCache.getServiceId() != null) { + && cldsDBServiceCache.getServiceId() != null) { String invariantUuid = cldsDBServiceCache.getInvariantId(); String serviceUuid = cldsDBServiceCache.getServiceId(); InputStream is = cldsDBServiceCache.getCldsDataInstream(); String insertCldsServiceCacheSql = "INSERT INTO clds_service_cache" - + "(invariant_service_id,service_id,timestamp,object_data) VALUES" - + "(?,?,CURRENT_TIMESTAMP,?) ON DUPLICATE KEY UPDATE invariant_service_id = VALUES(invariant_service_id) , timestamp = CURRENT_TIMESTAMP , object_data = VALUES(object_data) "; + + "(invariant_service_id,service_id,timestamp,object_data) VALUES" + + "(?,?,CURRENT_TIMESTAMP,?) ON DUPLICATE KEY UPDATE invariant_service_id = VALUES(invariant_service_id) , timestamp = CURRENT_TIMESTAMP , object_data = VALUES(object_data) "; jdbcTemplateObject.update(insertCldsServiceCacheSql, invariantUuid, serviceUuid, is); } } @@ -377,13 +392,13 @@ public class CldsDao { /** * Method to get deployed/active models with model properties. - * + * * @return list of CldsModelProp */ public List getDeployedModelProperties() { List cldsModelPropList = new ArrayList<>(); String modelsSql = "select m.model_id, m.model_name, mp.model_prop_id, mp.model_prop_text FROM model m, model_properties mp, event e " - + "WHERE m.model_prop_id = mp.model_prop_id and m.event_id = e.event_id and e.action_cd = 'DEPLOY'"; + + "WHERE m.model_prop_id = mp.model_prop_id and m.event_id = e.event_id and e.action_cd = 'DEPLOY'"; List> rows = jdbcTemplateObject.queryForList(modelsSql); CldsModelProp cldsModelProp = null; for (Map row : rows) { @@ -399,23 +414,22 @@ public class CldsDao { /** * Method to get deployed/active models with model properties. - * + * * @return list of CLDS-Monitoring-Details: CLOSELOOP_NAME | Close loop name - * used in the CLDS application (prefix: ClosedLoop- + unique - * ClosedLoop ID) MODEL_NAME | Model Name in CLDS application - * SERVICE_TYPE_ID | TypeId returned from the DCAE application when - * the ClosedLoop is submitted (DCAEServiceTypeRequest generated in - * DCAE application). DEPLOYMENT_ID | Id generated when the - * ClosedLoop is deployed in DCAE. TEMPLATE_NAME | Template used to - * generate the ClosedLoop model. ACTION_CD | Current state of the - * ClosedLoop in CLDS application. + * used in the CLDS application (prefix: ClosedLoop- + unique ClosedLoop + * ID) MODEL_NAME | Model Name in CLDS application SERVICE_TYPE_ID | + * TypeId returned from the DCAE application when the ClosedLoop is + * submitted (DCAEServiceTypeRequest generated in DCAE application). + * DEPLOYMENT_ID | Id generated when the ClosedLoop is deployed in DCAE. + * TEMPLATE_NAME | Template used to generate the ClosedLoop model. + * ACTION_CD | Current state of the ClosedLoop in CLDS application. */ public List getCLDSMonitoringDetails() { - SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss"); - List cldsMonitoringDetailsList = new ArrayList(); + SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + List cldsMonitoringDetailsList = new ArrayList<>(); String modelsSql = "SELECT CONCAT(M.CONTROL_NAME_PREFIX, M.CONTROL_NAME_UUID) AS CLOSELOOP_NAME , M.MODEL_NAME, M.SERVICE_TYPE_ID, M.DEPLOYMENT_ID, T.TEMPLATE_NAME, E.ACTION_CD, E.USER_ID, E.TIMESTAMP " - + "FROM MODEL M, TEMPLATE T, EVENT E " - + "WHERE M.TEMPLATE_ID = T.TEMPLATE_ID AND M.EVENT_ID = E.EVENT_ID " + "ORDER BY ACTION_CD"; + + "FROM MODEL M, TEMPLATE T, EVENT E " + "WHERE M.TEMPLATE_ID = T.TEMPLATE_ID AND M.EVENT_ID = E.EVENT_ID " + + "ORDER BY ACTION_CD"; List> rows = jdbcTemplateObject.queryForList(modelsSql); CldsMonitoringDetails cldsMonitoringDetails = null; for (Map row : rows) { @@ -435,16 +449,15 @@ public class CldsDao { /** * Method to delete model from database. - * + * * @param modelName */ public void deleteModel(String modelName) { SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName); logSqlExecution(procDeleteModel, in); } - + private void populateModelProperties(CldsModel model, Map out) { - // todo : rationalize model.setControlNamePrefix((String) out.get(V_CONTROL_NAME_PREFIX)); model.setControlNameUuid((String) out.get(V_CONTROL_NAME_UUID)); model.setId((String) (out.get("v_model_id"))); @@ -461,6 +474,252 @@ public class CldsDao { model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id")); model.getEvent().setUserid((String) out.get("v_event_user_id")); model.setTypeId((String) out.get("v_service_type_id")); - model.setDeploymentId((String) out.get("v_deployment_id")); - } + model.setDeploymentId((String) out.get("v_deployment_id")); + } + + /** + * Method to retrieve a tosca models by Policy Type from database. + * + * @param policyType + * @return List of CldsToscaModel + */ + public List getAllToscaModels() { + return getToscaModel(null, null); + } + + /** + * Method to retrieve a tosca models by Policy Type from database. + * + * @param policyType + * @return List of CldsToscaModel + */ + public List getToscaModelByPolicyType(String policyType) { + return getToscaModel(null, policyType); + } + + /** + * Method to retrieve a tosca models by toscaModelName, version from database. + * + * @param policyType + * @return List of CldsToscaModel + */ + public List getToscaModelByName(String toscaModelName) { + return getToscaModel(toscaModelName, null); + } + + // Retrieve the latest tosca model for a policy type or by tosca model name + + private List getToscaModel(String toscaModelName, String policyType) { + SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + List cldsToscaModels = new ArrayList<>(); + MapSqlParameterSource params = new MapSqlParameterSource(); + + String toscaModelSql = "SELECT tm.tosca_model_name, tm.tosca_model_id, tm.policy_type, tmr.tosca_model_revision_id, tmr.version, tmr.user_id, tmr.createdTimestamp, tmr.lastUpdatedTimestamp, tmr.tosca_model_yaml FROM tosca_model tm, tosca_model_revision tmr WHERE tm.tosca_model_id = tmr.tosca_model_id "; + if (toscaModelName != null) { + toscaModelSql += " AND tm.tosca_model_name = :toscaModelName"; + params.addValue("toscaModelName", toscaModelName); + } + if (policyType != null) { + toscaModelSql += " AND tm.policy_type = :policyType"; + params.addValue("policyType", policyType); + } + toscaModelSql += " AND tmr.version = (select max(version) from tosca_model_revision st where tmr.tosca_model_id=st.tosca_model_id)"; + + Optional.ofNullable(jdbcTemplateObject.queryForList(toscaModelSql, params)).orElse(Collections.emptyList()).forEach(row -> { + CldsToscaModel cldsToscaModel = new CldsToscaModel(); + cldsToscaModel.setId((String) row.get("tosca_model_id")); + cldsToscaModel.setPolicyType((String) row.get("policy_type")); + cldsToscaModel.setToscaModelName((String) row.get("tosca_model_name")); + cldsToscaModel.setUserId((String) row.get("user_id")); + cldsToscaModel.setRevisionId((String) row.get("tosca_model_revision_id")); + cldsToscaModel.setVersion(((Double) row.get("version"))); + cldsToscaModel.setCreatedDate(sdf.format(row.get("createdTimestamp"))); + cldsToscaModel.setToscaModelYaml((String) row.get("tosca_model_yaml")); + cldsToscaModels.add(cldsToscaModel); + }); + return cldsToscaModels; + } + + /** + * Method to upload a new version of Tosca Model Yaml in Database + * + * @param cldsToscaModel + * @param userId + * @return CldsToscaModel + * + */ + public CldsToscaModel updateToscaModelWithNewVersion(CldsToscaModel cldsToscaModel, String userId) { + SqlParameterSource in = new MapSqlParameterSource().addValue("v_tosca_model_id", cldsToscaModel.getId()) + .addValue("v_version", cldsToscaModel.getVersion()) + .addValue("v_tosca_model_yaml", cldsToscaModel.getToscaModelYaml()) + .addValue("v_tosca_model_json", cldsToscaModel.getToscaModelJson()).addValue("v_user_id", userId); + Map out = logSqlExecution(procInsertNewToscaModelVersion, in); + cldsToscaModel.setRevisionId((String) (out.get("v_revision_id"))); + return cldsToscaModel; + } + + /** + * Method to upload a new Tosca model Yaml in DB. Default version is 1.0 + * + * @param cldsToscaModel + * @param userId + * @return CldsToscaModel + */ + public CldsToscaModel insToscaModel(CldsToscaModel cldsToscaModel, String userId) { + SqlParameterSource in = new MapSqlParameterSource() + .addValue("v_tosca_model_name", cldsToscaModel.getToscaModelName()) + .addValue("v_policy_type", cldsToscaModel.getPolicyType()) + .addValue("v_tosca_model_yaml", cldsToscaModel.getToscaModelYaml()) + .addValue("v_tosca_model_json", cldsToscaModel.getToscaModelJson()) + .addValue("v_version", cldsToscaModel.getVersion()).addValue("v_user_id", userId); + Map out = logSqlExecution(procInsertToscaModel, in); + cldsToscaModel.setId((String) (out.get("v_tosca_model_id"))); + cldsToscaModel.setRevisionId((String) (out.get("v_revision_id"))); + cldsToscaModel.setUserId((String) out.get("v_user_id")); + return cldsToscaModel; + } + + /** + * Method to insert a new Dictionary in Database + * + * @param cldsDictionary + */ + public void insDictionary(CldsDictionary cldsDictionary) { + SqlParameterSource in = new MapSqlParameterSource() + .addValue("v_dictionary_name", cldsDictionary.getDictionaryName()) + .addValue("v_user_id", cldsDictionary.getCreatedBy()); + Map out = logSqlExecution(procInsertDictionary, in); + cldsDictionary.setDictionaryId((String) (out.get("v_dictionary_id"))); + } + + /** + * Method to update Dictionary with new info in Database + * + * @param dictionaryId + * @param cldsDictionary + * @param userId + */ + public void updateDictionary(String dictionaryId, CldsDictionary cldsDictionary, String userId) { + String dictionarySql = "UPDATE dictionary SET dictionary_name = :dictionary_name, modified_by = :modified_by WHERE dictionary_id = :dictionary_id"; + SqlParameterSource namedParameters = new MapSqlParameterSource() + .addValue("dictionary_name", cldsDictionary.getDictionaryName()).addValue("modified_by", userId) + .addValue("dictionary_id", dictionaryId); + jdbcTemplateObject.update(dictionarySql, namedParameters); + cldsDictionary.setUpdatedBy(userId); + } + + /** + * Method to get list of Dictionaries from the Database + * + * @param dictionaryId + * @param dictionaryName + * @return + */ + public List getDictionary(String dictionaryId, String dictionaryName) { + SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + List dictionaries = new ArrayList<>(); + String dictionarySql = "SELECT dictionary_id, dictionary_name, created_by, modified_by, timestamp FROM dictionary WHERE "; + MapSqlParameterSource namedParameters = new MapSqlParameterSource(); + Optional.ofNullable(dictionaryName).ifPresent(dn -> namedParameters.addValue("dictionary_name", dn)); + Optional.ofNullable(dictionaryId).ifPresent(dn -> namedParameters.addValue("dictionary_id", dn)); + dictionarySql += Optional.ofNullable(namedParameters.getParameterNames()).filter(a -> a.length > 0) + .map(Arrays::stream).map(s -> s.map(param -> param + " = :" + param).collect(Collectors.joining(" AND "))) + .orElse("1"); + + Optional.ofNullable(jdbcTemplateObject.queryForList(dictionarySql, namedParameters)).orElse(Collections.emptyList()).forEach(row -> { + CldsDictionary cldsDictionary = new CldsDictionary(); + cldsDictionary.setDictionaryId((String) row.get("dictionary_id")); + cldsDictionary.setDictionaryName((String) row.get("dictionary_name")); + cldsDictionary.setCreatedBy((String) row.get("created_by")); + cldsDictionary.setUpdatedBy((String) row.get("modified_by")); + cldsDictionary.setLastUpdatedDate(sdf.format(row.get("timestamp"))); + dictionaries.add(cldsDictionary); + }); + return dictionaries; + } + + /** + * Method to insert a new Dictionary Element for given dictionary in Database + * + * @param cldsDictionaryItem + * @param userId + */ + public void insDictionarElements(CldsDictionaryItem cldsDictionaryItem, String userId) { + SqlParameterSource in = new MapSqlParameterSource() + .addValue("v_dictionary_id", cldsDictionaryItem.getDictionaryId()) + .addValue("v_dict_element_name", cldsDictionaryItem.getDictElementName()) + .addValue("v_dict_element_short_name", cldsDictionaryItem.getDictElementShortName()) + .addValue("v_dict_element_description", cldsDictionaryItem.getDictElementDesc()) + .addValue("v_dict_element_type", cldsDictionaryItem.getDictElementType()).addValue("v_user_id", userId); + Map out = logSqlExecution(procInsertDictionaryElement, in); + cldsDictionaryItem.setDictElementId((String) (out.get("v_dict_element_id"))); + } + + /** + * Method to update Dictionary Elements with new info for a given dictionary in + * Database + * + * @param dictionaryElementId + * @param cldsDictionaryItem + * @param userId + */ + public void updateDictionaryElements(String dictionaryElementId, CldsDictionaryItem cldsDictionaryItem, + String userId) { + + String dictionarySql = "UPDATE dictionary_elements SET dict_element_name = :dict_element_name, dict_element_short_name = :dict_element_short_name, dict_element_description = :dict_element_description,dict_element_type=:dict_element_type, modified_by = :modified_by WHERE dict_element_id = :dict_element_id"; + SqlParameterSource namedParameters = new MapSqlParameterSource() + .addValue("dict_element_name", cldsDictionaryItem.getDictElementName()) + .addValue("dict_element_short_name", cldsDictionaryItem.getDictElementShortName()) + .addValue("dict_element_description", cldsDictionaryItem.getDictElementDesc()) + .addValue("dict_element_type", cldsDictionaryItem.getDictElementType()) + .addValue("modified_by", userId) + .addValue("dict_element_id", dictionaryElementId); + jdbcTemplateObject.update(dictionarySql, namedParameters); + cldsDictionaryItem.setUpdatedBy(userId); + } + + /** + * Method to get list of all dictionary elements for a given dictionary in the + * Database + * + * @param dictionaryName + * @param dictionaryId + * @param dictElementShortName + * @return + */ + public List getDictionaryElements(String dictionaryName, String dictionaryId, + String dictElementShortName) { + SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + List dictionaryItems = new ArrayList<>(); + MapSqlParameterSource namedParameters = new MapSqlParameterSource(); + String dictionarySql = "SELECT de.dict_element_id, de.dictionary_id, de.dict_element_name, de.dict_element_short_name, de.dict_element_description, de.dict_element_type, de.created_by, de.modified_by, de.timestamp " + + "FROM dictionary_elements de, dictionary d WHERE de.dictionary_id = d.dictionary_id "; + if (dictionaryId != null) { + dictionarySql+=" AND d.dictionary_id = :dictionaryId"; + namedParameters.addValue("dictionaryId", dictionaryId); + } + if (dictElementShortName!=null) { + dictionarySql+=" AND de.dict_element_short_name = :dictElementShortName"; + namedParameters.addValue("dictElementShortName", dictElementShortName); + } + if (dictionaryName!=null) { + dictionarySql+=" AND dictionary_name = :dictionaryName"; + namedParameters.addValue("dictionaryName", dictionaryName); + } + + Optional.ofNullable(jdbcTemplateObject.queryForList(dictionarySql,namedParameters)).orElse(Collections.emptyList()).forEach(row -> { + CldsDictionaryItem dictionaryItem = new CldsDictionaryItem(); + dictionaryItem.setDictElementId((String) row.get("dict_element_id")); + dictionaryItem.setDictionaryId((String) row.get("dictionary_id")); + dictionaryItem.setDictElementName((String) row.get("dict_element_name")); + dictionaryItem.setDictElementShortName((String) row.get("dict_element_short_name")); + dictionaryItem.setDictElementDesc((String) row.get("dict_element_description")); + dictionaryItem.setDictElementType((String) row.get("dict_element_type")); + dictionaryItem.setCreatedBy((String) row.get("created_by")); + dictionaryItem.setUpdatedBy((String) row.get("modified_by")); + dictionaryItem.setLastUpdatedDate(sdf.format(row.get("timestamp"))); + dictionaryItems.add(dictionaryItem); + }); + return dictionaryItems; + } } diff --git a/src/main/java/org/onap/clamp/clds/model/CldsDictionary.java b/src/main/java/org/onap/clamp/clds/model/CldsDictionary.java new file mode 100644 index 00000000..a9b003d4 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/model/CldsDictionary.java @@ -0,0 +1,164 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 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============================================ + * =================================================================== + * + */ + +package org.onap.clamp.clds.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.clamp.clds.dao.CldsDao; + +/** + * Represents a CLDS Dictionary. + */ +@JsonInclude(Include.NON_NULL) +public class CldsDictionary { + + private String dictionaryId; + private String dictionaryName; + private String createdBy; + private String updatedBy; + private String lastUpdatedDate; + private List cldsDictionaryItems = new ArrayList<>(); + + /** + * Creates or updates dictionary item for a dictionary in DB + * + * @param dictionaryName + * @param cldsDao + * @param userId + */ + public void save(String dictionaryName, CldsDao cldsDao, String userId) { + List list = cldsDao.getDictionary(this.getDictionaryId(), dictionaryName); + if (list != null && !list.isEmpty()) { + CldsDictionary cldsDictionary = list.stream().findFirst().get(); + if (!cldsDictionary.getDictionaryName().equalsIgnoreCase(this.getDictionaryName())) { + cldsDao.updateDictionary(cldsDictionary.getDictionaryId(), this, userId); + this.setCreatedBy(cldsDictionary.getCreatedBy()); + } else { + this.setDictionaryId(cldsDictionary.getDictionaryId()); + this.setCreatedBy(cldsDictionary.getCreatedBy()); + this.setUpdatedBy(cldsDictionary.getUpdatedBy()); + this.setLastUpdatedDate(cldsDictionary.getLastUpdatedDate()); + } + } else { + this.setCreatedBy(userId); + this.setUpdatedBy(userId); + cldsDao.insDictionary(this); + } + } + + /** + * @return the dictionaryId + */ + public String getDictionaryId() { + return dictionaryId; + } + + /** + * @param dictionaryId + * the dictionaryId to set + */ + public void setDictionaryId(String dictionaryId) { + this.dictionaryId = dictionaryId; + } + + /** + * @return the dictionaryName + */ + public String getDictionaryName() { + return dictionaryName; + } + + /** + * @param dictionaryName + * the dictionaryName to set + */ + public void setDictionaryName(String dictionaryName) { + this.dictionaryName = dictionaryName; + } + + /** + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } + + /** + * @param createdBy + * the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + /** + * @return the updatedBy + */ + public String getUpdatedBy() { + return updatedBy; + } + + /** + * @param updatedby + * the updatedBy to set + */ + public void setUpdatedBy(String updatedby) { + updatedBy = updatedby; + } + + /** + * @return the lastUpdatedDate + */ + public String getLastUpdatedDate() { + return lastUpdatedDate; + } + + /** + * @param lastUpdatedDate + * the lastUpdatedDate to set + */ + public void setLastUpdatedDate(String lastUpdatedDate) { + this.lastUpdatedDate = lastUpdatedDate; + } + + /** + * @return the cldsDictionaryItems + */ + public List getCldsDictionaryItems() { + return cldsDictionaryItems; + } + + /** + * @param cldsDictionaryItems + * the cldsDictionaryItems to set + */ + public void setCldsDictionaryItems(List cldsDictionaryItems) { + this.cldsDictionaryItems = cldsDictionaryItems; + } + +} diff --git a/src/main/java/org/onap/clamp/clds/model/CldsDictionaryItem.java b/src/main/java/org/onap/clamp/clds/model/CldsDictionaryItem.java new file mode 100644 index 00000000..87ba9fe8 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/model/CldsDictionaryItem.java @@ -0,0 +1,205 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 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============================================ + * =================================================================== + * + */ + +package org.onap.clamp.clds.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; + +import java.util.List; + +import org.onap.clamp.clds.dao.CldsDao; + +/** + * Represents a CLDS Dictionary Item. + */ +@JsonInclude(Include.NON_NULL) +public class CldsDictionaryItem { + + private String dictElementId; + private String dictionaryId; + private String dictElementName; + private String dictElementShortName; + private String dictElementDesc; + private String dictElementType; + private String createdBy; + private String updatedBy; + private String lastUpdatedDate; + + public void save(String dictionaryName, CldsDao cldsDao, String userId) { + // Check if dictionary exists. + List list = cldsDao.getDictionary(this.getDictionaryId(), dictionaryName); + if (list != null && !list.isEmpty()) { + // Dictionary found. We can add or update the dictionary element + CldsDictionary cldsDictionary = list.stream().findFirst().get(); + List dictionaryItems = cldsDao.getDictionaryElements(dictionaryName, + cldsDictionary.getDictionaryId(), this.getDictElementShortName()); + if (dictionaryItems != null && !dictionaryItems.isEmpty()) { + CldsDictionaryItem item = dictionaryItems.stream().findFirst().get(); + cldsDao.updateDictionaryElements(item.getDictElementId(), this, userId); + this.setCreatedBy(item.getCreatedBy()); + + } else { + this.setCreatedBy(userId); + this.setUpdatedBy(userId); + cldsDao.insDictionarElements(this, userId); + } + } + } + + /** + * @return the dictElementId + */ + public String getDictElementId() { + return dictElementId; + } + + /** + * @param dictElementId + * the dictElementId to set + */ + public void setDictElementId(String dictElementId) { + this.dictElementId = dictElementId; + } + + /** + * @return the dictionaryId + */ + public String getDictionaryId() { + return dictionaryId; + } + + /** + * @param dictionaryId + * the dictionaryId to set + */ + public void setDictionaryId(String dictionaryId) { + this.dictionaryId = dictionaryId; + } + + /** + * @return the dictElementName + */ + public String getDictElementName() { + return dictElementName; + } + + /** + * @param dictElementName + * the dictElementName to set + */ + public void setDictElementName(String dictElementName) { + this.dictElementName = dictElementName; + } + + /** + * @return the dictElementShortName + */ + public String getDictElementShortName() { + return dictElementShortName; + } + + /** + * @param dictElementShortName + * the dictElementShortName to set + */ + public void setDictElementShortName(String dictElementShortName) { + this.dictElementShortName = dictElementShortName; + } + + /** + * @return the dictElementDesc + */ + public String getDictElementDesc() { + return dictElementDesc; + } + + /** + * @param dictElementDesc + * the dictElementDesc to set + */ + public void setDictElementDesc(String dictElementDesc) { + this.dictElementDesc = dictElementDesc; + } + + /** + * @return the dictElementType + */ + public String getDictElementType() { + return dictElementType; + } + + /** + * @param dictElementType + * the dictElementType to set + */ + public void setDictElementType(String dictElementType) { + this.dictElementType = dictElementType; + } + + /** + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } + + /** + * @param createdBy + * the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + /** + * @return the updatedBy + */ + public String getUpdatedBy() { + return updatedBy; + } + + /** + * @param updatedby + * the updatedBy to set + */ + public void setUpdatedBy(String updatedby) { + updatedBy = updatedby; + } + + /** + * @return the lastUpdatedDate + */ + public String getLastUpdatedDate() { + return lastUpdatedDate; + } + + /** + * @param lastUpdatedDate + * the lastUpdatedDate to set + */ + public void setLastUpdatedDate(String lastUpdatedDate) { + this.lastUpdatedDate = lastUpdatedDate; + } + +} diff --git a/src/main/java/org/onap/clamp/clds/model/CldsEvent.java b/src/main/java/org/onap/clamp/clds/model/CldsEvent.java index 0867b962..8d3807b7 100644 --- a/src/main/java/org/onap/clamp/clds/model/CldsEvent.java +++ b/src/main/java/org/onap/clamp/clds/model/CldsEvent.java @@ -29,37 +29,38 @@ import org.onap.clamp.clds.dao.CldsDao; * Represent a CLDS Event. */ public class CldsEvent { - public static final String ACTION_TEST = "TEST"; - public static final String ACTION_CREATE = "CREATE"; - public static final String ACTION_MODIFY = "MODIFY"; - public static final String ACTION_SUBMIT = "SUBMIT"; + public static final String ACTION_TEST = "TEST"; + public static final String ACTION_CREATE = "CREATE"; + public static final String ACTION_MODIFY = "MODIFY"; + public static final String ACTION_SUBMIT = "SUBMIT"; // an update before model is active - public static final String ACTION_RESUBMIT = "RESUBMIT"; + public static final String ACTION_RESUBMIT = "RESUBMIT"; // For simplified models - public static final String ACTION_SUBMITDCAE = "SUBMITDCAE"; + public static final String ACTION_SUBMITDCAE = "SUBMITDCAE"; + public static final String ACTION_SUBMITPOLICY = "SUBMITPOLICY"; // only from dcae - public static final String ACTION_DISTRIBUTE = "DISTRIBUTE"; + public static final String ACTION_DISTRIBUTE = "DISTRIBUTE"; // only from dcae - public static final String ACTION_DEPLOY = "DEPLOY"; + public static final String ACTION_DEPLOY = "DEPLOY"; // only from dcae - public static final String ACTION_UNDEPLOY = "UNDEPLOY"; - public static final String ACTION_UPDATE = "UPDATE"; - public static final String ACTION_DELETE = "DELETE"; - public static final String ACTION_STOP = "STOP"; - public static final String ACTION_RESTART = "RESTART"; + public static final String ACTION_UNDEPLOY = "UNDEPLOY"; + public static final String ACTION_UPDATE = "UPDATE"; + public static final String ACTION_DELETE = "DELETE"; + public static final String ACTION_STOP = "STOP"; + public static final String ACTION_RESTART = "RESTART"; public static final String ACTION_STATE_INITIATED = "INITIATED"; - public static final String ACTION_STATE_SENT = "SENT"; + public static final String ACTION_STATE_SENT = "SENT"; public static final String ACTION_STATE_COMPLETED = "COMPLETED"; - public static final String ACTION_STATE_RECEIVED = "RECEIVED"; - public static final String ACTION_STATE_ERROR = "ERROR"; - public static final String ACTION_STATE_ANY = null; - - private String id; - private String actionCd; - private String actionStateCd; - private String processInstanceId; - private String userid; + public static final String ACTION_STATE_RECEIVED = "RECEIVED"; + public static final String ACTION_STATE_ERROR = "ERROR"; + public static final String ACTION_STATE_ANY = null; + + private String id; + private String actionCd; + private String actionStateCd; + private String processInstanceId; + private String userid; public String getId() { return id; diff --git a/src/main/java/org/onap/clamp/clds/model/CldsInfo.java b/src/main/java/org/onap/clamp/clds/model/CldsInfo.java index 382d4e89..a24885f7 100644 --- a/src/main/java/org/onap/clamp/clds/model/CldsInfo.java +++ b/src/main/java/org/onap/clamp/clds/model/CldsInfo.java @@ -25,12 +25,14 @@ package org.onap.clamp.clds.model; public class CldsInfo { - private String userName; - private String cldsVersion; + private String userName; + private String cldsVersion; private boolean permissionReadCl; private boolean permissionUpdateCl; private boolean permissionReadTemplate; private boolean permissionUpdateTemplate; + private boolean permissionReadTosca; + private boolean permissionUpdateTosca; public String getUserName() { return userName; @@ -80,4 +82,20 @@ public class CldsInfo { this.permissionUpdateTemplate = permissionUpdateTemplate; } + public boolean isPermissionReadTosca() { + return permissionReadTosca; + } + + public void setPermissionReadTosca(boolean permissionReadTosca) { + this.permissionReadTosca = permissionReadTosca; + } + + public boolean isPermissionUpdateTosca() { + return permissionUpdateTosca; + } + + public void setPermissionUpdateTosca(boolean permissionUpdateTosca) { + this.permissionUpdateTosca = permissionUpdateTosca; + } + } diff --git a/src/main/java/org/onap/clamp/clds/model/CldsModel.java b/src/main/java/org/onap/clamp/clds/model/CldsModel.java index 8b239956..55f4dfd6 100644 --- a/src/main/java/org/onap/clamp/clds/model/CldsModel.java +++ b/src/main/java/org/onap/clamp/clds/model/CldsModel.java @@ -139,7 +139,8 @@ public class CldsModel { } else if (event.isActionAndStateCd(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_STATE_RECEIVED) || event.isActionAndStateCd(CldsEvent.ACTION_RESTART, CldsEvent.ACTION_STATE_ANY) || event.isActionAndStateCd(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_STATE_ANY) - || event.isActionAndStateCd(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_STATE_ANY)) { + || event.isActionAndStateCd(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_STATE_ANY) + || event.isActionAndStateCd(CldsEvent.ACTION_SUBMITPOLICY, CldsEvent.ACTION_STATE_ANY)) { status = STATUS_ACTIVE; } else if (event.isActionAndStateCd(CldsEvent.ACTION_STOP, CldsEvent.ACTION_STATE_ANY)) { status = STATUS_STOPPED; @@ -185,14 +186,15 @@ public class CldsModel { permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMIT, CldsEvent.ACTION_TEST, CldsEvent.ACTION_DELETE); if (isSimplifiedModel()) { - permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_TEST, - CldsEvent.ACTION_DELETE); + permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_SUBMITPOLICY, + CldsEvent.ACTION_TEST, CldsEvent.ACTION_DELETE); } break; case CldsEvent.ACTION_MODIFY: permittedActionCd = Arrays.asList(CldsEvent.ACTION_RESUBMIT, CldsEvent.ACTION_DELETE); if (isSimplifiedModel()) { - permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_DELETE); + permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_SUBMITPOLICY, + CldsEvent.ACTION_DELETE); } break; case CldsEvent.ACTION_SUBMIT: @@ -202,6 +204,9 @@ public class CldsModel { case CldsEvent.ACTION_SUBMITDCAE: permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_DELETE); break; + case CldsEvent.ACTION_SUBMITPOLICY: + permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_STOP); + break; case CldsEvent.ACTION_DISTRIBUTE: permittedActionCd = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_RESUBMIT, CldsEvent.ACTION_DELETE); @@ -226,10 +231,17 @@ public class CldsModel { case CldsEvent.ACTION_UPDATE: permittedActionCd = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_STOP, CldsEvent.ACTION_UNDEPLOY); + if (isPolicyOnly()) { + permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_STOP); + } break; case CldsEvent.ACTION_STOP: permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_RESTART, CldsEvent.ACTION_UNDEPLOY); + if (isPolicyOnly()) { + permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_RESTART, + CldsEvent.ACTION_DELETE); + } break; default: logger.warn("Invalid current actionCd: " + actionCd); @@ -252,6 +264,22 @@ public class CldsModel { return result; } + private boolean isPolicyOnly() { + boolean result = false; + try { + if (propText != null) { + JsonNode modelJson = JacksonUtils.getObjectMapperInstance().readTree(propText); + JsonNode policyOnlyJson = modelJson.get("policyOnly"); + if (policyOnlyJson != null && policyOnlyJson.asBoolean()) { + result = true; + } + } + } catch (IOException e) { + logger.error("Error while parsing propText json", e); + } + return result; + } + /** * Validate requestedActionCd - determine permittedActionCd and then check * if contained in permittedActionCd Throw IllegalArgumentException if diff --git a/src/main/java/org/onap/clamp/clds/model/CldsToscaModel.java b/src/main/java/org/onap/clamp/clds/model/CldsToscaModel.java new file mode 100644 index 00000000..4a235252 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/model/CldsToscaModel.java @@ -0,0 +1,130 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 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============================================ + * =================================================================== + * + */ + +package org.onap.clamp.clds.model; + +import java.util.List; + +import org.onap.clamp.clds.dao.CldsDao; + +public class CldsToscaModel extends CldsToscaModelRevision { + + private String id; + private String policyType; + private String toscaModelName; + private String toscaModelYaml; + + /** + * Creates or updates Tosca Model to DB + * + * @param cldsDao + * @param userId + */ + public CldsToscaModel save(CldsDao cldsDao, String userId) { + CldsToscaModel cldsToscaModel = null; + // TODO tosca parsing logic + this.setToscaModelJson("{}"); + this.setPolicyType("Aging");// TODO update with subString or node_type from the model name + List toscaModels = cldsDao.getToscaModelByName(this.getToscaModelName()); + if (toscaModels != null && !toscaModels.isEmpty()) { + CldsToscaModel toscaModel = toscaModels.stream().findFirst().get(); + // CldsToscaModelRevision modelRevision = + // revisions.stream().max(Comparator.comparingDouble(CldsToscaModelRevision::getVersion)).get(); + this.setVersion(incrementVersion(toscaModel.getVersion())); + this.setId(toscaModel.getId()); + this.setUserId(userId); + cldsToscaModel = cldsDao.updateToscaModelWithNewVersion(this, userId); + } else { + this.setVersion(1); + cldsToscaModel = cldsDao.insToscaModel(this, userId); + } + return cldsToscaModel; + } + + private double incrementVersion(double curVersion) { + return curVersion + 1; + } + + /** + * @return the id + */ + public String getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(String id) { + this.id = id; + } + + /** + * @return the policyType + */ + public String getPolicyType() { + return policyType; + } + + /** + * @param policyType + * the policyType to set + */ + public void setPolicyType(String policyType) { + this.policyType = policyType; + } + + /** + * @return the toscaModelName + */ + public String getToscaModelName() { + return toscaModelName; + } + + /** + * @param toscaModelName + * the toscaModelName to set + */ + public void setToscaModelName(String toscaModelName) { + this.toscaModelName = toscaModelName; + } + + /** + * @return the toscaModelYaml + */ + @Override + public String getToscaModelYaml() { + return toscaModelYaml; + } + + /** + * @param toscaModelYaml + * the toscaModelYaml to set + */ + @Override + public void setToscaModelYaml(String toscaModelYaml) { + this.toscaModelYaml = toscaModelYaml; + } + +} diff --git a/src/main/java/org/onap/clamp/clds/model/CldsToscaModelDetails.java b/src/main/java/org/onap/clamp/clds/model/CldsToscaModelDetails.java new file mode 100644 index 00000000..5c6f4aa5 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/model/CldsToscaModelDetails.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 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============================================ + * =================================================================== + * + */ + +package org.onap.clamp.clds.model; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents a CLDS Tosca model + * + */ +public class CldsToscaModelDetails { + + private String id; + private String toscaModelName; + private String policyType; + private List toscaModelRevisions = new ArrayList<>(); + private String userId; + private String lastUpdatedDate; + + /** + * @return the id + */ + public String getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(String id) { + this.id = id; + } + + /** + * @return the toscaModelName + */ + public String getToscaModelName() { + return toscaModelName; + } + + /** + * @param toscaModelName + * the toscaModelName to set + */ + public void setToscaModelName(String toscaModelName) { + this.toscaModelName = toscaModelName; + } + + /** + * @return the policyType + */ + public String getPolicyType() { + return policyType; + } + + /** + * @param policyType + * the policyType to set + */ + public void setPolicyType(String policyType) { + this.policyType = policyType; + } + + /** + * @return the toscaModelRevisions + */ + public List getToscaModelRevisions() { + return toscaModelRevisions; + } + + /** + * @param toscaModelRevisions + * the toscaModelRevisions to set + */ + public void setToscaModelRevisions(List toscaModelRevisions) { + this.toscaModelRevisions = toscaModelRevisions; + } + + /** + * @return the userId + */ + public String getUserId() { + return userId; + } + + /** + * @param userId + * the userId to set + */ + public void setUserId(String userId) { + this.userId = userId; + } + + /** + * @return the lastUpdatedDate + */ + public String getLastUpdatedDate() { + return lastUpdatedDate; + } + + /** + * @param lastUpdatedDate + * the lastUpdatedDate to set + */ + public void setLastUpdatedDate(String lastUpdatedDate) { + this.lastUpdatedDate = lastUpdatedDate; + } + +} diff --git a/src/main/java/org/onap/clamp/clds/model/CldsToscaModelRevision.java b/src/main/java/org/onap/clamp/clds/model/CldsToscaModelRevision.java new file mode 100644 index 00000000..bfb0536e --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/model/CldsToscaModelRevision.java @@ -0,0 +1,144 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 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============================================ + * =================================================================== + * + */ + +/** + * Represents a CLDS Tosca model revision + * + */ +package org.onap.clamp.clds.model; + +public class CldsToscaModelRevision { + + private String revisionId; + private String toscaModelYaml; + private double version; + private String toscaModelJson; + private String userId; + private String createdDate; + private String lastUpdatedDate; + + /** + * @return the revisionId + */ + public String getRevisionId() { + return revisionId; + } + + /** + * @param revisionId + * the revisionId to set + */ + public void setRevisionId(String revisionId) { + this.revisionId = revisionId; + } + + /** + * @return the toscaModelYaml + */ + public String getToscaModelYaml() { + return toscaModelYaml; + } + + /** + * @param toscaModelYaml + * the toscaModelYaml to set + */ + public void setToscaModelYaml(String toscaModelYaml) { + this.toscaModelYaml = toscaModelYaml; + } + + /** + * @return the version + */ + public double getVersion() { + return version; + } + + /** + * @param version + * the version to set + */ + public void setVersion(double version) { + this.version = version; + } + + /** + * @return the toscaModelJson + */ + public String getToscaModelJson() { + return toscaModelJson; + } + + /** + * @param toscaModelJson + * the toscaModelJson to set + */ + public void setToscaModelJson(String toscaModelJson) { + this.toscaModelJson = toscaModelJson; + } + + /** + * @return the userId + */ + public String getUserId() { + return userId; + } + + /** + * @param userId + * the userId to set + */ + public void setUserId(String userId) { + this.userId = userId; + } + + /** + * @return the createdDate + */ + public String getCreatedDate() { + return createdDate; + } + + /** + * @param createdDate + * the createdDate to set + */ + public void setCreatedDate(String createdDate) { + this.createdDate = createdDate; + } + + /** + * @return the lastUpdatedDate + */ + public String getLastUpdatedDate() { + return lastUpdatedDate; + } + + /** + * @param lastUpdatedDate + * the lastUpdatedDate to set + */ + public void setLastUpdatedDate(String lastUpdatedDate) { + this.lastUpdatedDate = lastUpdatedDate; + } +} diff --git a/src/main/java/org/onap/clamp/clds/model/properties/PolicyItem.java b/src/main/java/org/onap/clamp/clds/model/properties/PolicyItem.java index 6e3e8659..7caba41f 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/PolicyItem.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/PolicyItem.java @@ -66,6 +66,7 @@ public class PolicyItem implements Cloneable { private String targetResourceId; private String recipeInfo; private String recipeLevel; + private String recipeInput; private Map recipePayload; private String oapRop; private String oapLimit; @@ -76,7 +77,7 @@ public class PolicyItem implements Cloneable { * @param node * @throws IOException */ - public PolicyItem(JsonNode node) throws IOException { + public PolicyItem(JsonNode node) throws IOException { id = AbstractModelElement.getValueByName(node, "_id"); recipe = AbstractModelElement.getValueByName(node, "recipe"); maxRetries = AbstractModelElement.getIntValueByName(node, "maxRetries"); @@ -89,11 +90,10 @@ public class PolicyItem implements Cloneable { } recipeInfo = AbstractModelElement.getValueByName(node, "recipeInfo"); recipeLevel = AbstractModelElement.getValueByName(node, "recipeLevel"); - String payload = AbstractModelElement.getValueByName(node, "recipeInput"); - + recipeInput = AbstractModelElement.getValueByName(node, "recipeInput"); + String payload = AbstractModelElement.getValueByName(node, "recipePayload"); if (payload != null && !payload.isEmpty()) { - //recipePayload = JacksonUtils.getObjectMapperInstance().convertValue(payload, Map.class); recipePayload = JacksonUtils.getObjectMapperInstance().readValue(payload, new TypeReference>(){}); } oapRop = AbstractModelElement.getValueByName(node, "oapRop"); @@ -215,6 +215,10 @@ public class PolicyItem implements Cloneable { return recipeLevel; } + public String getRecipeInput() { + return recipeInput; + } + public Map getRecipePayload() { return recipePayload; } diff --git a/src/main/java/org/onap/clamp/clds/service/CldsDictionaryService.java b/src/main/java/org/onap/clamp/clds/service/CldsDictionaryService.java new file mode 100644 index 00000000..5d5e218a --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/service/CldsDictionaryService.java @@ -0,0 +1,149 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 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============================================ + * =================================================================== + * + */ + +package org.onap.clamp.clds.service; + +import java.util.Date; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.onap.clamp.clds.dao.CldsDao; +import org.onap.clamp.clds.model.CldsDictionary; +import org.onap.clamp.clds.model.CldsDictionaryItem; +import org.onap.clamp.clds.util.LoggingUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +/** + * REST services to manage dictionary and dictionary items for Tosca Model + */ +@Component +public class CldsDictionaryService extends SecureServiceBase { + + @Value("${clamp.config.security.permission.type.tosca:permission-type-tosca}") + private String cldsPermissionTypeTosca; + @Value("${clamp.config.security.permission.instance:dev}") + private String cldsPermissionInstance; + private SecureServicePermission permissionReadTosca; + private SecureServicePermission permissionUpdateTosca; + + @Autowired + private CldsDao cldsDao; + + @PostConstruct + private final void initConstruct() { + permissionReadTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, "read"); + permissionUpdateTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, "update"); + } + + /** + * REST Service that creates or Updates a Dictionary + * + * @param dictionaryName + * @param cldsDictionary + * @return CldsDictionary that was created in DB. + */ + public ResponseEntity createOrUpdateDictionary(String dictionaryName, + CldsDictionary cldsDictionary) { + Date startTime = new Date(); + LoggingUtils.setRequestContext("CldsDictionaryService: createOrUpdateDictionary", getPrincipalName()); + // TODO revisit based on new permissions + isAuthorized(permissionUpdateTosca); + if (cldsDictionary == null) { + cldsDictionary = new CldsDictionary(); + cldsDictionary.setDictionaryName(dictionaryName); + } + cldsDictionary.save(dictionaryName, cldsDao, getUserId()); + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", "createOrUpdateDictionary success", this.getClass().getName()); + auditLogger.info("createOrUpdateDictionary completed"); + return new ResponseEntity<>(cldsDictionary, HttpStatus.OK); + } + + /** + * REST Service that creates or Updates a Dictionary Elements for dictionary in DB + * + * @param dictionaryName + * @param dictionaryItem + * @return CldsDictionaryItem + * A dictionary items that was created or updated in DB + */ + public ResponseEntity createOrUpdateDictionaryElements(String dictionaryName, + CldsDictionaryItem dictionaryItem) { + Date startTime = new Date(); + LoggingUtils.setRequestContext("CldsDictionaryService: createOrUpdateDictionaryElements", getPrincipalName()); + // TODO revisit based on new permissions + isAuthorized(permissionUpdateTosca); + dictionaryItem.save(dictionaryName, cldsDao, getUserId()); + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", "createOrUpdateDictionaryElements success", this.getClass().getName()); + auditLogger.info("createOrUpdateDictionaryElements completed"); + return new ResponseEntity<>(dictionaryItem, HttpStatus.OK); + } + + /** + * Rest Service that retrieves all CLDS dictionary in DB + * + * @return CldsDictionary List + * List of CldsDictionary available in DB + */ + public ResponseEntity> getAllDictionaryNames() { + Date startTime = new Date(); + LoggingUtils.setRequestContext("CldsDictionaryService: getAllDictionaryNames", getPrincipalName()); + // TODO revisit based on new permissions + isAuthorized(permissionReadTosca); + List dictionaries = cldsDao.getDictionary(null, null); + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", "getAllDictionaryNames success", this.getClass().getName()); + auditLogger.info("getAllDictionaryNames completed"); + return new ResponseEntity<>(dictionaries, HttpStatus.OK); + } + + /** + * Rest Service that retrieves all CLDS dictionary items in DB for a give dictionary name + * + * @param dictionaryName + * @return CldsDictionaryItem list + * List of CLDS Dictionary items for a given dictionary name + */ + public ResponseEntity> getDictionaryElementsByName(String dictionaryName) { + Date startTime = new Date(); + LoggingUtils.setRequestContext("CldsDictionaryService: getDictionaryElementsByName", getPrincipalName()); + // TODO revisit based on new permissions + isAuthorized(permissionReadTosca); + List dictionaryItems = cldsDao.getDictionaryElements(dictionaryName, null, null); + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", "getAllDictionaryNames success", this.getClass().getName()); + auditLogger.info("getAllDictionaryNames completed"); + return new ResponseEntity<>(dictionaryItems, HttpStatus.OK); + } + + public ResponseEntity deleteDictionary() { + return null; + } + +} diff --git a/src/main/java/org/onap/clamp/clds/service/CldsInfoProvider.java b/src/main/java/org/onap/clamp/clds/service/CldsInfoProvider.java index 6bebde92..7027cf1b 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsInfoProvider.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsInfoProvider.java @@ -45,6 +45,8 @@ class CldsInfoProvider { cldsInfo.setPermissionUpdateCl(cldsService.isAuthorizedNoException(cldsService.permissionUpdateCl)); cldsInfo.setPermissionReadTemplate(cldsService.isAuthorizedNoException(cldsService.permissionReadTemplate)); cldsInfo.setPermissionUpdateTemplate(cldsService.isAuthorizedNoException(cldsService.permissionUpdateTemplate)); + cldsInfo.setPermissionReadTosca(cldsService.isAuthorizedNoException(cldsService.permissionReadTosca)); + cldsInfo.setPermissionUpdateTosca(cldsService.isAuthorizedNoException(cldsService.permissionUpdateTosca)); return cldsInfo; } } diff --git a/src/main/java/org/onap/clamp/clds/service/CldsService.java b/src/main/java/org/onap/clamp/clds/service/CldsService.java index bc58ee69..521f3ce2 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -105,6 +105,8 @@ public class CldsService extends SecureServiceBase { final SecureServicePermission permissionUpdateCl; final SecureServicePermission permissionReadTemplate; final SecureServicePermission permissionUpdateTemplate; + final SecureServicePermission permissionReadTosca; + final SecureServicePermission permissionUpdateTosca; private final CldsDao cldsDao; private final XslTransformer cldsBpmnTransformer; @@ -125,6 +127,7 @@ public class CldsService extends SecureServiceBase { @Value("${clamp.config.security.permission.type.cl.event:permission-type-cl-event}") String cldsPermissionTypeClEvent, @Value("${clamp.config.security.permission.type.filter.vf:permission-type-filter-vf}") String cldsPermissionTypeFilterVf, @Value("${clamp.config.security.permission.type.template:permission-type-template}") String cldsPermissionTypeTemplate, + @Value("${clamp.config.security.permission.type.tosca:permission-type-tosca}") String cldsPermissionTypeTosca, @Value("${clamp.config.security.permission.instance:dev}") String cldsPermissionInstance) { this.cldsDao = cldsDao; this.cldsBpmnTransformer = cldsBpmnTransformer; @@ -144,6 +147,9 @@ public class CldsService extends SecureServiceBase { "read"); permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance, "update"); + permissionReadTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, "read"); + permissionUpdateTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, + "update"); } /* @@ -401,7 +407,7 @@ public class CldsService extends SecureServiceBase { retrievedModel = CldsModel.retrieve(cldsDao, modelName, false); } if (retrievedModel != null) { - if (!isTest && (actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMIT) + if (!isTest && !errorCase && (actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMIT) || actionCd.equalsIgnoreCase(CldsEvent.ACTION_RESUBMIT) || actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE))) { if (retrievedModel.getTemplateName().startsWith(CsarInstallerImpl.TEMPLATE_NAME_PREFIX)) { diff --git a/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java b/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java new file mode 100644 index 00000000..f33039f0 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java @@ -0,0 +1,149 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 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============================================ + * =================================================================== + * + */ + +package org.onap.clamp.clds.service; + +import java.util.Date; +import java.util.List; +import java.util.Optional; + +import javax.annotation.PostConstruct; + +import org.onap.clamp.clds.dao.CldsDao; +import org.onap.clamp.clds.model.CldsToscaModel; +import org.onap.clamp.clds.util.LoggingUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +/** + * REST services to manage Tosca Model + */ +@Component +public class CldsToscaService extends SecureServiceBase { + + @Value("${clamp.config.security.permission.type.tosca:permission-type-tosca}") + private String cldsPermissionTypeTosca; + @Value("${clamp.config.security.permission.instance:dev}") + private String cldsPermissionInstance; + private SecureServicePermission permissionReadTosca; + private SecureServicePermission permissionUpdateTosca; + + @Autowired + private CldsDao cldsDao; + + @PostConstruct + private final void initConstruct() { + permissionReadTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, "read"); + permissionUpdateTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, "update"); + } + + /** + * REST service to upload a new Tosca Model or update an existing Tosca model with new version. + * This API will parse the Tosca model yaml and generates a JSON schema out of it. + * + * @param toscaModelName + * Tosca model name to be used as a key + * @param cldsToscaModel + * Object containing the tosca model yaml + * + * @return clds tosca models - list of CLDS tosca models for a given policy type + */ + public ResponseEntity parseToscaModelAndSave(String toscaModelName, CldsToscaModel cldsToscaModel ) { + Date startTime = new Date(); + LoggingUtils.setRequestContext("CldsToscaService: Parse Tosca model and save", getPrincipalName()); + //TODO revisit based on new permissions + isAuthorized(permissionUpdateTosca); + cldsToscaModel.setToscaModelName(toscaModelName); + cldsToscaModel = cldsToscaModel.save(cldsDao, getUserId()); + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", "Parse Tosca model and save success", this.getClass().getName()); + auditLogger.info("Parse Tosca model and save completed"); + return new ResponseEntity<>(cldsToscaModel, HttpStatus.CREATED); + } + + /** + * REST service to retrieve all Tosca models from the CLDS database. + * + * @return clds tosca models - list of CLDS tosca models + */ + public ResponseEntity> getAllToscaModels() { + + Date startTime = new Date(); + LoggingUtils.setRequestContext("CldsToscaService: Get All tosca models", getPrincipalName()); + //TODO revisit based on new permissions + isAuthorized(permissionReadTosca); + List cldsToscaModels = Optional.ofNullable(cldsDao.getAllToscaModels()).get(); + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", "Get All tosca models success", this.getClass().getName()); + auditLogger.info("Get All tosca models"); + return new ResponseEntity<>(cldsToscaModels, HttpStatus.OK); + } + + /** + * REST service that retrieves a CLDS Tosca model by model name from the database. + * + * @param toscaModelName + * Path param with tosca model name + * + * @return clds tosca model - CLDS tosca model for a given tosca model name + */ + public ResponseEntity getToscaModel(String toscaModelName) { + Date startTime = new Date(); + LoggingUtils.setRequestContext("CldsToscaService: Get tosca models by model name", getPrincipalName()); + //TODO revisit based on new permissions + isAuthorized(permissionReadTosca); + List cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByName(toscaModelName)).get(); + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", "Get tosca models by model name success", this.getClass().getName()); + auditLogger.info("GET tosca models by model name completed"); + return new ResponseEntity<>(Optional.ofNullable(cldsToscaModels).get().stream().findFirst().get(), HttpStatus.OK); + } + + + /** + * REST service that retrieves a CLDS Tosca model lists for a policy type from the database. + * + * @param policyType + * @return clds tosca model - CLDS tosca model for a given policy type + */ + public ResponseEntity getToscaModelsByPolicyType(String policyType) { + Date startTime = new Date(); + LoggingUtils.setRequestContext("CldsToscaService: Get tosca models by policyType", getPrincipalName()); + //TODO revisit based on new permissions + isAuthorized(permissionReadTosca); + List cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByPolicyType(policyType)).get(); + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", "Get tosca models by policyType success", this.getClass().getName()); + auditLogger.info("GET tosca models by policyType completed"); + return new ResponseEntity<>(Optional.ofNullable(cldsToscaModels).get().stream().findFirst().get(), HttpStatus.OK); + } + + public ResponseEntity deleteToscaModelById(String toscaModeId) { + //TODO + return null; + } + +} diff --git a/src/main/java/org/onap/clamp/clds/util/ClampTimer.java b/src/main/java/org/onap/clamp/clds/util/ClampTimer.java deleted file mode 100644 index 794e2b48..00000000 --- a/src/main/java/org/onap/clamp/clds/util/ClampTimer.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 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============================================ - * =================================================================== - * - */ -package org.onap.clamp.clds.util; - -import java.util.Timer; -import java.util.TimerTask; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.springframework.security.core.context.SecurityContextHolder; - -/** - * Define the ClampTimer and CleanupTask, to clear up the Spring Authenticataion info when time is up. - */ - -public class ClampTimer { - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(ClampTimer.class); - Timer timer; - - public ClampTimer(int seconds) { - timer = new Timer(); - timer.schedule(new CleanupTask(), seconds*1000); - } - - class CleanupTask extends TimerTask { - public void run() { - logger.debug("Time is up, clear the Spring authenticataion settings"); - //Clear up the spring authentication - SecurityContextHolder.getContext().setAuthentication(null); - //Terminate the timer thread - timer.cancel(); - } - } -} \ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java index cdb2e29c..759edb1d 100644 --- a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java @@ -18,7 +18,7 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds.util; @@ -31,21 +31,21 @@ import java.net.InetAddress; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; -import java.util.UUID; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; -import javax.validation.constraints.NotNull; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; + import javax.servlet.http.HttpServletRequest; +import javax.validation.constraints.NotNull; +import org.onap.clamp.clds.service.DefaultUserNameHandler; import org.slf4j.MDC; import org.slf4j.event.Level; import org.springframework.security.core.context.SecurityContextHolder; -import org.onap.clamp.clds.service.DefaultUserNameHandler; - /** * This class handles the special info that appear in the log, like RequestID, * time context, ... @@ -66,7 +66,7 @@ public class LoggingUtils { * Constructor */ public LoggingUtils(final EELFLogger loggerP) { - this.mLogger = checkNotNull(loggerP); + this.mLogger = checkNotNull(loggerP); } /** @@ -86,7 +86,7 @@ public class LoggingUtils { MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress()); } catch (UnknownHostException e) { logger.error("Failed to initiate setRequestContext", e); - } + } } /** @@ -149,7 +149,7 @@ public class LoggingUtils { * @return A string with the request ID */ public static String getRequestId() { - String requestId = (String) MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); if (requestId == null || requestId.isEmpty()) { requestId = UUID.randomUUID().toString(); MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); @@ -162,9 +162,9 @@ public class LoggingUtils { dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat; } - - - + + + /********************************************************************************************* * Method for ONAP Application Logging Specification v1.2 ********************************************************************************************/ @@ -181,7 +181,7 @@ public class LoggingUtils { final String requestID = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.REQUEST_ID)); final String invocationID = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.INVOCATION_ID)); final String partnerName = defaultToEmpty(request.getHeader(ONAPLogConstants.Headers.PARTNER_NAME)); - + // Default the partner name to the user name used to login to clamp if (partnerName.equalsIgnoreCase(EMPTY_MESSAGE)) { MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, new DefaultUserNameHandler().retrieveUserName(SecurityContextHolder.getContext())); @@ -192,8 +192,8 @@ public class LoggingUtils { // depending on where you need them to appear, OR extend the // ServiceDescriptor to add them. MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, - ZonedDateTime.now(ZoneOffset.UTC) - .format(DateTimeFormatter.ISO_INSTANT)); + ZonedDateTime.now(ZoneOffset.UTC) + .format(DateTimeFormatter.ISO_INSTANT)); MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestID); MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationID); MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr())); @@ -203,7 +203,7 @@ public class LoggingUtils { // Default the service name to the requestURI, in the event that // no value has been provided. if (serviceName == null || - serviceName.equalsIgnoreCase(EMPTY_MESSAGE)) { + serviceName.equalsIgnoreCase(EMPTY_MESSAGE)) { MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI()); } @@ -217,7 +217,7 @@ public class LoggingUtils { */ public void exiting(String code, String descrption, Level severity, ONAPLogConstants.ResponseStatus status) { try { - MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, defaultToEmpty(code)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, defaultToEmpty(code)); MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption)); MDC.put(ONAPLogConstants.MDCs.RESPONSE_SEVERITY, defaultToEmpty(severity)); MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, defaultToEmpty(status)); @@ -241,11 +241,11 @@ public class LoggingUtils { // Set standard HTTP headers on (southbound request) builder. con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID, - defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID))); + defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID))); con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID, - invocationID); + invocationID); con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME, - defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME))); + defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME))); invokeContext(targetEntity, targetServiceName, invocationID); @@ -314,8 +314,8 @@ public class LoggingUtils { MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName)); MDC.put(ONAPLogConstants.MDCs.INVOCATIONID_OUT, invocationID); MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, - ZonedDateTime.now(ZoneOffset.UTC) - .format(DateTimeFormatter.ISO_INSTANT)); + ZonedDateTime.now(ZoneOffset.UTC) + .format(DateTimeFormatter.ISO_INSTANT)); } /** diff --git a/src/main/resources/META-INF/resources/designer/partials/portfolios/extra_user_info.html b/src/main/resources/META-INF/resources/designer/partials/portfolios/extra_user_info.html index bf151d7f..c66047cc 100644 --- a/src/main/resources/META-INF/resources/designer/partials/portfolios/extra_user_info.html +++ b/src/main/resources/META-INF/resources/designer/partials/portfolios/extra_user_info.html @@ -38,7 +38,10 @@ User Permissions:
Read Template
Read Model
+
Read Tosca
Edit Model
+
Edit Template
+
Edit Tosca