diff options
Diffstat (limited to 'src/main/java')
29 files changed, 1135 insertions, 406 deletions
diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java b/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java index 3c8649cd3..9226604a1 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java @@ -31,8 +31,8 @@ import java.util.Date; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
-import org.onap.clamp.clds.config.CldsReferenceProperties;
-import org.onap.clamp.clds.exception.DcaeDeploymentException;
+import org.onap.clamp.clds.config.ClampProperties;
+import org.onap.clamp.clds.exception.dcae.DcaeDeploymentException;
import org.onap.clamp.clds.util.LoggingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -47,10 +47,10 @@ public class DcaeDispatcherServices { protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class);
protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
@Autowired
- private CldsReferenceProperties refProp;
+ private ClampProperties refProp;
private static final String STATUS_URL_LOG = "Status URL extracted: ";
private static final String DCAE_URL_PREFIX = "/dcae-deployments/";
- private static final String DCAE_URL_PROPERTY_NAME = "DCAE_DISPATCHER_URL";
+ private static final String DCAE_URL_PROPERTY_NAME = "dcae.dispatcher.url";
private static final String DCAE_REQUEST_FAILED_LOG = "RequestFailed - responseStr=";
public static final String DCAE_REQUESTID_PROPERTY_NAME = "dcae.header.requestId";
private static final String DCAE_LINK_FIELD = "links";
diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java index 1abd88985..c4abebdcd 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java @@ -41,7 +41,7 @@ import org.json.simple.JSONArray; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
-import org.onap.clamp.clds.config.CldsReferenceProperties;
+import org.onap.clamp.clds.config.ClampProperties;
import org.onap.clamp.clds.dao.CldsDao;
import org.onap.clamp.clds.model.CldsEvent;
import org.onap.clamp.clds.model.CldsModel;
@@ -61,9 +61,9 @@ public class DcaeInventoryServices { protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeInventoryServices.class);
protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
- private static final String DCAE_INVENTORY_URL = "DCAE_INVENTORY_URL";
+ private static final String DCAE_INVENTORY_URL = "dcae.inventory.url";
@Autowired
- private CldsReferenceProperties refProp;
+ private ClampProperties refProp;
@Autowired
private CldsDao cldsDao;
diff --git a/src/main/java/org/onap/clamp/clds/client/HolmesPolicyDelegate.java b/src/main/java/org/onap/clamp/clds/client/HolmesPolicyDelegate.java index 4e165e141..37259cdfe 100644 --- a/src/main/java/org/onap/clamp/clds/client/HolmesPolicyDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/HolmesPolicyDelegate.java @@ -31,7 +31,7 @@ import java.util.UUID; import org.apache.camel.Exchange; import org.apache.camel.Handler; import org.onap.clamp.clds.client.req.policy.PolicyClient; -import org.onap.clamp.clds.config.CldsReferenceProperties; +import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.model.properties.Holmes; import org.onap.clamp.clds.model.properties.ModelProperties; import org.springframework.beans.factory.annotation.Autowired; @@ -48,7 +48,7 @@ public class HolmesPolicyDelegate { @Autowired private PolicyClient policyClient; @Autowired - private CldsReferenceProperties refProp; + private ClampProperties refProp; /** * Perform activity. Send Holmes info to policy api. 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 ec83db9de..ae2880567 100644 --- a/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java @@ -33,7 +33,7 @@ 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.PolicyClient; -import org.onap.clamp.clds.config.CldsReferenceProperties; +import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.model.properties.Policy; import org.onap.clamp.clds.model.properties.PolicyChain; @@ -61,7 +61,7 @@ public class OperationalPolicyDelegate { * Automatically injected by Spring, define in CldsConfiguration as a bean. */ @Autowired - private CldsReferenceProperties refProp; + private ClampProperties refProp; /** * Perform activity. Send Operational Policy info to policy api. diff --git a/src/main/java/org/onap/clamp/clds/client/SdcSendReqDelegate.java b/src/main/java/org/onap/clamp/clds/client/SdcSendReqDelegate.java index 438ea4727..64e19f922 100644 --- a/src/main/java/org/onap/clamp/clds/client/SdcSendReqDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/SdcSendReqDelegate.java @@ -35,7 +35,7 @@ import org.apache.camel.Handler; import org.apache.commons.codec.DecoderException; import org.onap.clamp.clds.client.req.sdc.SdcCatalogServices; import org.onap.clamp.clds.client.req.sdc.SdcRequests; -import org.onap.clamp.clds.config.CldsReferenceProperties; +import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.model.DcaeEvent; import org.onap.clamp.clds.model.properties.Global; import org.onap.clamp.clds.model.properties.ModelProperties; @@ -55,7 +55,7 @@ public class SdcSendReqDelegate { @Autowired private SdcRequests sdcReq; @Autowired - private CldsReferenceProperties refProp; + private ClampProperties refProp; /** * Perform activity. Send to sdc proxy. diff --git a/src/main/java/org/onap/clamp/clds/client/TcaPolicyDelegate.java b/src/main/java/org/onap/clamp/clds/client/TcaPolicyDelegate.java index 55fe2c571..e16e8c35a 100644 --- a/src/main/java/org/onap/clamp/clds/client/TcaPolicyDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/TcaPolicyDelegate.java @@ -32,7 +32,7 @@ import org.apache.camel.Exchange; import org.apache.camel.Handler; import org.onap.clamp.clds.client.req.policy.PolicyClient; import org.onap.clamp.clds.client.req.tca.TcaRequestFormatter; -import org.onap.clamp.clds.config.CldsReferenceProperties; +import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.model.properties.Tca; import org.springframework.beans.factory.annotation.Autowired; @@ -47,7 +47,7 @@ public class TcaPolicyDelegate { protected static final EELFLogger logger = EELFManager.getInstance().getLogger(TcaPolicyDelegate.class); protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); @Autowired - private CldsReferenceProperties refProp; + private ClampProperties refProp; @Autowired private PolicyClient policyClient; 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/OperationalPolicyReq.java index 434da4b65..d3e8a5418 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/OperationalPolicyReq.java @@ -39,7 +39,7 @@ import java.util.Map; import javax.ws.rs.BadRequestException; -import org.onap.clamp.clds.config.CldsReferenceProperties; +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; @@ -80,7 +80,7 @@ public class OperationalPolicyReq { * @throws BuilderException * @throws UnsupportedEncodingException */ - public static Map<AttributeType, Map<String, String>> formatAttributes(CldsReferenceProperties refProp, ModelProperties prop, + public static Map<AttributeType, Map<String, String>> formatAttributes(ClampProperties refProp, ModelProperties prop, String modelElementId, PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException { Global global = prop.getGlobal(); prop.setCurrentModelElementId(modelElementId); @@ -163,7 +163,7 @@ public class OperationalPolicyReq { * @throws BuilderException * @throws UnsupportedEncodingException */ - protected static String formatOpenLoopYaml(CldsReferenceProperties refProp, ModelProperties prop, String modelElementId, + protected static String formatOpenLoopYaml(ClampProperties refProp, ModelProperties prop, String modelElementId, PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException { // get property objects Global global = prop.getGlobal(); @@ -193,7 +193,7 @@ public class OperationalPolicyReq { * @throws BuilderException * @throws UnsupportedEncodingException */ - protected static String formatYaml(CldsReferenceProperties refProp, ModelProperties prop, String modelElementId, + protected static String formatYaml(ClampProperties refProp, ModelProperties prop, String modelElementId, PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException { // get property objects Global global = prop.getGlobal(); @@ -251,7 +251,7 @@ public class OperationalPolicyReq { * @throws BuilderException * @throws UnsupportedEncodingException */ - protected static String formateNodeBYaml(CldsReferenceProperties refProp, ModelProperties prop, String modelElementId, + protected static String formateNodeBYaml(ClampProperties refProp, ModelProperties prop, String modelElementId, PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException { // get property objects Global global = prop.getGlobal(); @@ -329,7 +329,7 @@ public class OperationalPolicyReq { * @param inOrigList * @return */ - private static List<PolicyItem> addAOTSActorRecipe(CldsReferenceProperties refProp, String service, List<PolicyItem> inOrigList) { + private static List<PolicyItem> addAOTSActorRecipe(ClampProperties refProp, String service, List<PolicyItem> inOrigList) { List<PolicyItem> outList = new ArrayList<>(); try { PolicyItem policyItem = inOrigList.get(0); 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 06eff4ef7..144a48c92 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 @@ -37,7 +37,7 @@ import java.util.UUID; import javax.ws.rs.BadRequestException; -import org.onap.clamp.clds.config.CldsReferenceProperties; +import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.exception.policy.PolicyClientException; import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.util.LoggingUtils; @@ -71,12 +71,12 @@ public class PolicyClient { protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); protected static final String POLICY_MSTYPE_PROPERTY_NAME = "policy.ms.type"; protected static final String POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name"; - @Value("${org.onap.clamp.config.files.cldsPolicyConfig:'classpath:/clds/clds-policy-config.properties'}") + @Value("${clamp.config.files.cldsPolicyConfig:'classpath:/clds/clds-policy-config.properties'}") protected String cldsPolicyConfigFile; @Autowired protected ApplicationContext appContext; @Autowired - protected CldsReferenceProperties refProp; + protected ClampProperties refProp; /** * Perform BRMS policy type. diff --git a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java index 299ec1e9e..fd7d096fa 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java +++ b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcCatalogServices.java @@ -58,8 +58,8 @@ import org.apache.commons.csv.CSVRecord; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
-import org.onap.clamp.clds.config.CldsReferenceProperties;
-import org.onap.clamp.clds.exception.SdcCommunicationException;
+import org.onap.clamp.clds.config.ClampProperties;
+import org.onap.clamp.clds.exception.sdc.SdcCommunicationException;
import org.onap.clamp.clds.model.CldsAlarmCondition;
import org.onap.clamp.clds.model.CldsServiceData;
import org.onap.clamp.clds.model.CldsVfData;
@@ -72,6 +72,7 @@ import org.onap.clamp.clds.model.sdc.SdcResource; import org.onap.clamp.clds.model.sdc.SdcResourceBasicInfo;
import org.onap.clamp.clds.model.sdc.SdcServiceDetail;
import org.onap.clamp.clds.model.sdc.SdcServiceInfo;
+import org.onap.clamp.clds.service.CldsService;
import org.onap.clamp.clds.util.CryptoUtils;
import org.onap.clamp.clds.util.LoggingUtils;
import org.springframework.beans.factory.annotation.Autowired;
@@ -93,7 +94,7 @@ public class SdcCatalogServices { private static final String SDC_INSTANCE_ID_CLAMP = "CLAMP-Tool";
private static final String RESOURCE_URL_PREFIX = "resources";
@Autowired
- private CldsReferenceProperties refProp;
+ private ClampProperties refProp;
/**
* Return SDC id and pw as a HTTP Basic Auth string (for example: Basic
@@ -840,11 +841,13 @@ public class SdcCatalogServices { * @param globalProps
* @param cldsServiceData
* @return
+ * @throws IOException
+ * In case of issues during the parsing of the Global Properties
*/
- public String createPropertiesObjectByUUID(String globalProps, CldsServiceData cldsServiceData) {
+ public String createPropertiesObjectByUUID(CldsServiceData cldsServiceData) throws IOException {
String totalPropsStr;
ObjectMapper mapper = new ObjectMapper();
- ObjectNode globalPropsJson;
+ ObjectNode globalPropsJson = (ObjectNode) refProp.getJsonTemplate(CldsService.GLOBAL_PROPERTIES_KEY);
if (cldsServiceData != null && cldsServiceData.getServiceUUID() != null) {
// Objectnode to save all byservice, byvf , byvfc and byalarm nodes
ObjectNode byIdObjectNode = mapper.createObjectNode();
@@ -886,28 +889,13 @@ public class SdcCatalogServices { "alertDescription");
ObjectNode alertDescObjectNodeByAlert = createAlarmCondObjectNodeByAlarmKey(mapper, allAlertDescriptions);
byIdObjectNode.putPOJO("byAlertDescription", alertDescObjectNodeByAlert);
- globalPropsJson = decodeGlobalProp(globalProps, mapper);
globalPropsJson.putPOJO("shared", byIdObjectNode);
logger.info("Global properties JSON created with SDC info:" + globalPropsJson);
- } else {
- /**
- * to create json with total properties when no serviceUUID passed
- */
- globalPropsJson = decodeGlobalProp(globalProps, mapper);
}
totalPropsStr = globalPropsJson.toString();
return totalPropsStr;
}
- private ObjectNode decodeGlobalProp(String globalProps, ObjectMapper mapper) {
- try {
- return (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
- } catch (IOException e) {
- logger.error("Exception occurred during decoding of the global props, returning an empty objectNode", e);
- return mapper.createObjectNode();
- }
- }
-
/**
* Method to get alarm conditions/alert description from Service Data.
*
diff --git a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcRequests.java b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcRequests.java index 214933d49..e34b7e907 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcRequests.java +++ b/src/main/java/org/onap/clamp/clds/client/req/sdc/SdcRequests.java @@ -41,7 +41,7 @@ import java.util.Map.Entry; import org.apache.commons.codec.DecoderException; import org.onap.clamp.clds.client.req.tca.TcaRequestFormatter; -import org.onap.clamp.clds.config.CldsReferenceProperties; +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.Tca; @@ -61,7 +61,7 @@ public class SdcRequests { @Autowired private SdcCatalogServices sdcCatalogServices; @Autowired - protected CldsReferenceProperties refProp; + protected ClampProperties refProp; /** * Format the Blueprint from a Yaml diff --git a/src/main/java/org/onap/clamp/clds/client/req/tca/TcaRequestFormatter.java b/src/main/java/org/onap/clamp/clds/client/req/tca/TcaRequestFormatter.java index 73355a7a4..f51469159 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/tca/TcaRequestFormatter.java +++ b/src/main/java/org/onap/clamp/clds/client/req/tca/TcaRequestFormatter.java @@ -32,7 +32,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.util.Map; -import org.onap.clamp.clds.config.CldsReferenceProperties; +import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.exception.TcaRequestFormatterException; import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.model.properties.Tca; @@ -64,7 +64,7 @@ public class TcaRequestFormatter { * The Model Prop created from BPMN JSON and BPMN properties JSON * @return The Json string containing that should be sent to policy */ - public static String createPolicyJson(CldsReferenceProperties refProp, ModelProperties modelProperties) { + public static String createPolicyJson(ClampProperties refProp, ModelProperties modelProperties) { try { String service = modelProperties.getGlobal().getService(); Tca tca = modelProperties.getType(Tca.class); @@ -103,7 +103,7 @@ public class TcaRequestFormatter { * modelProperties.setCurrentModelElementId will be used * @return The Json node containing what should be sent to policy */ - public static JsonNode createPolicyContent(CldsReferenceProperties refProp, ModelProperties modelProperties, String service, + public static JsonNode createPolicyContent(ClampProperties refProp, ModelProperties modelProperties, String service, String policyName, Tca tca) { try { String serviceToUse = service; @@ -153,7 +153,7 @@ public class TcaRequestFormatter { * The Model Properties created from BPMN JSON and BPMN * properties JSON */ - private static void addThresholds(CldsReferenceProperties refProp, String service, ObjectNode appendToNode, TcaItem tcaItem, + private static void addThresholds(ClampProperties refProp, String service, ObjectNode appendToNode, TcaItem tcaItem, ModelProperties modelProperties) { ArrayNode tcaNodes = appendToNode.withArray("thresholds"); ObjectNode tcaNode; @@ -185,7 +185,7 @@ public class TcaRequestFormatter { * The yaml string received from the UI * @return The updated YAML as a string */ - public static String updatedBlueprintWithConfiguration(CldsReferenceProperties refProp, ModelProperties modelProperties, + public static String updatedBlueprintWithConfiguration(ClampProperties refProp, ModelProperties modelProperties, String yamlValue) { String jsonPolicy = ((ObjectNode) createPolicyContent(refProp, modelProperties, null, null, null)).toString(); logger.info("Yaml that will be updated:" + yamlValue); diff --git a/src/main/java/org/onap/clamp/clds/config/ClampProperties.java b/src/main/java/org/onap/clamp/clds/config/ClampProperties.java new file mode 100644 index 000000000..66f35acc6 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/config/ClampProperties.java @@ -0,0 +1,154 @@ +/*- + * ============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============================================ + * =================================================================== + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.clamp.clds.config; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.net.URL; +import java.nio.charset.StandardCharsets; + +import org.apache.commons.io.IOUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +/** + * Holds Clamp properties and add some functionalities. + */ +@Component +public class ClampProperties { + + @Autowired + private ApplicationContext appContext; + @Autowired + private Environment env; + public static final String CONFIG_PREFIX = "clamp.config."; + + /** + * get property value. + * + * @param key + * The first key + * @return The string with the value + */ + public String getStringValue(String key) { + return env.getProperty(CONFIG_PREFIX + key); + } + + /** + * get property value for a combo key (key1 + "." + key2). If not found just + * use key1. + * + * @param key1 + * The first key + * @param key2 + * The second key after a dot + * @return The string with the value + */ + public String getStringValue(String key1, String key2) { + String value = getStringValue(key1 + "." + key2); + if (value == null || value.length() == 0) { + value = getStringValue(key1); + } + return value; + } + + /** + * Return json as objects that can be updated. The value obtained from the + * clds-reference file will be used as a filename. + * + * @param key + * The key that will be used to access the clds-reference file + * @return A jsonNode + * @throws IOException + * In case of issues with the JSON parser + */ + public JsonNode getJsonTemplate(String key) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + String fileReference = getStringValue(key); + return (fileReference != null) ? objectMapper.readValue(getFileContentFromPath(fileReference), JsonNode.class) + : null; + } + + /** + * Return json as objects that can be updated. First try with combo key + * (key1 + "." + key2), otherwise default to just key1. The value obtained + * from the clds-reference file will be used as a filename. + * + * @param key1 + * The first key + * @param key2 + * The second key after a dot + * @return A JsonNode + * @throws IOException + * In case of issues with the JSON parser + */ + public JsonNode getJsonTemplate(String key1, String key2) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + String fileReference = getStringValue(key1, key2); + return (fileReference != null) ? objectMapper.readValue(getFileContentFromPath(fileReference), JsonNode.class) + : null; + } + + /** + * Return the file content. The value obtained from the clds-reference file + * will be used as a filename. + * + * @param key + * The key that will be used to access the clds-reference file + * @return File content in String + * @throws IOException + * In case of issues with the JSON parser + */ + public String getFileContent(String key) throws IOException { + String fileReference = getStringValue(key); + return (fileReference != null) ? getFileContentFromPath(fileReference) : null; + } + + /** + * Return the file content. First try with combo key (key1 + "." + key2), + * otherwise default to just key1. The value obtained from the + * clds-reference file will be used as a filename. + * + * @param key1 + * The first key + * @param key2 + * The second key after a dot + * @return File content in String + * @throws IOException + * In case of issues with the JSON parser + */ + public String getFileContent(String key1, String key2) throws IOException { + String fileReference = getStringValue(key1, key2); + return (fileReference != null) ? getFileContentFromPath(fileReference) : null; + } + + private String getFileContentFromPath(String filepath) throws IOException { + URL url = appContext.getResource(filepath).getURL(); + return IOUtils.toString(url, StandardCharsets.UTF_8); + } +} diff --git a/src/main/java/org/onap/clamp/clds/config/CldsReferenceProperties.java b/src/main/java/org/onap/clamp/clds/config/CldsReferenceProperties.java deleted file mode 100644 index a8acdee14..000000000 --- a/src/main/java/org/onap/clamp/clds/config/CldsReferenceProperties.java +++ /dev/null @@ -1,110 +0,0 @@ -/*- - * ============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============================================ - * =================================================================== - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ - -package org.onap.clamp.clds.config; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.util.Properties; - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.ApplicationContext; -import org.springframework.core.io.Resource; -import org.springframework.stereotype.Component; - -/** - * Holds reference properties. - */ -@Component -public class CldsReferenceProperties { - - @Autowired - private ApplicationContext appContext; - private Properties prop; - @Value("${org.onap.clamp.config.files.cldsReference:'classpath:/clds/clds-reference.properties'}") - private String cldsReferenceValuesFile; - - @PostConstruct - public void loadConfig() throws IOException { - prop = new Properties(); - Resource resource = appContext.getResource(cldsReferenceValuesFile); - prop.load(resource.getInputStream()); - } - - /** - * get property value - * - * @param key - * @return - */ - public String getStringValue(String key) { - return prop.getProperty(key); - } - - /** - * get property value for a combo key (key1 + "." + key2). If not found just - * use key1. - * - * @param key1 - * @param key2 - * @return - */ - public String getStringValue(String key1, String key2) { - String value = getStringValue(key1 + "." + key2); - if (value == null || value.length() == 0) { - value = getStringValue(key1); - } - return value; - } - - /** - * Return json as objects that can be updated - * - * @param key - * @return - * @throws IOException - */ - public JsonNode getJsonTemplate(String key) throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.readValue(getStringValue(key), JsonNode.class); - } - - /** - * Return json as objects that can be updated. First try with combo key - * (key1 + "." + key2), otherwise default to just key1. - * - * @param key1 - * @param key2 - * @return - * @throws IOException - */ - public JsonNode getJsonTemplate(String key1, String key2) throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.readValue(getStringValue(key1, key2), JsonNode.class); - } -} diff --git a/src/main/java/org/onap/clamp/clds/config/CldsUserJsonDecoder.java b/src/main/java/org/onap/clamp/clds/config/CldsUserJsonDecoder.java index 15d06b9af..bb1b9d139 100644 --- a/src/main/java/org/onap/clamp/clds/config/CldsUserJsonDecoder.java +++ b/src/main/java/org/onap/clamp/clds/config/CldsUserJsonDecoder.java @@ -27,11 +27,14 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import org.apache.commons.io.IOUtils; import org.onap.clamp.clds.exception.CldsUsersException; import org.onap.clamp.clds.service.CldsUser; public class CldsUserJsonDecoder { + /** * This method decodes the JSON file provided to a CldsUser Array. The * stream is closed after this call, this is not possible to reuse it. @@ -43,9 +46,17 @@ public class CldsUserJsonDecoder { */ public static CldsUser[] decodeJson(InputStream cldsUsersFile) { try { + return decodeJson(IOUtils.toString(cldsUsersFile, StandardCharsets.UTF_8.name())); + } catch (IOException e) { + throw new CldsUsersException("Exception occurred during the decoding of the clds-users.json", e); + } + } + + public static CldsUser[] decodeJson(String cldsUsersString) { + try { // the ObjectMapper readValue method closes the stream no need to do // it - return new ObjectMapper().readValue(cldsUsersFile, CldsUser[].class); + return new ObjectMapper().readValue(cldsUsersString, CldsUser[].class); } catch (IOException e) { throw new CldsUsersException("Exception occurred during the decoding of the clds-users.json", e); } diff --git a/src/main/java/org/onap/clamp/clds/config/sdc/SdcControllersConfiguration.java b/src/main/java/org/onap/clamp/clds/config/sdc/SdcControllersConfiguration.java new file mode 100644 index 000000000..5b5490426 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/config/sdc/SdcControllersConfiguration.java @@ -0,0 +1,94 @@ +/*- + * ============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============================================ + * =================================================================== + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.clamp.clds.config.sdc; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import javax.annotation.PostConstruct; + +import org.onap.clamp.clds.exception.sdc.controller.SdcParametersException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.Resource; +import org.springframework.stereotype.Component; + +/** + * This class maps the SDC config JSON file. This JSON can have multiple + * sdc-controller config. So the json is loaded in a static way and the instance + * must specify the controller name that it represents. + */ +@Component +public class SdcControllersConfiguration { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcControllersConfiguration.class); + public static final String CONTROLLER_SUBTREE_KEY = "sdc-connections"; + @Autowired + protected ApplicationContext appContext; + /** + * The file name that will be loaded by Spring. + */ + @Value("${clamp.config.files.sdcController:'classpath:/clds/sdc-controllers-config.json'}") + protected String sdcControllerFile; + /** + * The root of the JSON. + */ + private JsonNode jsonRootNode; + + @PostConstruct + public void loadConfiguration() throws IOException { + Resource resource = appContext.getResource(sdcControllerFile); + // Try to load json tree + jsonRootNode = new ObjectMapper().readValue(resource.getInputStream(), JsonNode.class); + } + + public SdcSingleControllerConfiguration getSdcSingleControllerConfiguration(String controllerName) { + Map<String, SdcSingleControllerConfiguration> controllerMap = getAllDefinedControllers(); + return controllerMap.get(controllerName); + } + + /** + * This method reads all Controllers configurations and returns them. + * + * @return A list of controller Names defined in the config + */ + public Map<String, SdcSingleControllerConfiguration> getAllDefinedControllers() { + Map<String, SdcSingleControllerConfiguration> result = new HashMap<>(); + if (jsonRootNode.get(CONTROLLER_SUBTREE_KEY) != null) { + jsonRootNode.get(CONTROLLER_SUBTREE_KEY).fields().forEachRemaining(entry -> result.put(entry.getKey(), + new SdcSingleControllerConfiguration(entry.getValue(), entry.getKey()))); + } else { + throw new SdcParametersException( + CONTROLLER_SUBTREE_KEY + " key not found in the file: " + sdcControllerFile); + } + return result; + } +} diff --git a/src/main/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfiguration.java b/src/main/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfiguration.java new file mode 100644 index 000000000..c97beb08d --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/config/sdc/SdcSingleControllerConfiguration.java @@ -0,0 +1,285 @@ +/*- + * ============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============================================ + * =================================================================== + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.clamp.clds.config.sdc; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.fasterxml.jackson.databind.JsonNode; + +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.codec.DecoderException; +import org.onap.clamp.clds.exception.sdc.controller.SdcParametersException; +import org.onap.clamp.clds.util.CryptoUtils; +import org.openecomp.sdc.api.consumer.IConfiguration; + +/** + * This class maps the SDC config JSON for one controller. + */ +public class SdcSingleControllerConfiguration implements IConfiguration { + + private static final EELFLogger logger = EELFManager.getInstance() + .getLogger(SdcSingleControllerConfiguration.class); + /** + * The sdc Controller name corresponding. + */ + private String sdcControllerName; + /** + * The root of the JSON. + */ + private JsonNode jsonRootNode; + // All keys that can be present in the JSON + public static final String CONSUMER_GROUP_ATTRIBUTE_NAME = "consumerGroup"; + public static final String CONSUMER_ID_ATTRIBUTE_NAME = "consumerId"; + public static final String ENVIRONMENT_NAME_ATTRIBUTE_NAME = "environmentName"; + public static final String PASSWORD_ATTRIBUTE_NAME = "password"; + public static final String POLLING_INTERVAL_ATTRIBUTE_NAME = "pollingInterval"; + public static final String RELEVANT_ARTIFACT_TYPES_ATTRIBUTE_NAME = "relevantArtifactTypes"; + public static final String USER_ATTRIBUTE_NAME = "user"; + public static final String SDC_ADDRESS_ATTRIBUTE_NAME = "sdcAddress"; + public static final String POLLING_TIMEOUT_ATTRIBUTE_NAME = "pollingTimeout"; + public static final String ACTIVATE_SERVER_TLS_AUTH = "activateServerTLSAuth"; + public static final String KEY_STORE_PASSWORD = "keyStorePassword"; + public static final String KEY_STORE_PATH = "keyStorePath"; + private String errorMessageKeyNotFound; + /** + * Supported artifact types. + */ + public static final String HEAT = "HEAT"; + public static final String HEAT_ARTIFACT = "HEAT_ARTIFACT"; + public static final String HEAT_ENV = "HEAT_ENV"; + public static final String HEAT_NESTED = "HEAT_NESTED"; + public static final String HEAT_NET = "HEAT_NET"; + public static final String HEAT_VOL = "HEAT_VOL"; + public static final String OTHER = "OTHER"; + public static final String TOSCA_CSAR = "TOSCA_CSAR"; + public static final String VF_MODULES_METADATA = "VF_MODULES_METADATA"; + private static final String[] SUPPORTED_ARTIFACT_TYPES = { + HEAT, HEAT_ARTIFACT, HEAT_ENV, HEAT_NESTED, HEAT_NET, HEAT_VOL, OTHER, TOSCA_CSAR, VF_MODULES_METADATA + }; + public static final List<String> SUPPORTED_ARTIFACT_TYPES_LIST = Collections + .unmodifiableList(Arrays.asList(SUPPORTED_ARTIFACT_TYPES)); + + /** + * This constructor builds a SdcSingleControllerConfiguration from the + * corresponding json. + * + * @param jsonRootNode + * The JSON node + * @param controllerName + * The controller name that must appear in the JSON + */ + public SdcSingleControllerConfiguration(JsonNode jsonNode, String controllerName) { + jsonRootNode = jsonNode; + setSdcControllerName(controllerName); + testAllRequiredParameters(); + } + + public String getSdcControllerName() { + return sdcControllerName; + } + + public void setSdcControllerName(String controllerName) { + this.sdcControllerName = controllerName; + errorMessageKeyNotFound = " parameter cannot be found in config file for controller name" + sdcControllerName; + testAllRequiredParameters(); + } + + @Override + public java.lang.Boolean isUseHttpsWithDmaap() { + return false; + } + + @Override + public String getConsumerGroup() { + if (jsonRootNode != null && jsonRootNode.get(CONSUMER_GROUP_ATTRIBUTE_NAME) != null) { + String config = jsonRootNode.get(CONSUMER_GROUP_ATTRIBUTE_NAME).asText(); + return "NULL".equals(config) || config.isEmpty() ? null : config; + } + return null; + } + + @Override + public String getConsumerID() { + if (jsonRootNode != null && jsonRootNode.get(CONSUMER_ID_ATTRIBUTE_NAME) != null) { + String config = jsonRootNode.get(CONSUMER_ID_ATTRIBUTE_NAME).asText(); + return config.isEmpty() ? null : config; + } + return null; + } + + @Override + public String getEnvironmentName() { + if (jsonRootNode != null && jsonRootNode.get(ENVIRONMENT_NAME_ATTRIBUTE_NAME) != null) { + String config = jsonRootNode.get(ENVIRONMENT_NAME_ATTRIBUTE_NAME).asText(); + return config.isEmpty() ? null : config; + } + return null; + } + + @Override + public String getPassword() { + try { + if (jsonRootNode != null && jsonRootNode.get(PASSWORD_ATTRIBUTE_NAME) != null) { + String config = CryptoUtils.decrypt(jsonRootNode.get(PASSWORD_ATTRIBUTE_NAME).asText()); + return config.isEmpty() ? null : config; + } + } catch (GeneralSecurityException | DecoderException e) { + logger.error("Unable to decrypt the SDC password", e); + } + return null; + } + + @Override + public int getPollingInterval() { + if (jsonRootNode != null && jsonRootNode.get(POLLING_INTERVAL_ATTRIBUTE_NAME) != null) { + return jsonRootNode.get(POLLING_INTERVAL_ATTRIBUTE_NAME).asInt(); + } else { + return 0; + } + } + + @Override + public List<String> getRelevantArtifactTypes() { + // DO not return the Static List SUPPORTED_ARTIFACT_TYPES_LIST because + // the ASDC Client could try to modify it !!! + return Arrays.asList(SUPPORTED_ARTIFACT_TYPES); + } + + @Override + public String getUser() { + if (jsonRootNode != null && jsonRootNode.get(USER_ATTRIBUTE_NAME) != null) { + String config = jsonRootNode.get(USER_ATTRIBUTE_NAME).asText(); + return config.isEmpty() ? null : config; + } + return null; + } + + @Override + public String getAsdcAddress() { + if (jsonRootNode != null && jsonRootNode.get(SDC_ADDRESS_ATTRIBUTE_NAME) != null) { + String config = jsonRootNode.get(SDC_ADDRESS_ATTRIBUTE_NAME).asText(); + return config.isEmpty() ? null : config; + } + return null; + } + + @Override + public int getPollingTimeout() { + if (jsonRootNode != null && jsonRootNode.get(POLLING_TIMEOUT_ATTRIBUTE_NAME) != null) { + return jsonRootNode.get(POLLING_TIMEOUT_ATTRIBUTE_NAME).asInt(); + } else { + return 0; + } + } + + @Override + public boolean activateServerTLSAuth() { + if (jsonRootNode != null && jsonRootNode.get(ACTIVATE_SERVER_TLS_AUTH) != null) { + return jsonRootNode.get(ACTIVATE_SERVER_TLS_AUTH).asBoolean(false); + } else { + return false; + } + } + + @Override + public String getKeyStorePassword() { + try { + if (jsonRootNode != null && jsonRootNode.get(KEY_STORE_PASSWORD) != null) { + String config = CryptoUtils.decrypt(jsonRootNode.get(KEY_STORE_PASSWORD).asText()); + return config.isEmpty() ? null : config; + } + } catch (GeneralSecurityException | DecoderException e) { + logger.error("Unable to decrypt the SDC password", e); + } + return null; + } + + @Override + public String getKeyStorePath() { + if (jsonRootNode != null && jsonRootNode.get(KEY_STORE_PATH) != null) { + String config = jsonRootNode.get(KEY_STORE_PATH).asText(); + return config.isEmpty() ? null : config; + } + return null; + } + + /** + * This method can be used to validate all required parameters are well + * there. + */ + public void testAllRequiredParameters() { + // Special case for this attribute that can be null from + // getConsumerGroup + if (jsonRootNode == null) { + throw new SdcParametersException("Json is null for controller " + this.getSdcControllerName()); + } + if (this.getConsumerGroup() == null && (jsonRootNode.get(CONSUMER_GROUP_ATTRIBUTE_NAME) == null + || !"NULL".equals(jsonRootNode.get(CONSUMER_GROUP_ATTRIBUTE_NAME).asText()))) { + throw new SdcParametersException(CONSUMER_GROUP_ATTRIBUTE_NAME + errorMessageKeyNotFound); + } + if (this.getConsumerID() == null || this.getConsumerID().isEmpty()) { + throw new SdcParametersException(CONSUMER_ID_ATTRIBUTE_NAME + errorMessageKeyNotFound); + } + if (this.getEnvironmentName() == null || this.getEnvironmentName().isEmpty()) { + throw new SdcParametersException(ENVIRONMENT_NAME_ATTRIBUTE_NAME + errorMessageKeyNotFound); + } + if (this.getAsdcAddress() == null || this.getAsdcAddress().isEmpty()) { + throw new SdcParametersException(SDC_ADDRESS_ATTRIBUTE_NAME + errorMessageKeyNotFound); + } + if (this.getPassword() == null || this.getPassword().isEmpty()) { + throw new SdcParametersException(PASSWORD_ATTRIBUTE_NAME + errorMessageKeyNotFound); + } + if (this.getPollingInterval() == 0) { + throw new SdcParametersException(POLLING_INTERVAL_ATTRIBUTE_NAME + errorMessageKeyNotFound); + } + if (this.getPollingTimeout() == 0) { + throw new SdcParametersException(POLLING_TIMEOUT_ATTRIBUTE_NAME + errorMessageKeyNotFound); + } + if (this.getRelevantArtifactTypes() == null || this.getRelevantArtifactTypes().isEmpty()) { + throw new SdcParametersException(RELEVANT_ARTIFACT_TYPES_ATTRIBUTE_NAME + errorMessageKeyNotFound); + } + if (this.getUser() == null || this.getUser().isEmpty()) { + throw new SdcParametersException(USER_ATTRIBUTE_NAME + errorMessageKeyNotFound); + } + } + + /** + * The flag allows the client to receive metadata for all resources of the + * service regardless of the artifacts associated to them. Setting the flag + * to false will preserve legacy behavior. + */ + @Override + public boolean isFilterInEmptyResources() { + return true; + } + + @Override + public List<String> getMsgBusAddress() { + return null; + } +} diff --git a/src/main/java/org/onap/clamp/clds/config/CldsConfiguration.java b/src/main/java/org/onap/clamp/clds/config/spring/CldsConfiguration.java index ae9704109..7ba5b1c73 100644 --- a/src/main/java/org/onap/clamp/clds/config/CldsConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/spring/CldsConfiguration.java @@ -21,11 +21,12 @@ * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -package org.onap.clamp.clds.config; +package org.onap.clamp.clds.config.spring; import javax.sql.DataSource; import javax.xml.transform.TransformerConfigurationException; +import org.onap.clamp.clds.config.EncodedPasswordBasicDataSource; import org.onap.clamp.clds.dao.CldsDao; import org.onap.clamp.clds.transform.XslTransformer; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/src/main/java/org/onap/clamp/clds/config/CldsSecurityConfigUsers.java b/src/main/java/org/onap/clamp/clds/config/spring/CldsSecurityConfigUsers.java index db99dbaf4..d9e5ef298 100644 --- a/src/main/java/org/onap/clamp/clds/config/CldsSecurityConfigUsers.java +++ b/src/main/java/org/onap/clamp/clds/config/spring/CldsSecurityConfigUsers.java @@ -21,18 +21,19 @@ * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -package org.onap.clamp.clds.config; +package org.onap.clamp.clds.config.spring; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import java.io.IOException; +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.clds.config.CldsUserJsonDecoder; import org.onap.clamp.clds.exception.CldsUsersException; import org.onap.clamp.clds.service.CldsUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; @@ -43,29 +44,21 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur /** * This class is used to enable the HTTP authentication to login. It requires a * specific JSON file containing the user definition - * (classpath:etc/config/clds/clds-users.json). - * + * (classpath:clds/clds-users.json). */ @Configuration @EnableWebSecurity @Profile("clamp-spring-authentication") public class CldsSecurityConfigUsers extends WebSecurityConfigurerAdapter { - protected static final EELFLogger logger = EELFManager.getInstance() - .getLogger(CldsSecurityConfigUsers.class); + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsSecurityConfigUsers.class); protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - @Autowired - private ApplicationContext appContext; - - @Value("${org.onap.clamp.config.files.cldsUsers:'classpath:etc/config/clds/clds-users.json'}") - private String cldsUsersFile; - - @Value("${CLDS_PERMISSION_TYPE_CL:permission-type-cl}") - private String cldsPersmissionTypeCl; - + private ClampProperties refProp; + @Value("${clamp.config.security.permission.type.cl:permission-type-cl}") + private String cldsPersmissionTypeCl; @Value("${CLDS_PERMISSION_INSTANCE:dev}") - private String cldsPermissionInstance; + private String cldsPermissionInstance; /** * This method configures on which URL the authorization will be enabled. @@ -92,13 +85,11 @@ public class CldsSecurityConfigUsers extends WebSecurityConfigurerAdapter { public void configureGlobal(AuthenticationManagerBuilder auth) { try { CldsUser[] usersList = loadUsers(); - // no users defined if (null == usersList) { - logger.warn("No users defined. Users should be defined under " + cldsUsersFile); + logger.warn("No users defined. Users should be defined under clds-users.json"); return; } - for (CldsUser user : usersList) { auth.inMemoryAuthentication().withUser(user.getUser()).password(user.getPassword()) .roles(user.getPermissionsString()); @@ -114,14 +105,11 @@ public class CldsSecurityConfigUsers extends WebSecurityConfigurerAdapter { * CldsUser. * * @return The array of CldsUser + * @throws IOException + * In case of the file is not found */ - private CldsUser[] loadUsers() { - try { - logger.info("Load from clds-users.properties"); - return CldsUserJsonDecoder.decodeJson(appContext.getResource(cldsUsersFile).getInputStream()); - } catch (IOException e) { - logger.error("Unable to decode the User Json file", e); - throw new CldsUsersException("Load from clds-users.properties", e); - } + private CldsUser[] loadUsers() throws IOException { + logger.info("Load from clds-users.properties"); + return CldsUserJsonDecoder.decodeJson(refProp.getFileContent("files.cldsUsers")); } } diff --git a/src/main/java/org/onap/clamp/clds/exception/DcaeDeploymentException.java b/src/main/java/org/onap/clamp/clds/exception/dcae/DcaeDeploymentException.java index 6a60ac9d9..4cafe794e 100644 --- a/src/main/java/org/onap/clamp/clds/exception/DcaeDeploymentException.java +++ b/src/main/java/org/onap/clamp/clds/exception/dcae/DcaeDeploymentException.java @@ -21,7 +21,7 @@ * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -package org.onap.clamp.clds.exception; +package org.onap.clamp.clds.exception.dcae; /** * New exception to capture DCAE communication errors. diff --git a/src/main/java/org/onap/clamp/clds/exception/SdcCommunicationException.java b/src/main/java/org/onap/clamp/clds/exception/sdc/SdcCommunicationException.java index 429ab8dff..a38284399 100644 --- a/src/main/java/org/onap/clamp/clds/exception/SdcCommunicationException.java +++ b/src/main/java/org/onap/clamp/clds/exception/sdc/SdcCommunicationException.java @@ -21,7 +21,7 @@ * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -package org.onap.clamp.clds.exception; +package org.onap.clamp.clds.exception.sdc; /** * New exception to capture SDC communication errors. diff --git a/src/main/java/org/onap/clamp/clds/exception/sdc/controller/SdcArtifactInstallerException.java b/src/main/java/org/onap/clamp/clds/exception/sdc/controller/SdcArtifactInstallerException.java new file mode 100644 index 000000000..973081c27 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/exception/sdc/controller/SdcArtifactInstallerException.java @@ -0,0 +1,55 @@ +/*- + * ============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============================================ + * =================================================================== + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.clamp.clds.exception.sdc.controller; + +/** + * Exception during SDC artifact installation. + */ +public class SdcArtifactInstallerException extends Exception { + + /** + * serialization id. + */ + private static final long serialVersionUID = 4095937499475915021L; + + /** + * @param message + * The message to dump + * @param cause + * The Throwable cause object + */ + public SdcArtifactInstallerException(final String message) { + super(message); + } + + /** + * @param message + * The message to dump + * @param cause + * The Throwable cause object + */ + public SdcArtifactInstallerException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/org/onap/clamp/clds/exception/sdc/controller/SdcControllerException.java b/src/main/java/org/onap/clamp/clds/exception/sdc/controller/SdcControllerException.java new file mode 100644 index 000000000..9c347572f --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/exception/sdc/controller/SdcControllerException.java @@ -0,0 +1,55 @@ +/*- + * ============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============================================ + * =================================================================== + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.clamp.clds.exception.sdc.controller; + +/** + * Exception of the SDC controller. + */ +public class SdcControllerException extends Exception { + + /** + * serialization id. + */ + private static final long serialVersionUID = -4236006447255525130L; + + /** + * @param message + * The message to dump + * @param cause + * The Throwable cause object + */ + public SdcControllerException(final String message) { + super(message); + } + + /** + * @param message + * The message to dump + * @param cause + * The Throwable cause object + */ + public SdcControllerException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/org/onap/clamp/clds/exception/sdc/controller/SdcDownloadException.java b/src/main/java/org/onap/clamp/clds/exception/sdc/controller/SdcDownloadException.java new file mode 100644 index 000000000..bace1ac48 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/exception/sdc/controller/SdcDownloadException.java @@ -0,0 +1,55 @@ +/*- + * ============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============================================ + * =================================================================== + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.clamp.clds.exception.sdc.controller; + +/** + * Exception during download from SDC. + */ +public class SdcDownloadException extends Exception { + + /** + * serialization id. + */ + private static final long serialVersionUID = -5276848693231134901L; + + /** + * @param message + * The message to dump + * @param cause + * The Throwable cause object + */ + public SdcDownloadException(final String message) { + super(message); + } + + /** + * @param message + * The message to dump + * @param cause + * The Throwable cause object + */ + public SdcDownloadException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/org/onap/clamp/clds/exception/sdc/controller/SdcParametersException.java b/src/main/java/org/onap/clamp/clds/exception/sdc/controller/SdcParametersException.java new file mode 100644 index 000000000..6ff0f1546 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/exception/sdc/controller/SdcParametersException.java @@ -0,0 +1,55 @@ +/*- + * ============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============================================ + * =================================================================== + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.clamp.clds.exception.sdc.controller; + +/** + * Exception of the SDC controller. + */ +public class SdcParametersException extends RuntimeException { + + /** + * serialization id. + */ + private static final long serialVersionUID = 8425657297510362736L; + + /** + * @param message + * The message to dump + * @param cause + * The Throwable cause object + */ + public SdcParametersException(final String message) { + super(message); + } + + /** + * @param message + * The message to dump + * @param cause + * The Throwable cause object + */ + public SdcParametersException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/DistributionStatusMessage.java b/src/main/java/org/onap/clamp/clds/sdc/controller/DistributionStatusMessage.java new file mode 100644 index 000000000..db5d271b0 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/DistributionStatusMessage.java @@ -0,0 +1,70 @@ +/*- + * ============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============================================ + * =================================================================== + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.clamp.clds.sdc.controller; + +import org.openecomp.sdc.api.consumer.IDistributionStatusMessage; +import org.openecomp.sdc.utils.DistributionStatusEnum; + +public class DistributionStatusMessage implements IDistributionStatusMessage { + + private String artifactURL; + private String consumerID; + private String distributionID; + private DistributionStatusEnum distributionStatus; + private long timestamp; + + public DistributionStatusMessage(final String artifactUrl, final String consumerId, final String distributionId, + final DistributionStatusEnum distributionStatusEnum, final long timestampL) { + artifactURL = artifactUrl; + consumerID = consumerId; + distributionID = distributionId; + distributionStatus = distributionStatusEnum; + timestamp = timestampL; + } + + @Override + public String getArtifactURL() { + return artifactURL; + } + + @Override + public String getConsumerID() { + return consumerID; + } + + @Override + public String getDistributionID() { + return distributionID; + } + + @Override + public DistributionStatusEnum getStatus() { + return distributionStatus; + } + + @Override + public long getTimestamp() { + return timestamp; + } +} diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleControllerStatus.java b/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleControllerStatus.java new file mode 100644 index 000000000..8fbf41614 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleControllerStatus.java @@ -0,0 +1,28 @@ +/*- + * ============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============================================ + * =================================================================== + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.clamp.clds.sdc.controller; + +public enum SdcSingleControllerStatus { + STOPPED, IDLE, BUSY +} 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 14e65627f..d22a5188b 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -34,9 +34,7 @@ import java.io.InputStream; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -54,6 +52,7 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import javax.xml.transform.TransformerException; import org.apache.camel.Produce; @@ -64,11 +63,11 @@ import org.onap.clamp.clds.camel.CamelProxy; import org.onap.clamp.clds.client.DcaeDispatcherServices; import org.onap.clamp.clds.client.DcaeInventoryServices; import org.onap.clamp.clds.client.req.sdc.SdcCatalogServices; -import org.onap.clamp.clds.config.CldsReferenceProperties; +import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.dao.CldsDao; import org.onap.clamp.clds.exception.CldsConfigException; -import org.onap.clamp.clds.exception.SdcCommunicationException; import org.onap.clamp.clds.exception.policy.PolicyClientException; +import org.onap.clamp.clds.exception.sdc.SdcCommunicationException; import org.onap.clamp.clds.model.CLDSMonitoringDetails; import org.onap.clamp.clds.model.CldsDBServiceCache; import org.onap.clamp.clds.model.CldsEvent; @@ -89,7 +88,6 @@ import org.onap.clamp.clds.transform.XslTransformer; import org.onap.clamp.clds.util.LoggingUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpClientErrorException; @@ -104,20 +102,19 @@ public class CldsService extends SecureServiceBase { @Produce(uri = "direct:processSubmit") private CamelProxy camelProxy; protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger(); - @Autowired - private ApplicationContext appContext; private static final String RESOURCE_NAME = "clds-version.properties"; - @Value("${CLDS_PERMISSION_TYPE_CL:permission-type-cl}") + public static final String GLOBAL_PROPERTIES_KEY = "files.globalProperties"; + @Value("${clamp.config.security.permission.type.cl:permission-type-cl}") private String cldsPersmissionTypeCl; - @Value("${CLDS_PERMISSION_TYPE_CL_MANAGE:permission-type-cl-manage}") + @Value("${clamp.config.security.permission.type.cl.manage:permission-type-cl-manage}") private String cldsPermissionTypeClManage; - @Value("${CLDS_PERMISSION_TYPE_CL_EVENT:permission-type-cl-event}") + @Value("${clamp.config.security.permission.type.cl.event:permission-type-cl-event}") private String cldsPermissionTypeClEvent; - @Value("${CLDS_PERMISSION_TYPE_FILTER_VF:permission-type-filter-vf}") + @Value("${clamp.config.security.permission.type.filter.vf:permission-type-filter-vf}") private String cldsPermissionTypeFilterVf; - @Value("${CLDS_PERMISSION_TYPE_TEMPLATE:permission-type-template}") + @Value("${clamp.config.security.permission.type.template:permission-type-template}") private String cldsPermissionTypeTemplate; - @Value("${CLDS_PERMISSION_INSTANCE:dev}") + @Value("${clamp.config.security.permission.instance:dev}") private String cldsPermissionInstance; private SecureServicePermission permissionReadCl; private SecureServicePermission permissionUpdateCl; @@ -134,15 +131,12 @@ public class CldsService extends SecureServiceBase { "update"); } - @Value("${org.onap.clamp.config.files.globalClds:'classpath:/clds/globalClds.properties'}") - private String globalClds; - private Properties globalCldsProperties; @Autowired private CldsDao cldsDao; @Autowired private XslTransformer cldsBpmnTransformer; @Autowired - private CldsReferenceProperties refProp; + private ClampProperties refProp; @Autowired private SdcCatalogServices sdcCatalogServices; @Autowired @@ -214,7 +208,7 @@ public class CldsService extends SecureServiceBase { /** * REST service that retrieves clds healthcheck information. - * + * * @return CldsHealthCheck class containing healthcheck info */ @GET @@ -348,6 +342,9 @@ public class CldsService extends SecureServiceBase { if (template != null) { cldsModel.setTemplateId(template.getId()); cldsModel.setDocText(template.getPropText()); + // This is to provide the Bpmn XML when Template part in UI is + // disabled + cldsModel.setBpmnText(template.getBpmnText()); } } cldsModel.save(cldsDao, getUserId()); @@ -400,105 +397,106 @@ public class CldsService extends SecureServiceBase { @Path("/action/{action}/{modelName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - public CldsModel putModelAndProcessAction(@PathParam("action") String action, + public Response putModelAndProcessAction(@PathParam("action") String action, @PathParam("modelName") String modelName, @QueryParam("test") String test, CldsModel model) throws TransformerException, ParseException, GeneralSecurityException, DecoderException { Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsService: Process model action", getPrincipalName()); - String actionCd = action.toUpperCase(); - SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage, - cldsPermissionInstance, actionCd); - isAuthorized(permisionManage); - isAuthorizedForVf(model); - String userId = getUserId(); - String actionStateCd = CldsEvent.ACTION_STATE_INITIATED; - String processDefinitionKey = "clds-process-action-wf"; - logger.info("PUT actionCd={}", actionCd); - logger.info("PUT actionStateCd={}", actionStateCd); - logger.info("PUT processDefinitionKey={}", processDefinitionKey); - logger.info("PUT modelName={}", modelName); - logger.info("PUT test={}", test); - logger.info("PUT bpmnText={}", model.getBpmnText()); - logger.info("PUT propText={}", model.getPropText()); - logger.info("PUT userId={}", userId); - logger.info("PUT getTypeId={}", model.getTypeId()); - logger.info("PUT deploymentId={}", model.getDeploymentId()); - if (model.getTemplateName() != null) { - CldsTemplate template = cldsDao.getTemplate(model.getTemplateName()); - if (template != null) { - model.setTemplateId(template.getId()); - model.setDocText(template.getPropText()); + CldsModel retrievedModel = null; + Boolean errorCase = false; + try { + LoggingUtils.setRequestContext("CldsService: Process model action", getPrincipalName()); + String actionCd = action.toUpperCase(); + SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage, + cldsPermissionInstance, actionCd); + isAuthorized(permisionManage); + isAuthorizedForVf(model); + String userId = getUserId(); + String actionStateCd = CldsEvent.ACTION_STATE_INITIATED; + String processDefinitionKey = "clds-process-action-wf"; + logger.info("PUT actionCd={}", actionCd); + logger.info("PUT actionStateCd={}", actionStateCd); + logger.info("PUT processDefinitionKey={}", processDefinitionKey); + logger.info("PUT modelName={}", modelName); + logger.info("PUT test={}", test); + logger.info("PUT bpmnText={}", model.getBpmnText()); + logger.info("PUT propText={}", model.getPropText()); + logger.info("PUT userId={}", userId); + logger.info("PUT getTypeId={}", model.getTypeId()); + logger.info("PUT deploymentId={}", model.getDeploymentId()); + if (model.getTemplateName() != null) { + CldsTemplate template = cldsDao.getTemplate(model.getTemplateName()); + if (template != null) { + model.setTemplateId(template.getId()); + model.setDocText(template.getPropText()); + // This is to provide the Bpmn XML when Template part in UI is + // disabled + model.setBpmnText(template.getBpmnText()); + } } - } - // save model to db - model.setName(modelName); - model.save(cldsDao, getUserId()); - // get vars and format if necessary - String prop = model.getPropText(); - String bpmn = model.getBpmnText(); - String docText = model.getDocText(); - String controlName = model.getControlName(); - String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn); - logger.info("PUT bpmnJson={}", bpmnJson); - // Flag indicates whether it is triggered by Validation Test button from - // UI - boolean isTest = false; - if (test != null && test.equalsIgnoreCase("true")) { - isTest = true; - } else { - String actionTestOverride = refProp.getStringValue("action.test.override"); - if (actionTestOverride != null && actionTestOverride.equalsIgnoreCase("true")) { - logger.info("PUT actionTestOverride={}", actionTestOverride); - logger.info("PUT override test indicator and setting it to true"); + // save model to db + model.setName(modelName); + model.save(cldsDao, getUserId()); + // get vars and format if necessary + String prop = model.getPropText(); + String bpmn = model.getBpmnText(); + String docText = model.getDocText(); + String controlName = model.getControlName(); + String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn); + logger.info("PUT bpmnJson={}", bpmnJson); + // Flag indicates whether it is triggered by Validation Test button from + // UI + boolean isTest = false; + if (test != null && test.equalsIgnoreCase("true")) { isTest = true; + } else { + String actionTestOverride = refProp.getStringValue("action.test.override"); + if (actionTestOverride != null && actionTestOverride.equalsIgnoreCase("true")) { + logger.info("PUT actionTestOverride={}", actionTestOverride); + logger.info("PUT override test indicator and setting it to true"); + isTest = true; + } } + logger.info("PUT isTest={}", isTest); + boolean isInsertTestEvent = false; + String insertTestEvent = refProp.getStringValue("action.insert.test.event"); + if (insertTestEvent != null && insertTestEvent.equalsIgnoreCase("true")) { + isInsertTestEvent = true; + } + logger.info("PUT isInsertTestEvent={}", isInsertTestEvent); + // determine if requested action is permitted + model.validateAction(actionCd); + logger.info("modelProp - " + prop); + logger.info("docText - " + docText); + try { + String result = camelProxy.submit(actionCd, prop, bpmnJson, modelName, controlName, docText, isTest, userId, + isInsertTestEvent); + 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 (!isTest && (actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMIT) + || actionCd.equalsIgnoreCase(CldsEvent.ACTION_RESUBMIT) + || actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE))) { + // To verify inventory status and modify model status to distribute + dcaeInventoryServices.setEventInventory(retrievedModel, getUserId()); + retrievedModel.save(cldsDao, getUserId()); + } + // audit log + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", "Process model action success", this.getClass().getName()); + auditLogger.info("Process model action completed"); + } catch (Exception e) { + errorCase = true; + logger.error("Exception occured during putModelAndProcessAction", e); } - logger.info("PUT isTest={}", isTest); - boolean isInsertTestEvent = false; - String insertTestEvent = refProp.getStringValue("action.insert.test.event"); - if (insertTestEvent != null && insertTestEvent.equalsIgnoreCase("true")) { - isInsertTestEvent = true; - } - logger.info("PUT isInsertTestEvent={}", isInsertTestEvent); - // determine if requested action is permitted - model.validateAction(actionCd); - // input variables for Camel process - Map<String, Object> variables = new HashMap<>(); - variables.put("actionCd", actionCd); - variables.put("modelProp", prop.getBytes()); - variables.put("modelBpmnProp", bpmnJson); - variables.put("modelName", modelName); - variables.put("controlName", controlName); - variables.put("docText", docText.getBytes()); - variables.put("isTest", isTest); - variables.put("userid", userId); - variables.put("isInsertTestEvent", isInsertTestEvent); - logger.info("modelProp - " + prop); - logger.info("docText - " + docText); - // ModelProperties modelProperties = new ModelProperties(modelName, - // controlName, actionCd, isTest, modelBpmnProp, modelProp); - try { - String result = camelProxy.submit(actionCd, prop, bpmnJson, modelName, controlName, docText, isTest, userId, - isInsertTestEvent); - logger.info("Starting Camel flow on request, result is: ", result); - } catch (SdcCommunicationException | PolicyClientException | BadRequestException e) { - logger.error("Exception occured during invoking Camel process", e); - throw new CldsConfigException(e.getMessage(), e); - } - // refresh model info from db (get fresh event info) - CldsModel retreivedModel = CldsModel.retrieve(cldsDao, modelName, false); - if (!isTest && (actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMIT) - || actionCd.equalsIgnoreCase(CldsEvent.ACTION_RESUBMIT) - || actionCd.equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE))) { - // To verify inventory status and modify model status to distribute - dcaeInventoryServices.setEventInventory(retreivedModel, getUserId()); - retreivedModel.save(cldsDao, getUserId()); + + if (errorCase) { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(retrievedModel).build(); } - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Process model action success", this.getClass().getName()); - auditLogger.info("Process model action completed"); - return retreivedModel; + return Response.status(Response.Status.OK).entity(retrievedModel).build(); } /** @@ -556,7 +554,7 @@ public class CldsService extends SecureServiceBase { /** * REST service that retrieves sdc services - * + * * @throws GeneralSecurityException * In case of issue when decryting the SDC password * @throws DecoderException @@ -586,7 +584,7 @@ public class CldsService extends SecureServiceBase { /** * REST service that retrieves total properties required by UI - * + * * @throws IOException * In case of issues */ @@ -594,13 +592,13 @@ public class CldsService extends SecureServiceBase { @Path("/properties") @Produces(MediaType.APPLICATION_JSON) public String getSdcProperties() throws IOException { - return createPropertiesObjectByUUID(getGlobalCldsString(), "{}"); + return createPropertiesObjectByUUID("{}"); } /** * REST service that retrieves total properties by using invariantUUID based * on refresh and non refresh - * + * * @throws GeneralSecurityException * In case of issues with the decryting the encrypted password * @throws DecoderException @@ -629,7 +627,7 @@ public class CldsService extends SecureServiceBase { // filter out VFs the user is not authorized for cldsServiceData.filterVfs(this); // format retrieved data into properties json - String sdcProperties = sdcCatalogServices.createPropertiesObjectByUUID(getGlobalCldsString(), cldsServiceData); + String sdcProperties = sdcCatalogServices.createPropertiesObjectByUUID(cldsServiceData); // audit log LoggingUtils.setTimeContext(startTime, new Date()); LoggingUtils.setResponseContext("0", "Get sdc properties by uuid success", this.getClass().getName()); @@ -698,10 +696,10 @@ public class CldsService extends SecureServiceBase { return serviceNode.toString(); } - private String createPropertiesObjectByUUID(String globalProps, String cldsResponseStr) throws IOException { + private String createPropertiesObjectByUUID(String cldsResponseStr) throws IOException { ObjectMapper mapper = new ObjectMapper(); SdcServiceDetail cldsSdcServiceDetail = mapper.readValue(cldsResponseStr, SdcServiceDetail.class); - ObjectNode globalPropsJson = null; + ObjectNode globalPropsJson = (ObjectNode) refProp.getJsonTemplate(GLOBAL_PROPERTIES_KEY); if (cldsSdcServiceDetail != null && cldsSdcServiceDetail.getUuid() != null) { /** * to create json with vf, alarm and locations @@ -720,14 +718,8 @@ public class CldsService extends SecureServiceBase { */ ObjectNode emptyvfcobjectNode = createByVFCObjectNode(mapper, cldsSdcServiceDetail.getResources()); byServiceBasicObjetNode.putPOJO("byVf", emptyvfcobjectNode); - globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class); globalPropsJson.putPOJO("shared", byServiceBasicObjetNode); logger.info("valuie of objNode: {}", globalPropsJson); - } else { - /** - * to create json with total properties when no serviceUUID passed - */ - globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class); } return globalPropsJson.toString(); } @@ -814,115 +806,123 @@ public class CldsService extends SecureServiceBase { @Path("/deploy/{modelName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - public CldsModel deployModel(@PathParam("action") String action, @PathParam("modelName") String modelName, + public Response deployModel(@PathParam("action") String action, @PathParam("modelName") String modelName, @QueryParam("test") String test, CldsModel model) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: Deploy model", getPrincipalName()); + Boolean errorCase = false; try { - checkForDuplicateServiceVf(modelName, model.getPropText()); - } catch (IOException | BadRequestException e) { - logger.error("Exception occured during duplicate check for service and VF", e); - throw new CldsConfigException(e.getMessage(), e); - } - String deploymentId = ""; - // If model is already deployed then pass same deployment id - if (model.getDeploymentId() != null && !model.getDeploymentId().isEmpty()) { - deploymentId = model.getDeploymentId(); - } else { - deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId"; - } - String createNewDeploymentStatusUrl = dcaeDispatcherServices.createNewDeployment(deploymentId, - model.getTypeId()); - String operationStatus = "processing"; - long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10); - while ("processing".equalsIgnoreCase(operationStatus)) { - // Break the loop if waiting for more than 10 mins - if (waitingTime < System.nanoTime()) { - break; + try { + checkForDuplicateServiceVf(modelName, model.getPropText()); + } catch (IOException | BadRequestException e) { + errorCase = true; + logger.error("Exception occured during duplicate check for service and VF", e); } - operationStatus = dcaeDispatcherServices.getOperationStatus(createNewDeploymentStatusUrl); - } - if ("succeeded".equalsIgnoreCase(operationStatus)) { - String artifactName = model.getControlName(); - if (artifactName != null) { - artifactName = artifactName + ".yml"; + String deploymentId = ""; + // If model is already deployed then pass same deployment id + if (model.getDeploymentId() != null && !model.getDeploymentId().isEmpty()) { + deploymentId = model.getDeploymentId(); + } else { + deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId"; } - DcaeEvent dcaeEvent = new DcaeEvent(); - /* set dcae events */ - dcaeEvent.setArtifactName(artifactName); - dcaeEvent.setEvent(DcaeEvent.EVENT_DEPLOYMENT); - CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(), - CldsEvent.ACTION_STATE_RECEIVED, null); - model.setDeploymentId(deploymentId); - model.save(cldsDao, getUserId()); - } else { - logger.info("Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); - throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, - "Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); + String createNewDeploymentStatusUrl = dcaeDispatcherServices.createNewDeployment(deploymentId, + model.getTypeId()); + String operationStatus = "processing"; + long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10); + while ("processing".equalsIgnoreCase(operationStatus)) { + // Break the loop if waiting for more than 10 mins + if (waitingTime < System.nanoTime()) { + break; + } + operationStatus = dcaeDispatcherServices.getOperationStatus(createNewDeploymentStatusUrl); + } + if ("succeeded".equalsIgnoreCase(operationStatus)) { + String artifactName = model.getControlName(); + if (artifactName != null) { + artifactName = artifactName + ".yml"; + } + DcaeEvent dcaeEvent = new DcaeEvent(); + /* set dcae events */ + dcaeEvent.setArtifactName(artifactName); + dcaeEvent.setEvent(DcaeEvent.EVENT_DEPLOYMENT); + CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(), + CldsEvent.ACTION_STATE_RECEIVED, null); + model.setDeploymentId(deploymentId); + model.save(cldsDao, getUserId()); + } else { + logger.info("Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); + throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, + "Deploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); + } + logger.info("Deploy model (" + modelName + ") succeeded...Deployment Id is - " + deploymentId); + // audit log + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", "Deploy model success", this.getClass().getName()); + auditLogger.info("Deploy model completed"); + } catch (Exception e) { + errorCase = true; + logger.error("Exception occured during deployModel", e); } - logger.info("Deploy model (" + modelName + ") succeeded...Deployment Id is - " + deploymentId); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Deploy model success", this.getClass().getName()); - auditLogger.info("Deploy model completed"); - return model; + + if (errorCase) { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(model).build(); + } + return Response.status(Response.Status.OK).entity(model).build(); } @PUT @Path("/undeploy/{modelName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - public CldsModel unDeployModel(@PathParam("action") String action, @PathParam("modelName") String modelName, - @QueryParam("test") String test, CldsModel model) throws IOException { + public Response unDeployModel(@PathParam("action") String action, @PathParam("modelName") String modelName, + @QueryParam("test") String test, CldsModel model) { Date startTime = new Date(); LoggingUtils.setRequestContext("CldsService: Undeploy model", getPrincipalName()); - String operationStatusUndeployUrl = dcaeDispatcherServices.deleteExistingDeployment(model.getDeploymentId(), - model.getTypeId()); - String operationStatus = "processing"; - long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10); - while ("processing".equalsIgnoreCase(operationStatus)) { - if (waitingTime < System.nanoTime()) { - break; + + Boolean errorCase = false; + try { + String operationStatusUndeployUrl = dcaeDispatcherServices.deleteExistingDeployment(model.getDeploymentId(), + model.getTypeId()); + String operationStatus = "processing"; + long waitingTime = System.nanoTime() + TimeUnit.MINUTES.toNanos(10); + while ("processing".equalsIgnoreCase(operationStatus)) { + if (waitingTime < System.nanoTime()) { + break; + } + operationStatus = dcaeDispatcherServices.getOperationStatus(operationStatusUndeployUrl); } - operationStatus = dcaeDispatcherServices.getOperationStatus(operationStatusUndeployUrl); - } - if ("succeeded".equalsIgnoreCase(operationStatus)) { - String artifactName = model.getControlName(); - if (artifactName != null) { - artifactName = artifactName + ".yml"; + if ("succeeded".equalsIgnoreCase(operationStatus)) { + String artifactName = model.getControlName(); + if (artifactName != null) { + artifactName = artifactName + ".yml"; + } + DcaeEvent dcaeEvent = new DcaeEvent(); + // set dcae events + dcaeEvent.setArtifactName(artifactName); + dcaeEvent.setEvent(DcaeEvent.EVENT_UNDEPLOYMENT); + CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(), + CldsEvent.ACTION_STATE_RECEIVED, null); + model.setDeploymentId(null); + model.save(cldsDao, getUserId()); + } else { + logger.info("Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); + throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, + "Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); } - DcaeEvent dcaeEvent = new DcaeEvent(); - // set dcae events - dcaeEvent.setArtifactName(artifactName); - dcaeEvent.setEvent(DcaeEvent.EVENT_UNDEPLOYMENT); - CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), dcaeEvent.getCldsActionCd(), - CldsEvent.ACTION_STATE_RECEIVED, null); - model.setDeploymentId(null); - model.save(cldsDao, getUserId()); - } else { - logger.info("Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); - throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, - "Undeploy model (" + modelName + ") failed...Operation Status is - " + operationStatus); + logger.info("Undeploy model (" + modelName + ") succeeded."); + // audit log + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", "Undeploy model success", this.getClass().getName()); + auditLogger.info("Undeploy model completed"); + } catch (Exception e) { + errorCase = true; + logger.error("Exception occured during unDeployModel", e); } - logger.info("Undeploy model (" + modelName + ") succeeded."); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "Undeploy model success", this.getClass().getName()); - auditLogger.info("Undeploy model completed"); - return model; - } - private String getGlobalCldsString() { - try { - if (null == globalCldsProperties) { - globalCldsProperties = new Properties(); - globalCldsProperties.load(appContext.getResource(globalClds).getInputStream()); - } - return (String) globalCldsProperties.get("globalCldsProps"); - } catch (IOException e) { - logger.error("Unable to load the globalClds due to an exception", e); - throw new CldsConfigException("Unable to load the globalClds due to an exception", e); + if (errorCase) { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(model).build(); } + return Response.status(Response.Status.OK).entity(model).build(); } private void checkForDuplicateServiceVf(String modelName, String modelPropText) throws IOException { diff --git a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java index e64f74bb2..1b03922d1 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java @@ -55,9 +55,9 @@ import org.springframework.stereotype.Component; @Path("/cldsTempate") public class CldsTemplateService extends SecureServiceBase { - @Value("${CLDS_PERMISSION_TYPE_TEMPLATE:permission-type-template}") + @Value("${clamp.config.security.permission.type.template:permission-type-template}") private String cldsPermissionTypeTemplate; - @Value("${CLDS_PERMISSION_INSTANCE:dev}") + @Value("${clamp.config.security.permission.instance:dev}") private String cldsPermissionInstance; private SecureServicePermission permissionReadTemplate; private SecureServicePermission permissionUpdateTemplate; diff --git a/src/main/java/org/onap/clamp/clds/util/ResourceFileUtil.java b/src/main/java/org/onap/clamp/clds/util/ResourceFileUtil.java index 57705d8fd..720576c47 100644 --- a/src/main/java/org/onap/clamp/clds/util/ResourceFileUtil.java +++ b/src/main/java/org/onap/clamp/clds/util/ResourceFileUtil.java @@ -28,7 +28,7 @@ import java.io.InputStream; import java.util.Scanner; /** - * Utility methods supporting transforms. + * Utility methods supporting resources accesses. */ public final class ResourceFileUtil { |