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;
DELIMITER //
CREATE PROCEDURE get_template
(IN v_template_name VARCHAR(80),
UPDATE event
SET process_instance_id = v_process_instance_id
WHERE event_id = v_event_id;
+END;
+CREATE PROCEDURE del_model (IN v_model_name VARCHAR(80))
+BEGIN
+ DECLARE v_model_id VARCHAR(36);
+ SELECT model_id INTO v_model_id from model where model_name = v_model_name;
+ UPDATE model set event_id = null, model_blueprint_id = null, model_prop_id = null where model_id = v_model_id;
+ DELETE from event where model_id = v_model_id;
+ DELETE from model_blueprint where model_id = v_model_id;
+ DELETE from model_properties where model_id = v_model_id;
+ DELETE from model where model_id = v_model_id;
END
//
DELIMITER ;
<modelVersion>4.0.0</modelVersion>
<groupId>org.onap.clamp</groupId>
<artifactId>clds</artifactId>
- <version>2.0.2-SNAPSHOT</version>
+ <version>3.0.0-SNAPSHOT</version>
<name>clamp</name>
<parent>
<docker.skip.tag>true</docker.skip.tag>
<skip.staging.artifacts>false</skip.staging.artifacts>
<python.http.proxy.param></python.http.proxy.param>
+ <tomcat.version>8.5.28</tomcat.version>
</properties>
<distributionManagement>
<artifactId>eelf-core</artifactId>
<version>${eelf.core.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.apache.tomcat.embed</groupId>
+ <artifactId>tomcat-embed-core</artifactId>
+ <version>${tomcat.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.tomcat.embed</groupId>
+ <artifactId>tomcat-embed-el</artifactId>
+ <version>${tomcat.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.tomcat.embed</groupId>
+ <artifactId>tomcat-embed-websocket</artifactId>
+ <version>${tomcat.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.tomcat</groupId>
+ <artifactId>tomcat-annotations-api</artifactId>
+ <version>${tomcat.version}</version>
+ </dependency>
<!-- For CAMEL -->
<dependency>
<groupId>org.apache.camel</groupId>
<goal>build</goal>
</goals>
<configuration>
- <image>onap/clamp</image>
+ <images>
+ <image>
+ <alias>onap-clamp</alias>
+ </image>
+ </images>
</configuration>
</execution>
<execution>
<goal>push</goal>
</goals>
<configuration>
- <image>onap/clamp</image>
+ <images>
+ <image>
+ <alias>onap-clamp</alias>
+ </image>
+ </images>
</configuration>
</execution>
<execution>
</goals>
<configuration>
<skip>${skipITs}</skip>
+ <images>
+ <image>
+ <alias>mariadb</alias>
+ </image>
+ <image>
+ <alias>python</alias>
+ </image>
+ </images>
</configuration>
</execution>
<execution>
</goals>
<configuration>
<skip>${skipITs}</skip>
+ <images>
+ <image>
+ <alias>mariadb</alias>
+ </image>
+ <image>
+ <alias>python</alias>
+ </image>
+ </images>
</configuration>
</execution>
</executions>
* The user ID coming from the UI
* @param isInsertTestEvent
* Is a test or not (flag coming from the UI)
+ * @param eventAction
+ * The latest event action in database (like CREATE, SUBMIT, ...)
* @return A string containing the result of the Camel flow execution
*/
String submit(@ExchangeProperty("actionCd") String actionCommand,
@ExchangeProperty("modelBpmnProp") String modelBpmnProperties,
@ExchangeProperty("modelName") String modelName, @ExchangeProperty("controlName") String controlName,
@ExchangeProperty("docText") String docText, @ExchangeProperty("isTest") boolean isTest,
- @ExchangeProperty("userid") String userId,
- @ExchangeProperty("isInsertTestEvent") boolean isInsertTestEvent);
+ @ExchangeProperty("userid") String userId, @ExchangeProperty("isInsertTestEvent") boolean isInsertTestEvent,
+ @ExchangeProperty("eventAction") String eventAction);
}
import com.fasterxml.jackson.databind.JsonNode;\r
import com.fasterxml.jackson.databind.node.ObjectNode;\r
\r
+import java.io.IOException;\r
import java.util.Date;\r
\r
import org.json.simple.JSONObject;\r
import org.json.simple.parser.JSONParser;\r
+import org.json.simple.parser.ParseException;\r
import org.onap.clamp.clds.config.ClampProperties;\r
import org.onap.clamp.clds.exception.dcae.DcaeDeploymentException;\r
import org.onap.clamp.clds.util.LoggingUtils;\r
private static final String STATUS_URL_LOG = "Status URL extracted: ";\r
private static final String DCAE_URL_PREFIX = "/dcae-deployments/";\r
private static final String DCAE_URL_PROPERTY_NAME = "dcae.dispatcher.url";\r
- private static final String DCAE_REQUEST_FAILED_LOG = "RequestFailed - responseStr=";\r
public static final String DCAE_REQUESTID_PROPERTY_NAME = "dcae.header.requestId";\r
private static final String DCAE_LINK_FIELD = "links";\r
private static final String DCAE_STATUS_FIELD = "status";\r
LoggingUtils.setTargetContext("DCAE", "deleteDeployment");\r
try {\r
String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;\r
- String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "DELETE", null, null);\r
- JSONParser parser = new JSONParser();\r
- Object obj0 = parser.parse(responseStr);\r
- JSONObject jsonObj = (JSONObject) obj0;\r
- JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD);\r
- String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD);\r
+ String statusUrl = getDcaeResponse(url, "DELETE", null, null, DCAE_LINK_FIELD, DCAE_STATUS_FIELD);\r
logger.info(STATUS_URL_LOG + statusUrl);\r
LoggingUtils.setResponseContext("0", "Delete deployments success", this.getClass().getName());\r
return statusUrl;\r
} catch (Exception e) {\r
- // Log StatusCode during exception in metrics log\r
LoggingUtils.setResponseContext("900", "Delete deployments failed", this.getClass().getName());\r
LoggingUtils.setErrorContext("900", "Delete deployments error");\r
logger.error("Exception occurred during Delete Deployment Operation with DCAE", e);\r
LoggingUtils.setTargetContext("DCAE", "getOperationStatus");\r
try {\r
String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(statusUrl, "GET", null, null);\r
- JSONParser parser = new JSONParser();\r
- Object obj0 = parser.parse(responseStr);\r
- JSONObject jsonObj = (JSONObject) obj0;\r
+ JSONObject jsonObj = parseResponse(responseStr);\r
String operationType = (String) jsonObj.get("operationType");\r
- String status = (String) jsonObj.get("status");\r
+ String status = (String) jsonObj.get(DCAE_STATUS_FIELD);\r
logger.info("Operation Type - " + operationType + ", Status " + status);\r
LoggingUtils.setResponseContext("0", "Get operation status success", this.getClass().getName());\r
opStatus = status;\r
} catch (Exception e) {\r
- // Log StatusCode during exception in metrics log\r
LoggingUtils.setResponseContext("900", "Get operation status failed", this.getClass().getName());\r
LoggingUtils.setErrorContext("900", "Get operation status error");\r
logger.error("Exception occurred during getOperationStatus Operation with DCAE", e);\r
DcaeHttpConnectionManager.doDcaeHttpQuery(url, "GET", null, null);\r
LoggingUtils.setResponseContext("0", "Get deployments success", this.getClass().getName());\r
} catch (Exception e) {\r
- // Log StatusCode during exception in metrics log\r
LoggingUtils.setResponseContext("900", "Get deployments failed", this.getClass().getName());\r
LoggingUtils.setErrorContext("900", "Get deployments error");\r
logger.error("Exception occurred during getDeployments Operation with DCAE", e);\r
ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("dcae.deployment.template");\r
rootNode.put("serviceTypeId", serviceTypeId);\r
if (blueprintInputJson != null) {\r
- rootNode.put("inputs", blueprintInputJson);\r
+ rootNode.set("inputs", blueprintInputJson);\r
}\r
String apiBodyString = rootNode.toString();\r
logger.info("Dcae api Body String - " + apiBodyString);\r
String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;\r
- String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "PUT", apiBodyString,\r
- "application/json");\r
- JSONParser parser = new JSONParser();\r
- Object obj0 = parser.parse(responseStr);\r
- JSONObject jsonObj = (JSONObject) obj0;\r
- JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD);\r
- String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD);\r
- logger.info(STATUS_URL_LOG + statusUrl);\r
+ String statusUrl = getDcaeResponse(url, "PUT", apiBodyString, "application/json", DCAE_LINK_FIELD,\r
+ DCAE_STATUS_FIELD);\r
LoggingUtils.setResponseContext("0", "Create new deployment failed", this.getClass().getName());\r
return statusUrl;\r
} catch (Exception e) {\r
- // Log StatusCode during exception in metrics log\r
LoggingUtils.setResponseContext("900", "Create new deployment failed", this.getClass().getName());\r
LoggingUtils.setErrorContext("900", "Create new deployment error");\r
logger.error("Exception occurred during createNewDeployment Operation with DCAE", e);\r
}\r
}\r
\r
- /**\r
+ /***\r
* Returns status URL for deleteExistingDeployment operation.\r
* \r
* @param deploymentId\r
String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";\r
logger.info("Dcae api Body String - " + apiBodyString);\r
String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;\r
- String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "DELETE", apiBodyString,\r
- "application/json");\r
- JSONParser parser = new JSONParser();\r
- Object obj0 = parser.parse(responseStr);\r
- JSONObject jsonObj = (JSONObject) obj0;\r
- JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD);\r
- String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD);\r
- logger.info(STATUS_URL_LOG + statusUrl);\r
+ String statusUrl = getDcaeResponse(url, "DELETE", apiBodyString, "application/json", DCAE_LINK_FIELD,\r
+ DCAE_STATUS_FIELD);\r
LoggingUtils.setResponseContext("0", "Delete existing deployment success", this.getClass().getName());\r
return statusUrl;\r
+\r
} catch (Exception e) {\r
- // Log StatusCode during exception in metrics log\r
LoggingUtils.setResponseContext("900", "Delete existing deployment failed", this.getClass().getName());\r
LoggingUtils.setErrorContext("900", "Delete existing deployment error");\r
logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e);\r
metricsLogger.info("deleteExistingDeployment complete");\r
}\r
}\r
+\r
+ private String getDcaeResponse(String url, String requestMethod, String payload, String contentType, String node,\r
+ String nodeAttr) throws IOException, ParseException {\r
+ Date startTime = new Date();\r
+ try {\r
+ String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, requestMethod, payload, contentType);\r
+ JSONObject jsonObj = parseResponse(responseStr);\r
+ JSONObject linksObj = (JSONObject) jsonObj.get(node);\r
+ String statusUrl = (String) linksObj.get(nodeAttr);\r
+ logger.info(STATUS_URL_LOG + statusUrl);\r
+ return statusUrl;\r
+ } catch (IOException | ParseException e) {\r
+ logger.error("Exception occurred getting response from DCAE", e);\r
+ throw e;\r
+ } finally {\r
+ LoggingUtils.setTimeContext(startTime, new Date());\r
+ metricsLogger.info("getDcaeResponse complete");\r
+ }\r
+ }\r
+\r
+ private JSONObject parseResponse(String responseStr) throws ParseException {\r
+ JSONParser parser = new JSONParser();\r
+ Object obj0 = parser.parse(responseStr);\r
+ JSONObject jsonObj = (JSONObject) obj0;\r
+ return jsonObj;\r
+ }\r
}
\ No newline at end of file
if (dcaeResponse != null) {\r
logger.info("Dcae Response for query on inventory: " + dcaeResponse);\r
String oldTypeId = cldsModel.getTypeId();\r
- String newTypeId = "";\r
if (dcaeResponse.getTypeId() != null) {\r
- newTypeId = dcaeResponse.getTypeId();\r
cldsModel.setTypeId(dcaeResponse.getTypeId());\r
}\r
if (dcaeResponse.getTypeName() != null) {\r
cldsModel.setTypeName(dcaeResponse.getTypeName());\r
}\r
- if (oldTypeId == null || !oldTypeId.equalsIgnoreCase(newTypeId)\r
+ if (oldTypeId == null || !cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_DISTRIBUTE)\r
|| cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE)) {\r
CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userId, dcaeEvent.getCldsActionCd(),\r
CldsEvent.ACTION_STATE_RECEIVED, null);\r
}\r
return typeId;\r
}\r
+\r
+ /**\r
+ * Method to delete blueprint from dcae inventory if it's exists.\r
+ * \r
+ * @param typeName\r
+ * @param serviceUuid\r
+ * @param resourceUuid\r
+ * @throws InterruptedException\r
+ */\r
+ public void deleteDCAEServiceType(String typeName, String serviceUuid, String resourceUuid)\r
+ throws InterruptedException {\r
+ Date startTime = new Date();\r
+ LoggingUtils.setTargetContext("DCAE", "deleteDCAEServiceType");\r
+ boolean result = false;\r
+ try {\r
+ DcaeInventoryResponse inventoryResponse = getDcaeInformation(typeName, serviceUuid, resourceUuid);\r
+ if (inventoryResponse != null && inventoryResponse.getTypeId() != null) {\r
+ String fullUrl = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types/"\r
+ + inventoryResponse.getTypeId();\r
+ DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "DELETE", null, null);\r
+ }\r
+ result = true;\r
+ } catch (IOException | ParseException e) {\r
+ logger.error("Exception occurred during deleteDCAEServiceType Operation with DCAE", e);\r
+ throw new BadRequestException("Exception occurred during deleteDCAEServiceType Operation with DCAE", e);\r
+ } finally {\r
+ if (result) {\r
+ LoggingUtils.setResponseContext("0", "Delete DCAE ServiceType success", this.getClass().getName());\r
+ } else {\r
+ LoggingUtils.setResponseContext("900", "Delete DCAE ServiceType failed", this.getClass().getName());\r
+ LoggingUtils.setErrorContext("900", "Delete DCAE ServiceType error");\r
+ }\r
+ LoggingUtils.setTimeContext(startTime, new Date());\r
+ metricsLogger.info("deleteDCAEServiceType completed");\r
+ }\r
+ }\r
}\r
--- /dev/null
+/*-
+ * ============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.client;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Handler;
+import org.onap.clamp.clds.dao.CldsDao;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * Delete model.
+ */
+@Component
+public class ModelDeleteDelegate {
+
+ protected static final EELFLogger logger = EELFManager.getInstance().getLogger(ModelDeleteDelegate.class);
+ protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
+ @Autowired
+ private CldsDao cldsDao;
+
+ /**
+ * Insert event using process variables.
+ *
+ * @param camelExchange
+ * The Camel Exchange object containing the properties
+ */
+ @Handler
+ public void execute(Exchange camelExchange) {
+ String modelName = (String) camelExchange.getProperty("modelName");
+ cldsDao.deleteModel(modelName);
+ }
+}
import org.apache.camel.Exchange;
import org.apache.camel.Handler;
import org.onap.clamp.clds.client.req.policy.PolicyClient;
+import org.onap.clamp.clds.model.CldsEvent;
import org.onap.clamp.clds.model.properties.ModelProperties;
import org.onap.clamp.clds.model.properties.Policy;
import org.onap.clamp.clds.model.properties.PolicyChain;
ModelProperties prop = ModelProperties.create(camelExchange);
Policy policy = prop.getType(Policy.class);
prop.setCurrentModelElementId(policy.getId());
+ String eventAction = (String) camelExchange.getProperty("eventAction");
String responseMessage = "";
- if (policy.isFound()) {
+ if (!eventAction.equalsIgnoreCase(CldsEvent.ACTION_CREATE) && policy.isFound()) {
for (PolicyChain policyChain : policy.getPolicyChains()) {
prop.setPolicyUniqueId(policyChain.getPolicyId());
responseMessage = policyClient.deleteBrms(prop);
logger.info("notificationTopic=" + notificationTopic);
Map<String, String> ruleAttributes = new HashMap<>();
ruleAttributes.put("templateName", templateName);
- ruleAttributes.put("ClosedLoopControlName", prop.getControlNameAndPolicyUniqueId());
- ruleAttributes.put("NotificationTopic", notificationTopic);
+ 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
logger.info("operationTopic=" + operationTopic);
// format yaml
String yaml = formatYaml(refProp, prop, modelElementId, policyChain);
- ruleAttributes.put("OperationTopic", operationTopic);
- ruleAttributes.put("ControlLoopYaml", yaml);
+ ruleAttributes.put("operationTopic", operationTopic);
+ ruleAttributes.put("controlLoopYaml", yaml);
}
// matchingAttributes
Map<String, String> matchingAttributes = new HashMap<>();
String policyName = policyItem.getRecipe() + " Policy";
Target target = new Target();
target.setType(TargetType.VM);
+ // We can send target type as VM/VNF for most of recipes
+ if (policyItem.getRecipeLevel() != null && !policyItem.getRecipeLevel().isEmpty()) {
+ target.setType(TargetType.valueOf(policyItem.getRecipeLevel()));
+ }
target.setResourceID(policyItem.getTargetResourceId());
+ String actor = refProp.getStringValue("op.policy.appc");
+ Map<String, String> payloadMap = null;
+ if ("health-diagnostic".equalsIgnoreCase(policyItem.getRecipe())) {
+ actor = refProp.getStringValue("op.policy.sdno");
+ payloadMap = new HashMap<String, String>();
+ payloadMap.put("ttl", policyItem.getRecipePayload());
+ }
+ // For reboot recipe we have to send type as SOFT/HARD in pay load
+ if (policyItem.getRecipeInfo() != null && !policyItem.getRecipeInfo().isEmpty()) {
+ payloadMap = new HashMap<String, String>();
+ payloadMap.put("type", policyItem.getRecipeInfo());
+ }
Policy policyObj;
if (policyItemList.indexOf(policyItem) == 0) {
String policyDescription = policyItem.getRecipe()
+ " Policy - the trigger (no parent) policy - created by CLDS";
- policyObj = builder.setTriggerPolicy(policyName, policyDescription,
- refProp.getStringValue("op.policy.appc"), target, policyItem.getRecipe(), null,
- policyItem.getMaxRetries(), policyItem.getRetryTimeLimit());
+ policyObj = builder.setTriggerPolicy(policyName, policyDescription, actor, target,
+ policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit());
} else {
Policy parentPolicyObj = policyObjMap.get(policyItem.getParentPolicy());
String policyDescription = policyItem.getRecipe() + " Policy - triggered conditionally by "
+ parentPolicyObj.getName() + " - created by CLDS";
- policyObj = builder.setPolicyForPolicyResult(policyName, policyDescription,
- refProp.getStringValue("op.policy.appc"), target, policyItem.getRecipe(), null,
- policyItem.getMaxRetries(), policyItem.getRetryTimeLimit(), parentPolicyObj.getId(),
- convertToPolicyResult(policyItem.getParentPolicyConditions()));
+ policyObj = builder.setPolicyForPolicyResult(policyName, policyDescription, actor, target,
+ policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit(),
+ parentPolicyObj.getId(), convertToPolicyResult(policyItem.getParentPolicyConditions()));
logger.info("policyObj.id=" + policyObj.getId() + "; parentPolicyObj.id=" + parentPolicyObj.getId());
}
policyObjMap.put(policyItem.getId(), policyObj);
return URLEncoder.encode(results.getSpecification(), "UTF-8");
}
- private static void validate(Results results) {
+ protected static void validate(Results results) {
if (results.isValid()) {
logger.info("results.getSpecification()=" + results.getSpecification());
} else {
* @param resourceType
* @return
*/
- private static Resource[] convertToResource(List<String> stringList, ResourceType resourceType) {
+ protected static Resource[] convertToResource(List<String> stringList, ResourceType resourceType) {
if (stringList == null || stringList.isEmpty()) {
return new Resource[0];
}
* @param prList
* @return
*/
- private static PolicyResult[] convertToPolicyResult(List<String> prList) {
+ protected static PolicyResult[] convertToPolicyResult(List<String> prList) {
if (prList == null || prList.isEmpty()) {
return new PolicyResult[0];
}
import org.onap.policy.api.PushPolicyParameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
/**
* Policy utility methods - specifically, send the policy.
*/
@Component
+@Primary
public class PolicyClient {
protected PolicyEngine policyEngine;
* @return The response message from Policy
*/
public String deleteMicrosService(ModelProperties prop) {
- String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
- return deletePolicy(prop, policyType);
+ String deletePolicyResponse = "";
+ try {
+ String policyNamePrefix = refProp.getStringValue(POLICY_MS_NAME_PREFIX_PROPERTY_NAME);
+ List<Integer> versions = getVersions(policyNamePrefix, prop);
+ if (!versions.isEmpty()) {
+ String policyType = refProp.getStringValue(POLICY_MSTYPE_PROPERTY_NAME);
+ deletePolicyResponse = deletePolicy(prop, policyType);
+ }
+ } catch (Exception e) {
+ logger.error("Exception occurred during policy communication", e);
+ throw new PolicyClientException("Exception while communicating with Policy", e);
+ }
+ return deletePolicyResponse;
}
/**
* @return The response message from policy
*/
public String deleteBrms(ModelProperties prop) {
- String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
- return deletePolicy(prop, policyType);
+ String deletePolicyResponse = "";
+ try {
+ String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME);
+ List<Integer> versions = getVersions(policyNamePrefix, prop);
+ if (!versions.isEmpty()) {
+ String policyType = refProp.getStringValue(POLICY_OP_TYPE_PROPERTY_NAME);
+ deletePolicyResponse = deletePolicy(prop, policyType);
+ }
+ } catch (Exception e) {
+ logger.error("Exception occurred during policy communication", e);
+ throw new PolicyClientException("Exception while communicating with Policy", e);
+ }
+ return deletePolicyResponse;
}
/**
import org.onap.clamp.clds.util.JacksonUtils;\r
import org.onap.clamp.clds.util.LoggingUtils;\r
import org.springframework.beans.factory.annotation.Autowired;\r
+import org.springframework.context.annotation.Primary;\r
import org.springframework.stereotype.Component;\r
\r
@Component\r
+@Primary\r
public class SdcCatalogServices {\r
\r
private static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcCatalogServices.class);\r
}\r
}\r
}\r
+\r
+ /**\r
+ * Method to delete blueprint and location json artifacts from sdc\r
+ * \r
+ * @param prop\r
+ * @param userid\r
+ * @param sdcReqUrlsList\r
+ * @param artifactName\r
+ * @param locationArtifactName\r
+ * @throws GeneralSecurityException\r
+ * @throws DecoderException\r
+ */\r
+ public void deleteArtifactsFromSdc(ModelProperties prop, String userid, List<String> sdcReqUrlsList,\r
+ String artifactName, String locationArtifactName) throws GeneralSecurityException, DecoderException {\r
+ String serviceInvariantUuid = getServiceInvariantUuidFromProps(prop);\r
+ for (String url : sdcReqUrlsList) {\r
+ String originalServiceUuid = getServiceUuidFromServiceInvariantId(serviceInvariantUuid);\r
+ logger.info("ServiceUUID used before deleting in url:" + originalServiceUuid);\r
+ String sdcServicesInformation = getSdcServicesInformation(originalServiceUuid);\r
+ SdcServiceDetail cldsSdcServiceDetail = decodeCldsSdcServiceDetailFromJson(sdcServicesInformation);\r
+ String uploadedArtifactUuid = getArtifactIdIfArtifactAlreadyExists(cldsSdcServiceDetail, artifactName);\r
+ String responseStr = deleteArtifact(userid, url, uploadedArtifactUuid);\r
+ logger.info("value of sdc Response of deleting blueprint from sdc :" + responseStr);\r
+ String updatedServiceUuid = getServiceUuidFromServiceInvariantId(serviceInvariantUuid);\r
+ if (!originalServiceUuid.equalsIgnoreCase(updatedServiceUuid)) {\r
+ url = url.replace(originalServiceUuid, updatedServiceUuid);\r
+ }\r
+ logger.info("ServiceUUID used after delete in ulr:" + updatedServiceUuid);\r
+ sdcServicesInformation = getSdcServicesInformation(updatedServiceUuid);\r
+ cldsSdcServiceDetail = decodeCldsSdcServiceDetailFromJson(sdcServicesInformation);\r
+ uploadedArtifactUuid = getArtifactIdIfArtifactAlreadyExists(cldsSdcServiceDetail, locationArtifactName);\r
+ responseStr = deleteArtifact(userid, url, uploadedArtifactUuid);\r
+ logger.info("value of sdc Response of deleting location json from sdc :" + responseStr);\r
+ }\r
+ }\r
+\r
+ private String deleteArtifact(String userid, String url, String uploadedArtifactUuid) {\r
+ try {\r
+ String responseStr = "";\r
+ if (uploadedArtifactUuid != null && !uploadedArtifactUuid.isEmpty()) {\r
+ logger.info("userid=" + userid);\r
+ String basicAuth = getSdcBasicAuth();\r
+ String sdcXonapInstanceId = refProp.getStringValue("sdc.sdcX-InstanceID");\r
+ url = url + "/" + uploadedArtifactUuid;\r
+ URL urlObj = new URL(url);\r
+ HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();\r
+ conn.setDoOutput(true);\r
+ conn.setRequestProperty(refProp.getStringValue(SDC_INSTANCE_ID_PROPERTY_NAME), sdcXonapInstanceId);\r
+ conn.setRequestProperty(HttpHeaders.AUTHORIZATION, basicAuth);\r
+ conn.setRequestProperty("USER_ID", userid);\r
+ conn.setRequestMethod("DELETE");\r
+ conn.setRequestProperty("charset", "utf-8");\r
+ conn.setUseCaches(false);\r
+ conn.setRequestProperty(refProp.getStringValue(SDC_REQUESTID_PROPERTY_NAME),\r
+ LoggingUtils.getRequestId());\r
+ boolean requestFailed = true;\r
+ int responseCode = conn.getResponseCode();\r
+ logger.info("responseCode=" + responseCode);\r
+ if (responseCode == 200) {\r
+ requestFailed = false;\r
+ }\r
+ responseStr = getResponse(conn);\r
+ if (responseStr != null && requestFailed) {\r
+ logger.error("requestFailed - responseStr=" + responseStr);\r
+ throw new BadRequestException(responseStr);\r
+ }\r
+ }\r
+ return responseStr;\r
+ } catch (IOException | DecoderException | GeneralSecurityException e) {\r
+ logger.error("Exception when attempting to communicate with SDC", e);\r
+ throw new SdcCommunicationException("Exception when attempting to communicate with SDC", e);\r
+ }\r
+ }\r
}\r
import org.onap.clamp.clds.model.sdc.SdcServiceDetail;
import org.onap.clamp.clds.util.JacksonUtils;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
/**
* Construct a Sdc request given CLDS objects.
*/
@Component
+@Primary
public class SdcRequests {
protected static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcRequests.class);
private SimpleJdbcCall procGetTemplate;
private SimpleJdbcCall procDelAllModelInstances;
private SimpleJdbcCall procInsModelInstance;
+ private SimpleJdbcCall procDeleteModel;
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";
+
/**
* Log message when instantiating
*/
this.procSetTemplate = new SimpleJdbcCall(dataSource).withProcedureName("set_template");
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");
}
/**
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<String, Object> out = logSqlExecution(procGetModel, in);
- 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")));
- model.setTemplateId((String) (out.get("v_template_id")));
- model.setTemplateName((String) (out.get("v_template_name")));
- model.setBpmnText((String) out.get("v_template_bpmn_text"));
- model.setPropText((String) out.get("v_model_prop_text"));
- model.setImageText((String) out.get("v_template_image_text"));
- model.setDocText((String) out.get("v_template_doc_text"));
- model.setBlueprintText((String) out.get("v_model_blueprint_text"));
- model.getEvent().setId((String) (out.get("v_event_id")));
- model.getEvent().setActionCd((String) out.get("v_action_cd"));
- model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
- 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"));
+ populateModelProperties(model, out);
return model;
}
SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName);
Map<String, Object> out = logSqlExecution(procGetModelTemplate, in);
// 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")));
- model.setTemplateId((String) (out.get("v_template_id")));
- model.setTemplateName((String) (out.get("v_template_name")));
- model.setBpmnText((String) out.get("v_template_bpmn_text"));
- model.setPropText((String) out.get("v_model_prop_text"));
- model.setImageText((String) out.get("v_template_image_text"));
- model.setDocText((String) out.get("v_template_doc_text"));
- model.setBlueprintText((String) out.get("v_model_blueprint_text"));
- model.getEvent().setId((String) (out.get("v_event_id")));
- model.getEvent().setActionCd((String) out.get("v_action_cd"));
- model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
- 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"));
+ populateModelProperties(model, out);
Map<String, Object> modelResults = logSqlExecution(procGetModel, in);
Object modelResultObject = modelResults.get("#result-set-1");
if (modelResultObject != null && modelResultObject instanceof ArrayList) {
.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_CONTROL_NAME_UUID, model.getControlNameUuid());
Map<String, Object> out = logSqlExecution(procSetModel, in);
- model.setControlNamePrefix((String) out.get("v_control_name_prefix"));
- model.setControlNameUuid((String) out.get("v_control_name_uuid"));
+ 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")));
model.getEvent().setId((String) (out.get("v_event_id")));
model.getEvent().setActionCd((String) out.get("v_action_cd"));
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_CONTROL_NAME_UUID, model.getControlNameUuid())
.addValue("v_vm_name", currModelInstance.getVmName())
.addValue("v_location", currModelInstance.getLocation());
Map<String, Object> out = logSqlExecution(procInsModelInstance, in);
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_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());
}
private String delAllModelInstances(String controlNameUUid) {
- SqlParameterSource in = new MapSqlParameterSource().addValue("v_control_name_uuid", controlNameUUid);
+ SqlParameterSource in = new MapSqlParameterSource().addValue(V_CONTROL_NAME_UUID, controlNameUUid);
Map<String, Object> out = logSqlExecution(procDelAllModelInstances, in);
return (String) (out.get("v_model_id"));
}
CldsServiceData cldsServiceData = null;
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());
+ cldsServiceData = jdbcTemplateObject.queryForObject(getCldsServiceSQL, new Object[] { invariantUUID },
+ new CldsServiceDataMapper());
if (cldsServiceData != null) {
logger.info("CldsServiceData found in cache for Service Invariant ID:"
+ cldsServiceData.getServiceInvariantUUID());
}
return cldsMonitoringDetailsList;
}
+
+ /**
+ * 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")));
+ model.setTemplateId((String) (out.get("v_template_id")));
+ model.setTemplateName((String) (out.get("v_template_name")));
+ model.setBpmnText((String) out.get("v_template_bpmn_text"));
+ model.setPropText((String) out.get("v_model_prop_text"));
+ model.setImageText((String) out.get("v_template_image_text"));
+ model.setDocText((String) out.get("v_template_doc_text"));
+ model.setBlueprintText((String) out.get("v_model_blueprint_text"));
+ model.getEvent().setId((String) (out.get("v_event_id")));
+ model.getEvent().setActionCd((String) out.get("v_action_cd"));
+ model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
+ 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"));
+ }
}
import org.apache.commons.io.serialization.ValidatingObjectInputStream;
import org.onap.clamp.clds.model.CldsServiceData;
import org.onap.clamp.clds.model.CldsVfData;
+import org.onap.clamp.clds.model.CldsVfKPIData;
import org.onap.clamp.clds.model.CldsVfcData;
import org.springframework.jdbc.core.RowMapper;
public CldsServiceData mapRow(ResultSet rs, int rowNum) throws SQLException {
CldsServiceData cldsServiceData = new CldsServiceData();
try (ValidatingObjectInputStream oip = new ValidatingObjectInputStream(rs.getBlob(4).getBinaryStream())) {
- oip.accept(CldsServiceData.class, ArrayList.class, CldsVfData.class, CldsVfcData.class);
+ oip.accept(CldsServiceData.class, ArrayList.class, CldsVfData.class, CldsVfcData.class,
+ CldsVfKPIData.class);
cldsServiceData = (CldsServiceData) oip.readObject();
cldsServiceData.setAgeOfRecord(rs.getLong(5));
} catch (IOException | ClassNotFoundException e) {
* ============LICENSE_START=======================================================
* ONAP CLAMP
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights
+ * 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.
+ * 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
+ *
+ * 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============================================
* ===================================================================
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";
// an update before model is active
public static final String ACTION_RESUBMIT = "RESUBMIT";
public boolean canInventoryCall() {
boolean canCall = false;
- /* Below checks the clds event is submit/resubmit */
- if ((event.isActionCd(CldsEvent.ACTION_SUBMIT) || event.isActionCd(CldsEvent.ACTION_RESUBMIT)
- || event.isActionCd(CldsEvent.ACTION_SUBMITDCAE))) {
+ /* Below checks the clds event is submit/resubmit/distribute */
+ if (event.isActionCd(CldsEvent.ACTION_SUBMIT) || event.isActionCd(CldsEvent.ACTION_RESUBMIT)
+ || event.isActionCd(CldsEvent.ACTION_DISTRIBUTE) || event.isActionCd(CldsEvent.ACTION_SUBMITDCAE)) {
canCall = true;
}
return canCall;
|| event.isActionAndStateCd(CldsEvent.ACTION_SUBMIT, CldsEvent.ACTION_STATE_ANY)
|| event.isActionAndStateCd(CldsEvent.ACTION_RESUBMIT, CldsEvent.ACTION_STATE_ANY)
|| event.isActionAndStateCd(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_STATE_ANY)
- || event.isActionAndStateCd(CldsEvent.ACTION_DELETE, CldsEvent.ACTION_STATE_RECEIVED)) {
+ || event.isActionAndStateCd(CldsEvent.ACTION_DELETE, CldsEvent.ACTION_STATE_RECEIVED)
+ || event.isActionAndStateCd(CldsEvent.ACTION_MODIFY, CldsEvent.ACTION_STATE_ANY)) {
status = STATUS_DESIGN;
} else if (event.isActionAndStateCd(CldsEvent.ACTION_DISTRIBUTE, CldsEvent.ACTION_STATE_RECEIVED)
|| event.isActionAndStateCd(CldsEvent.ACTION_UNDEPLOY, CldsEvent.ACTION_STATE_RECEIVED)) {
String actionCd = getCurrentActionCd();
switch (actionCd) {
case CldsEvent.ACTION_CREATE:
- permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMIT, CldsEvent.ACTION_TEST);
+ permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMIT, CldsEvent.ACTION_TEST,
+ CldsEvent.ACTION_DELETE);
if (isSimplifiedModel()) {
- permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_TEST);
+ permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, 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);
}
break;
case CldsEvent.ACTION_SUBMIT:
case CldsEvent.ACTION_RESUBMIT:
- // for 1702 delete is not currently implemented (and resubmit
- // requires manually deleting artifact from sdc
- permittedActionCd = Arrays.asList(CldsEvent.ACTION_RESUBMIT);
+ permittedActionCd = Arrays.asList(CldsEvent.ACTION_RESUBMIT, CldsEvent.ACTION_DELETE);
break;
case CldsEvent.ACTION_SUBMITDCAE:
- permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE);
+ permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_DELETE);
break;
case CldsEvent.ACTION_DISTRIBUTE:
- permittedActionCd = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_RESUBMIT);
+ permittedActionCd = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_RESUBMIT,
+ CldsEvent.ACTION_DELETE);
if (isSimplifiedModel()) {
- permittedActionCd = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_SUBMITDCAE);
+ permittedActionCd = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_SUBMITDCAE,
+ CldsEvent.ACTION_DELETE);
}
break;
case CldsEvent.ACTION_UNDEPLOY:
permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_DEPLOY,
- CldsEvent.ACTION_RESUBMIT);
+ CldsEvent.ACTION_RESUBMIT, CldsEvent.ACTION_DELETE);
if (isSimplifiedModel()) {
permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_DEPLOY,
- CldsEvent.ACTION_SUBMITDCAE);
+ CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_DELETE);
}
break;
case CldsEvent.ACTION_DEPLOY:
break;
case CldsEvent.ACTION_RESTART:
case CldsEvent.ACTION_UPDATE:
- // for 1702 delete is not currently implemented
permittedActionCd = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_UPDATE,
CldsEvent.ACTION_STOP, CldsEvent.ACTION_UNDEPLOY);
break;
- case CldsEvent.ACTION_DELETE:
- if (getCurrentActionStateCd().equals(CldsEvent.ACTION_STATE_SENT)) {
- permittedActionCd = Arrays.asList();
- } else {
- permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMIT);
- }
- break;
case CldsEvent.ACTION_STOP:
- // for 1702 delete is not currently implemented
permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_RESTART,
CldsEvent.ACTION_UNDEPLOY);
break;
* "targetResourceId","value":["Eace933104d443b496b8.nodes.heat.vpg"]}]]}]
*/
public class PolicyItem implements Cloneable {
-
protected static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyItem.class);
protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
+
private String id;
private String recipe;
private int maxRetries;
private List<String> parentPolicyConditions;
private String actor;
private String targetResourceId;
+ private String recipeInfo;
+ private String recipeLevel;
+ private String recipePayload;
+ private String oapRop;
+ private String oapLimit;
/**
* Parse Policy given json node.
if (targetResourceId != null && targetResourceId.isEmpty()) {
this.setTargetResourceId(null);
}
+ recipeInfo = AbstractModelElement.getValueByName(node, "recipeInfo");
+ recipeLevel = AbstractModelElement.getValueByName(node, "recipeLevel");
+ recipePayload = AbstractModelElement.getValueByName(node, "recipeInput");
+ oapRop = AbstractModelElement.getValueByName(node, "oapRop");
+ oapLimit = AbstractModelElement.getValueByName(node, "oapLimit");
}
/**
this.targetResourceId = targetResourceId;
}
+ public String getRecipeInfo() {
+ return recipeInfo;
+ }
+
+ public String getRecipeLevel() {
+ return recipeLevel;
+ }
+
+ public String getRecipePayload() {
+ return recipePayload;
+ }
+
+ public String getOapRop() {
+ if (oapRop == null) {
+ oapRop = "0m";
+ }
+ return oapRop;
+ }
+
+ public String getOapLimit() {
+ if (oapLimit == null) {
+ oapLimit = "0";
+ }
+ return oapLimit;
+ }
+
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
+++ /dev/null
-/*-
- * ============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============================================
- * ===================================================================
- *
- */
-
-package org.onap.clamp.clds.model.properties;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.fasterxml.jackson.databind.JsonNode;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * Parse Resource Group json properties.
- *
- * Example json:
- * {"TCA_0aji7go":{"Group1":[{"name":"rgname","value":"1493749598520"},{
- * "name":"rgfriendlyname","value":"Group1"},{"name":"policyName","value":
- * "Policy1"},{"name":"policyId","value":"1"},{"serviceConfigurations":[[{"name"
- * :"aaiMatchingFields","value":["complex.city","vserver.vserver-name"]},{"name"
- * :"aaiSendFields","value":["complex.city","vserver.vserver-name"]},{"name":
- * "eventSeverity","value":["OK"]},{"name":"eventSourceType","value":[""]},{
- * "name":"timeWindow","value":["100"]},{"name":"ageLimit","value":["100"]},{
- * "name":"createClosedLoopEventId","value":["Initial"]},{"name":
- * "outputEventName","value":["ONSET"]}]]}],"Group2":[{"name":"rgname","value":
- * "1493749665149"},{"name":"rgfriendlyname","value":"Group2"},{"name":
- * "policyName","value":"Policy2"},{"name":"policyId","value":"2"},{
- * "serviceConfigurations":[[{"name":"aaiMatchingFields","value":[
- * "cloud-region.identity-url","vserver.vserver-name"]},{"name":"aaiSendFields",
- * "value":["cloud-region.identity-url","vserver.vserver-name"]},{"name":
- * "eventSeverity","value":["NORMAL"]},{"name":"eventSourceType","value":[""]},{
- * "name":"timeWindow","value":["1000"]},{"name":"ageLimit","value":["1000"]},{
- * "name":"createClosedLoopEventId","value":["Initial"]},{"name":
- * "outputEventName","value":["ONSET"]}],[{"name":"aaiMatchingFields","value":[
- * "generic-vnf.vnf-name","vserver.vserver-name"]},{"name":"aaiSendFields",
- * "value":["generic-vnf.vnf-name","vserver.vserver-name"]},{"name":
- * "eventSeverity","value":["CRITICAL"]},{"name":"eventSourceType","value":[""]}
- * ,{"name":"timeWindow","value":["3000"]},{"name":"ageLimit","value":["3000"]},
- * {"name":"createClosedLoopEventId","value":["Initial"]},{"name":
- * "outputEventName","value":["ABATED"]}]]}]}}
- *
- */
-public class ResourceGroup {
-
- protected static final EELFLogger logger = EELFManager.getInstance().getLogger(ResourceGroup.class);
- protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
-
- private String groupNumber;
- private String policyId;
- private List<ServiceConfiguration> serviceConfigurations;
-
- /**
- * Parse String Match Resource Group given json node.
- *
- * @param modelBpmn
- * @param modelJson
- */
- public ResourceGroup(JsonNode node) {
-
- groupNumber = AbstractModelElement.getValueByName(node, "rgname");
- policyId = AbstractModelElement.getValueByName(node, "policyId");
-
- // process Server_Configurations
- JsonNode serviceConfigurationsNode = node.get(node.size() - 1).get("serviceConfigurations");
- Iterator<JsonNode> itr = serviceConfigurationsNode.elements();
- serviceConfigurations = new ArrayList<>();
- while (itr.hasNext()) {
- serviceConfigurations.add(new ServiceConfiguration(itr.next()));
- }
- }
-
- /**
- * @return the groupNumber
- */
- public String getGroupNumber() {
- return groupNumber;
- }
-
- /**
- * @return the policyId
- */
- public String getPolicyId() {
- return policyId;
- }
-
- /**
- * @return the serviceConfigurations
- */
- public List<ServiceConfiguration> getServiceConfigurations() {
- return serviceConfigurations;
- }
-
-}
+++ /dev/null
-/*-
- * ============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============================================
- * ===================================================================
- *
- */
-
-package org.onap.clamp.clds.model.properties;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.fasterxml.jackson.databind.JsonNode;
-
-/**
- * Parse serviceConfigurations from Tca json properties.
- * <p>
- * Example json:
- * {"Tca_0aji7go":{"Group1":[{"name":"rgname","value":"1493749598520"},{
- * "name":"rgfriendlyname","value":"Group1"},{"name":"policyName","value":
- * "Policy1"},{"name":"policyId","value":"1"},{"serviceConfigurations":[[{"name"
- * :"aaiMatchingFields","value":["complex.city","vserver.vserver-name"]},{"name"
- * :"aaiSendFields","value":["complex.city","vserver.vserver-name"]},{"name":
- * "eventSeverity","value":["OK"]},{"name":"eventSourceType","value":[""]},{
- * "name":"timeWindow","value":["100"]},{"name":"ageLimit","value":["100"]},{
- * "name":"createClosedLoopEventId","value":["Initial"]},{"name":
- * "outputEventName","value":["ONSET"]}]]}],"Group2":[{"name":"rgname","value":
- * "1493749665149"},{"name":"rgfriendlyname","value":"Group2"},{"name":
- * "policyName","value":"Policy2"},{"name":"policyId","value":"2"},{
- * "serviceConfigurations":[[{"name":"aaiMatchingFields","value":[
- * "cloud-region.identity-url","vserver.vserver-name"]},{"name":"aaiSendFields",
- * "value":["cloud-region.identity-url","vserver.vserver-name"]},{"name":
- * "eventSeverity","value":["NORMAL"]},{"name":"eventSourceType","value":[""]},{
- * "name":"timeWindow","value":["1000"]},{"name":"ageLimit","value":["1000"]},{
- * "name":"createClosedLoopEventId","value":["Initial"]},{"name":
- * "outputEventName","value":["ONSET"]}],[{"name":"aaiMatchingFields","value":[
- * "generic-vnf.vnf-name","vserver.vserver-name"]},{"name":"aaiSendFields",
- * "value":["generic-vnf.vnf-name","vserver.vserver-name"]},{"name":
- * "eventSeverity","value":["CRITICAL"]},{"name":"eventSourceType","value":[""]}
- * ,{"name":"timeWindow","value":["3000"]},{"name":"ageLimit","value":["3000"]},
- * {"name":"createClosedLoopEventId","value":["Initial"]},{"name":
- * "outputEventName","value":["ABATED"]}]]}]}}
- *
- */
-public class ServiceConfiguration {
-
- protected static final EELFLogger logger = EELFManager.getInstance().getLogger(ServiceConfiguration.class);
- protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
-
- private final List<String> aaiMatchingFields;
- private final List<String> aaiSendFields;
- // private final String groupNumber;
- private final List<String> resourceVf;
- private final List<String> resourceVfc;
- private final String timeWindow;
- private final String ageLimit;
- private final String createClosedLoopEventId;
- private final String outputEventName;
- private final Map<String, String> stringSet;
-
- /**
- * Parse serviceConfigurations given json node.
- *
- * @param node
- */
- public ServiceConfiguration(JsonNode node) {
- aaiMatchingFields = AbstractModelElement.getValuesByName(node, "aaiMatchingFields");
- aaiSendFields = AbstractModelElement.getValuesByName(node, "aaiSendFields");
- // groupNumber = ModelElement.getValueByName(node, "groupNumber");
- resourceVf = AbstractModelElement.getValuesByName(node, "vf");
- resourceVfc = AbstractModelElement.getValuesByName(node, "vfc");
- timeWindow = AbstractModelElement.getValueByName(node, "timeWindow");
- ageLimit = AbstractModelElement.getValueByName(node, "ageLimit");
- createClosedLoopEventId = AbstractModelElement.getValueByName(node, "createClosedLoopEventId");
- outputEventName = AbstractModelElement.getValueByName(node, "outputEventName");
-
- // process the stringSet fields
- JsonNode ssNodes = node.findPath("stringSet");
- Iterator<JsonNode> itr = ssNodes.elements();
- stringSet = new HashMap<>();
- while (itr.hasNext()) {
- JsonNode ssNode = itr.next();
- String key = ssNode.path("name").asText();
- String value = ssNode.path("value").path(0).asText();
- if (key.length() != 0 && value.length() != 0) {
- // only add string set field if not null
- logger.debug("stringSet: " + key + "=" + value);
- stringSet.put(key, value);
- }
- }
- }
-
- /**
- * @return the aaiMatchingFields
- */
- public List<String> getaaiMatchingFields() {
- return aaiMatchingFields;
- }
-
- /**
- * @return the aaiSendFields
- */
- public List<String> getaaiSendFields() {
- return aaiSendFields;
- }
-
- /**
- * @return the groupNumber
- */ /*
- * public String getGroupNumber() { return groupNumber; }
- */
- /**
- * @return the resourceVf
- */
- public List<String> getResourceVf() {
- return resourceVf;
- }
-
- /**
- * @return the resourceVfc
- */
- public List<String> getResourceVfc() {
- return resourceVfc;
- }
-
- /**
- * @return the timeWindow
- */
- public String getTimeWindow() {
- return timeWindow;
- }
-
- /**
- * @return the ageLimit
- */
- public String getAgeLimit() {
- return ageLimit;
- }
-
- /**
- * @return the createClosedLoopEventId
- */
- public String getCreateClosedLoopEventId() {
- return createClosedLoopEventId;
- }
-
- /**
- * @return the outputEventName
- */
- public String getOutputEventName() {
- return outputEventName;
- }
-
- /**
- * @return the stringSet
- */
- public Map<String, String> getStringSet() {
- return stringSet;
- }
-
-}
--- /dev/null
+/*-
+ * ============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============================================
+ * ===================================================================
+ */
+package org.onap.clamp.clds.service;
+
+import java.util.Date;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.onap.clamp.clds.dao.CldsDao;
+import org.onap.clamp.clds.model.CldsHealthCheck;
+import org.onap.clamp.clds.util.LoggingUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
+/**
+ * Service to retrieve the Health Check of the clds application.
+ *
+ */
+@Component
+@Path("/")
+public class CldsHealthcheckService {
+
+ @Autowired
+ private CldsDao cldsDao;
+
+ protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsHealthcheckService.class);
+
+ /**
+ * REST service that retrieves clds healthcheck information.
+ *
+ * @return CldsHealthCheck class containing healthcheck info
+ */
+ @GET
+ @Path("/healthcheck")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response gethealthcheck() {
+ CldsHealthCheck cldsHealthCheck = new CldsHealthCheck();
+ Date startTime = new Date();
+ LoggingUtils.setRequestContext("CldsService: GET healthcheck", "Clamp-Health-Check");
+ LoggingUtils.setTimeContext(startTime, new Date());
+ boolean healthcheckFailed = false;
+ try {
+ cldsDao.doHealthCheck();
+ cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
+ cldsHealthCheck.setHealthCheckStatus("UP");
+ cldsHealthCheck.setDescription("OK");
+ LoggingUtils.setResponseContext("0", "Get healthcheck success", this.getClass().getName());
+ } catch (Exception e) {
+ healthcheckFailed = true;
+ logger.error("CLAMP application Heath check failed", e);
+ LoggingUtils.setResponseContext("999", "Get healthcheck failed", this.getClass().getName());
+ cldsHealthCheck.setHealthCheckComponent("CLDS-APP");
+ cldsHealthCheck.setHealthCheckStatus("DOWN");
+ cldsHealthCheck.setDescription("NOT-OK");
+ }
+ // audit log
+ LoggingUtils.setTimeContext(startTime, new Date());
+ if(healthcheckFailed) {
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(cldsHealthCheck).build();
+ } else {
+ return Response.status(Response.Status.OK).entity(cldsHealthCheck).build();
+ }
+ }
+}
\ No newline at end of file
cldsModel.setBpmnText(template.getBpmnText());
}
}
+ updateAndInsertNewEvent(cldsModel.getName(), cldsModel.getControlNamePrefix(), cldsModel.getEvent(),
+ CldsEvent.ACTION_MODIFY);
cldsModel.save(cldsDao, getUserId());
// audit log
LoggingUtils.setTimeContext(startTime, new Date());
this.fillInCldsModel(model);
// save model to db
model.setName(modelName);
+ updateAndInsertNewEvent(modelName, model.getControlNamePrefix(), model.getEvent(), CldsEvent.ACTION_MODIFY);
model.save(cldsDao, getUserId());
// get vars and format if necessary
String prop = model.getPropText();
logger.info("docText - " + docText);
try {
String result = camelProxy.submit(actionCd, prop, bpmnJson, modelName, controlName, docText, isTest,
- userId, isInsertTestEvent);
+ userId, isInsertTestEvent, model.getEvent().getActionCd());
logger.info("Starting Camel flow on request, result is: ", result);
} catch (SdcCommunicationException | PolicyClientException | BadRequestException e) {
errorCase = true;
logger.error("Exception occured during invoking Camel process", e);
}
- // refresh model info from db (get fresh event info)
- retrievedModel = CldsModel.retrieve(cldsDao, modelName, false);
+ if (!actionCd.equalsIgnoreCase(CldsEvent.ACTION_DELETE)) {
+ // refresh model info from db (get fresh event info)
+ retrievedModel = CldsModel.retrieve(cldsDao, modelName, false);
+ }
if (!isTest && (actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMIT)
|| actionCd.equalsIgnoreCase(CldsEvent.ACTION_RESUBMIT)
|| actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE))) {
}
}
}
+
+ private void updateAndInsertNewEvent(String cldsModelName, String cldsControlNamePrfx, CldsEvent event,
+ String newAction) {
+ // If model action is in submit/resubmit/distributed and user try
+ // to save then we are changing action back to create.
+ if (event != null && (CldsEvent.ACTION_SUBMIT.equalsIgnoreCase(event.getActionCd())
+ || CldsEvent.ACTION_RESUBMIT.equalsIgnoreCase(event.getActionCd())
+ || CldsEvent.ACTION_DISTRIBUTE.equalsIgnoreCase(event.getActionCd()))) {
+ CldsEvent newEvent = new CldsEvent();
+ newEvent.setUserid(getUserId());
+ newEvent.setActionCd(newAction);
+ newEvent.setActionStateCd(CldsEvent.ACTION_STATE_COMPLETED);
+ cldsDao.insEvent(cldsModelName, cldsControlNamePrfx, null, newEvent);
+ }
+ }
}
\ No newline at end of file
* In case of issues with the permission test, error is returned
* in this exception
*/
- public boolean isAuthorized(SecureServicePermission inPermission) throws NotAuthorizedException {
- boolean authorized = false;
-
- Date startTime = new Date();
- LoggingUtils.setTargetContext("CLDS", "isAuthorized");
- LoggingUtils.setTimeContext(startTime, new Date());
-
- securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission);
-
- // check if the user has the permission key or the permission key with a
- // combination of all instance and/or all action.
- if (securityContext.isUserInRole(inPermission.getKey())) {
- securityLogger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey());
- authorized = true;
- // the rest of these don't seem to be required - isUserInRole method
- // appears to take * as a wildcard
- } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) {
- securityLogger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(), inPermission.getKey());
- authorized = true;
- } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) {
- securityLogger.info("{} authorized because user has permission with * for instance and * for action: {}", getPrincipalName(), inPermission.getKey());
- authorized = true;
- } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) {
- securityLogger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(), inPermission.getKey());
- authorized = true;
- } else {
- String msg = getPrincipalName() + " does not have permission: " + inPermission;
- LoggingUtils.setErrorContext("100", "Authorization Error");
- securityLogger.warn(msg);
- throw new NotAuthorizedException(msg);
- }
- return authorized;
- }
+ public boolean isAuthorized(SecureServicePermission inPermission) throws NotAuthorizedException {
+ Date startTime = new Date();
+ LoggingUtils.setTargetContext("CLDS", "isAuthorized");
+ LoggingUtils.setTimeContext(startTime, new Date());
+ securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission);
+ try {
+ return isUserPermitted(inPermission);
+ } catch (NotAuthorizedException nae) {
+ String msg = getPrincipalName() + " does not have permission: " + inPermission;
+ LoggingUtils.setErrorContext("100", "Authorization Error");
+ securityLogger.warn(msg);
+ throw new NotAuthorizedException(msg);
+ }
+ }
/**
* Check if user is authorized for the given aaf permission. Allow matches
* @return A boolean to indicate if the user has the permission to do
* execute the inPermission
*/
- public boolean isAuthorizedNoException(SecureServicePermission inPermission) {
- boolean authorized = false;
-
- securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission);
- Date startTime = new Date();
- LoggingUtils.setTargetContext("CLDS", "isAuthorizedNoException");
- LoggingUtils.setTimeContext(startTime, new Date());
-
- // check if the user has the permission key or the permission key with a
- // combination of all instance and/or all action.
- if (securityContext.isUserInRole(inPermission.getKey())) {
- securityLogger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey());
- authorized = true;
- // the rest of these don't seem to be required - isUserInRole method
- // appears to take * as a wildcard
- } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) {
- securityLogger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(),inPermission.getKey());
- authorized = true;
- } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) {
- securityLogger.info("{} authorized because user has permission with * for instance and * for action: {}", getPrincipalName(), inPermission.getKey());
- authorized = true;
- } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) {
- securityLogger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(), inPermission.getKey());
- authorized = true;
- } else {
- String msg = getPrincipalName() + " does not have permission: " + inPermission;
- LoggingUtils.setErrorContext("100", "Authorization Error");
- securityLogger.warn(msg);
- logger.warn(msg);
- }
- return authorized;
- }
+ public boolean isAuthorizedNoException(SecureServicePermission inPermission) {
+ securityLogger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission);
+ Date startTime = new Date();
+ LoggingUtils.setTargetContext("CLDS", "isAuthorizedNoException");
+ LoggingUtils.setTimeContext(startTime, new Date());
+ try {
+ return isUserPermitted(inPermission);
+ } catch (NotAuthorizedException nae) {
+ String msg = getPrincipalName() + " does not have permission: " + inPermission;
+ LoggingUtils.setErrorContext("100", "Authorization Error");
+ securityLogger.warn(msg);
+ }
+ return false;
+ }
/**
* This method can be used by the Application.class to set the
public void setSecurityContext(SecurityContext securityContext) {
this.securityContext = securityContext;
}
-
-}
+
+ private boolean isUserPermitted(SecureServicePermission inPermission) throws NotAuthorizedException {
+ boolean authorized = false;
+ // check if the user has the permission key or the permission key with a
+ // combination of all instance and/or all action.
+ if (securityContext.isUserInRole(inPermission.getKey())) {
+ securityLogger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey());
+ authorized = true;
+ // the rest of these don't seem to be required - isUserInRole method
+ // appears to take * as a wildcard
+ } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) {
+ securityLogger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(), inPermission.getKey());
+ authorized = true;
+ } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) {
+ securityLogger.info("{} authorized because user has permission with * for instance and * for action: {}", getPrincipalName(), inPermission.getKey());
+ authorized = true;
+ } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) {
+ securityLogger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(), inPermission.getKey());
+ authorized = true;
+ } else {
+ throw new NotAuthorizedException("");
+ }
+ return authorized;
+ }
+}
\ No newline at end of file
* Definition of encryption algorithm.
*/
private static final String ALGORITHM = "AES";
+
+ /**
+ * AES Encryption Key environment variable for external configuration
+ */
+ private static final String AES_ENCRYPTION_KEY = "AES_ENCRYPTION_KEY";
+
/**
* Detailed definition of encryption algorithm.
*/
private static SecretKeySpec readSecretKeySpec(String propertiesFileName) {
Properties props = new Properties();
try {
- props.load(ResourceFileUtil.getResourceAsStream(propertiesFileName));
- return getSecretKeySpec(props.getProperty(KEY_PARAM));
+ //Workaround fix to make encryption key configurable.
+ //System environment variable takes precedence for over clds/key.properties
+ String encryptionKey = System.getenv(AES_ENCRYPTION_KEY);
+ if(encryptionKey != null && encryptionKey.trim().length() > 0) {
+ return getSecretKeySpec(encryptionKey);
+ } else {
+ props.load(ResourceFileUtil.getResourceAsStream(propertiesFileName));
+ return getSecretKeySpec(props.getProperty(KEY_PARAM));
+ }
} catch (IOException | DecoderException e) {
logger.error("Exception occurred during the key reading", e);
return null;
MDC.put("RequestId", UUID.randomUUID().toString());\r
MDC.put("ServiceName", service);\r
MDC.put("PartnerName", partner);\r
+ //Defaulting to HTTP/1.1 protocol\r
+ MDC.put("Protocol", "HTTP/1.1");\r
try {\r
MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName());\r
MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress());\r
<constant>30000</constant>
</delay>
<to uri="bean:org.onap.clamp.clds.client.OperationalPolicyDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.CldsEventDelegate" />
</when>
<when>
<simple> ${exchangeProperty.actionCd} == 'DELETE'</simple>
<to uri="bean:org.onap.clamp.clds.client.TcaPolicyDeleteDelegate" />
<to uri="bean:org.onap.clamp.clds.client.HolmesPolicyDeleteDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.ModelDeleteDelegate" />
<delay>
<constant>30000</constant>
</delay>
<constant>30000</constant>
</delay>
<to uri="bean:org.onap.clamp.clds.client.OperationalPolicyDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.CldsEventDelegate" />
</when>
<when>
<simple> ${exchangeProperty.actionCd} == 'STOP'</simple>
<to
uri="bean:org.onap.clamp.clds.client.OperationalPolicyDeleteDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.CldsEventDelegate" />
</when>
<when>
<simple> ${exchangeProperty.actionCd} == 'RESTART'</simple>
<to uri="bean:org.onap.clamp.clds.client.OperationalPolicyDelegate" />
+ <to uri="bean:org.onap.clamp.clds.client.CldsEventDelegate" />
</when>
</choice>
- <to uri="bean:org.onap.clamp.clds.client.CldsEventDelegate" />
</route>
</routes>
\ No newline at end of file
--- /dev/null
+/*-
+ * ============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============================================
+ * ===================================================================
+ */
+
+package org.onap.clamp.clds.it;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import javax.ws.rs.core.Response;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.onap.clamp.clds.model.CldsHealthCheck;
+import org.onap.clamp.clds.service.CldsHealthcheckService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+/**
+ * Tests HealthCheck Service.
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+public class CldsHealthcheckServiceItCase {
+
+ @Autowired
+ private CldsHealthcheckService cldsHealthcheckService;
+
+ @Test
+ public void testGetHealthCheck() {
+ Response response = cldsHealthcheckService.gethealthcheck();
+ CldsHealthCheck cldsHealthCheck = (CldsHealthCheck) response.getEntity();
+ assertNotNull(cldsHealthCheck);
+ assertEquals("UP", cldsHealthCheck.getHealthCheckStatus());
+ assertEquals("CLDS-APP", cldsHealthCheck.getHealthCheckComponent());
+ assertEquals("OK", cldsHealthCheck.getDescription());
+ }
+}
assertTrue(attributes.size() == 2);
// now validate the Yaml, to do so we replace the dynamic ID by a known
// key so that we can compare it
- String yaml = URLDecoder.decode(attributes.get(0).get(AttributeType.RULE).get("ControlLoopYaml"), "UTF-8");
+ String yaml = URLDecoder.decode(attributes.get(0).get(AttributeType.RULE).get("controlLoopYaml"), "UTF-8");
yaml = replaceGeneratedValues(yaml);
assertEquals(ResourceFileUtil.getResourceAsString("example/operational-policy/yaml-policy-chain-1.yaml"), yaml);
- yaml = URLDecoder.decode(attributes.get(1).get(AttributeType.RULE).get("ControlLoopYaml"), "UTF-8");
+ yaml = URLDecoder.decode(attributes.get(1).get(AttributeType.RULE).get("controlLoopYaml"), "UTF-8");
yaml = replaceGeneratedValues(yaml);
assertEquals(ResourceFileUtil.getResourceAsString("example/operational-policy/yaml-policy-chain-2.yaml"), yaml);
}
fail("Exception should have been sent");
}
- @Test(expected = IllegalArgumentException.class)
- public void testValidateActionFromDelete() {
- CldsModel cldsModel = new CldsModel();
- cldsModel.getEvent().setActionCd(CldsEvent.ACTION_DELETE);
- cldsModel.validateAction(CldsEvent.ACTION_SUBMIT);
- try {
- cldsModel.validateAction(CldsEvent.ACTION_CREATE);
- fail("Exception should have been sent");
- } catch (IllegalArgumentException e) {
- System.out.println("Exception caught IllegalArgumentException as expected");
- }
- cldsModel.getEvent().setActionCd(CldsEvent.ACTION_DELETE);
- cldsModel.getEvent().setActionStateCd(CldsEvent.ACTION_STATE_SENT);
- cldsModel.validateAction(CldsEvent.ACTION_SUBMIT);
- fail("Exception should have been sent");
- }
-
@Test(expected = IllegalArgumentException.class)
public void testValidateActionFromStop() {
CldsModel cldsModel = new CldsModel();
package org.onap.clamp.clds.swagger;
import org.springframework.context.annotation.Configuration;
+
import springfox.documentation.builders.ApiInfoBuilder;
-import springfox.documentation.service.*;
-import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.service.ApiInfo;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
-
-
-
@EnableSwagger2
@Configuration
public class SwaggerConfig {
private ApiInfo apiInfo() {
- return new ApiInfoBuilder()
- .title("Clamp")
- .description("Clamp API Description")
- .license("Apache 2.0")
- .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
- .build();
+ return new ApiInfoBuilder().title("Clamp").description("Clamp API Description").license("Apache 2.0")
+ .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0").build();
}
}
* ============LICENSE_END============================================
* ===================================================================
*/
+
package org.onap.clamp.clds.swagger;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.onap.clamp.clds.Application;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import java.nio.file.Path;
-import java.nio.file.Paths;
+
import io.github.swagger2markup.Swagger2MarkupConverter;
-import org.onap.clamp.clds.Application;
@RunWith(SpringJUnit4ClassRunner.class)
-@SpringBootTest(classes = {Application.class, SwaggerConfig.class})
+@SpringBootTest(classes = {
+ Application.class, SwaggerConfig.class
+})
public class SwaggerGenerationTest {
@Test
+++ /dev/null
-org.onap.clamp.encryption.aes.key=aa3871669d893c7fb8abbcda31b88b4f
\ No newline at end of file
# Note that these variables cannot be structured (e.g. : version.release or version.snapshot etc... )
# because they are used in Jenkins, whose plug-in doesn't support
-major=2
+major=3
minor=0
-patch=2
+patch=0
base_version=${major}.${minor}.${patch}