Fix Sonar bugs & sec issues 79/120579/10
authorsebdet <sebastien.determe@intl.att.com>
Thu, 15 Apr 2021 17:43:27 +0000 (19:43 +0200)
committersebdet <sebastien.determe@intl.att.com>
Fri, 16 Apr 2021 16:40:43 +0000 (18:40 +0200)
Fix all bugs & sec issues reported by Sonar

Issue-ID: POLICY-3200
Signed-off-by: sebdet <sebastien.determe@intl.att.com>
Change-Id: Ifb3d0d3602586b8defb0826e799ef0e24742235c

src/main/java/org/onap/policy/clamp/clds/Application.java
src/main/java/org/onap/policy/clamp/clds/ClampServlet.java
src/main/java/org/onap/policy/clamp/clds/client/CdsServices.java
src/main/java/org/onap/policy/clamp/clds/client/DcaeInventoryServices.java
src/main/java/org/onap/policy/clamp/policy/PolicyEngineServices.java
src/main/java/org/onap/policy/clamp/policy/operational/OperationalPolicyRepresentationBuilder.java
src/test/java/org/onap/policy/clamp/clds/model/dcae/DcaeInventoryResponseCacheTestItCase.java
ui-react/src/components/dialogs/Loop/DeployLoopModal.js

index 17f08c9..a242086 100644 (file)
@@ -28,7 +28,6 @@ package org.onap.policy.clamp.clds;
 import com.att.eelf.configuration.EELFLogger;
 import com.att.eelf.configuration.EELFManager;
 import java.io.IOException;
-import java.io.InputStream;
 import java.security.KeyStore;
 import java.security.KeyStoreException;
 import java.security.NoSuchAlgorithmException;
@@ -78,7 +77,7 @@ public class Application extends SpringBootServletInitializer {
     // This settings is an additional one to Spring config,
     // only if we want to have an additional port automatically redirected to
     // HTTPS
-    @Value("${server.http-to-https-redirection.port:none}")
+    @Value("${server.http-to-https-redirection.port:#{null}}")
     private String httpRedirectedPort;
     /**
      * This 8080 is the default port used by spring if this parameter is not
@@ -86,8 +85,19 @@ public class Application extends SpringBootServletInitializer {
      */
     @Value("${server.port:8080}")
     private String springServerPort;
-    @Value("${server.ssl.key-store:none}")
-    private String sslKeystoreFile;
+
+    @Value("${server.ssl.key-store:#{null}}")
+    private String keystoreFile;
+
+    @Value("${server.ssl.key-store-password:#{null}}")
+    private String keyStorePass;
+
+    @Value("${server.ssl.key-store-type:JKS}")
+    private String keyStoreType;
+
+
+    @Value("${clamp.config.keyFile:#{null}}")
+    private String keyFile;
 
     @Autowired
     private Environment env;
@@ -99,6 +109,7 @@ public class Application extends SpringBootServletInitializer {
 
     /**
      * Main method that starts the Clamp backend.
+     *
      * @param args app params
      */
     public static void main(String[] args) {
@@ -130,7 +141,7 @@ public class Application extends SpringBootServletInitializer {
     @Bean
     public ServletWebServerFactory getEmbeddedServletContainerFactory() {
         TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
-        if (!"none".equals(httpRedirectedPort) && !"none".equals(sslKeystoreFile)) {
+        if (httpRedirectedPort != null && keystoreFile != null) {
             // Automatically redirect to HTTPS
             tomcat = new TomcatEmbeddedServletContainerFactoryRedirection();
             Connector newConnector = createRedirectConnector(Integer.parseInt(springServerPort));
@@ -158,14 +169,10 @@ public class Application extends SpringBootServletInitializer {
     private String getSslExpirationDate() throws IOException {
         StringBuilder result = new StringBuilder("   :: SSL Certificates ::     ");
         try {
-            if (env.getProperty("server.ssl.key-store") != null) {
-
-                KeyStore keystore = KeyStore.getInstance(env.getProperty("server.ssl.key-store-type"));
-                String password = PassDecoder.decode(env.getProperty("server.ssl.key-store-password"),
-                        env.getProperty("clamp.config.keyFile"));
-                String keyStore = env.getProperty("server.ssl.key-store");
-                InputStream is = ResourceFileUtils.getResourceAsStream(keyStore.replaceAll("classpath:", ""));
-                keystore.load(is, password.toCharArray());
+            if (keystoreFile != null) {
+                KeyStore keystore = KeyStore.getInstance(keyStoreType);
+                keystore.load(ResourceFileUtils.getResourceAsStream(keystoreFile.replace("classpath:", "")),
+                        PassDecoder.decode(keyStorePass, keyFile).toCharArray());
 
                 Enumeration<String> aliases = keystore.aliases();
                 while (aliases.hasMoreElements()) {
index 5149dd3..dcaa2ac 100644 (file)
@@ -71,7 +71,7 @@ public class ClampServlet extends CamelHttpTransportServlet {
 
     private synchronized List<String> loadDynamicAuthenticationClasses() {
         return Arrays.stream(WebApplicationContextUtils.getWebApplicationContext(getServletContext())
-                .getEnvironment().getProperty(AUTHENTICATION_CLASS).split(",")).map(className -> className.trim())
+                .getEnvironment().getProperty(AUTHENTICATION_CLASS).split(",")).map(String::trim)
                 .collect(Collectors.toList());
     }
 
index 085e905..80ff9f7 100644 (file)
@@ -1,9 +1,11 @@
 /*-\r
  * ============LICENSE_START=======================================================\r
- * ONAP CLAMP\r
+ * ONAP POLICY-CLAMP\r
  * ================================================================================\r
  * Copyright (C) 2020 Huawei Technologies Co., Ltd.\r
  * ================================================================================\r
+ * Modifications Copyright (C) 2021 AT&T.\r
+ * ================================================================================\r
  * Licensed under the Apache License, Version 2.0 (the "License");\r
  * you may not use this file except in compliance with the License.\r
  * You may obtain a copy of the License at\r
@@ -29,16 +31,19 @@ import com.att.eelf.configuration.EELFManager;
 import com.google.gson.JsonElement;\r
 import com.google.gson.JsonObject;\r
 import com.google.gson.JsonParser;\r
+import java.io.IOException;\r
 import java.util.Date;\r
 import java.util.Map;\r
 import org.apache.camel.CamelContext;\r
 import org.apache.camel.Exchange;\r
+import org.apache.camel.ProducerTemplate;\r
 import org.apache.camel.builder.ExchangeBuilder;\r
 import org.onap.policy.clamp.clds.exception.cds.CdsParametersException;\r
 import org.onap.policy.clamp.clds.model.cds.CdsBpWorkFlowListResponse;\r
 import org.onap.policy.clamp.clds.util.JsonUtils;\r
 import org.onap.policy.clamp.clds.util.LoggingUtils;\r
 import org.springframework.beans.factory.annotation.Autowired;\r
+import org.springframework.http.HttpStatus;\r
 import org.springframework.stereotype.Component;\r
 \r
 /**\r
@@ -56,14 +61,6 @@ public class CdsServices {
     private static final String PROPERTIES = "properties";\r
     private static final String LIST = "list";\r
 \r
-    /**\r
-     * Constructor.\r
-     */\r
-    @Autowired\r
-    public CdsServices() {\r
-    }\r
-\r
-\r
     /**\r
      * Query CDS to get blueprint's workflow list.\r
      *\r
@@ -74,23 +71,28 @@ public class CdsServices {
     public CdsBpWorkFlowListResponse getBlueprintWorkflowList(String blueprintName, String blueprintVersion) {\r
         LoggingUtils.setTargetContext("CDS", "getBlueprintWorkflowList");\r
 \r
-        Exchange exchangeResponse = camelContext.createProducerTemplate()\r
-                .send("direct:get-blueprint-workflow-list", ExchangeBuilder.anExchange(camelContext)\r
-                        .withProperty("blueprintName", blueprintName).withProperty("blueprintVersion", blueprintVersion)\r
-                        .withProperty("raiseHttpExceptionFlag", true).build());\r
-\r
-        if (Integer.valueOf(200).equals(exchangeResponse.getIn().getHeader("CamelHttpResponseCode"))) {\r
-            String cdsResponse = (String) exchangeResponse.getIn().getBody();\r
-            logger.info("getBlueprintWorkflowList, response from CDS:" + cdsResponse);\r
-            LoggingUtils.setResponseContext("0", "Get Blueprint workflow list", this.getClass().getName());\r
-            Date startTime = new Date();\r
-            LoggingUtils.setTimeContext(startTime, new Date());\r
-            return JsonUtils.GSON_JPA_MODEL.fromJson(cdsResponse, CdsBpWorkFlowListResponse.class);\r
-        } else {\r
-            logger.error("CDS getBlueprintWorkflowList FAILED");\r
-            return null;\r
+        try (ProducerTemplate producerTemplate = camelContext.createProducerTemplate()) {\r
+            Exchange exchangeResponse =\r
+                    producerTemplate.send("direct:get-blueprint-workflow-list", ExchangeBuilder.anExchange(camelContext)\r
+                            .withProperty("blueprintName", blueprintName)\r
+                            .withProperty("blueprintVersion", blueprintVersion)\r
+                            .withProperty("raiseHttpExceptionFlag", false).build());\r
+\r
+            if (HttpStatus.valueOf((Integer) exchangeResponse.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE))\r
+                    .is2xxSuccessful()) {\r
+                String cdsResponse = (String) exchangeResponse.getIn().getBody();\r
+                logger.info("getBlueprintWorkflowList, response from CDS:" + cdsResponse);\r
+                LoggingUtils.setResponseContext("0", "Get Blueprint workflow list", this.getClass().getName());\r
+                Date startTime = new Date();\r
+                LoggingUtils.setTimeContext(startTime, new Date());\r
+                return JsonUtils.GSON_JPA_MODEL.fromJson(cdsResponse, CdsBpWorkFlowListResponse.class);\r
+            } else {\r
+                logger.error("CDS getBlueprintWorkflowList FAILED");\r
+            }\r
+        } catch (IOException e) {\r
+            logger.error("IOException caught when trying to execute get-blueprint-workflow-list flow", e);\r
         }\r
-\r
+        return null;\r
     }\r
 \r
     /**\r
@@ -105,22 +107,27 @@ public class CdsServices {
                                                  String workflow) {\r
         LoggingUtils.setTargetContext("CDS", "getWorkflowInputProperties");\r
 \r
-        Exchange exchangeResponse = camelContext.createProducerTemplate()\r
-                .send("direct:get-blueprint-workflow-input-properties", ExchangeBuilder.anExchange(camelContext)\r
-                        .withBody(getCdsPayloadForWorkFlow(blueprintName, blueprintVersion, workflow))\r
-                        .withProperty("raiseHttpExceptionFlag", true).build());\r
-\r
-        if (Integer.valueOf(200).equals(exchangeResponse.getIn().getHeader("CamelHttpResponseCode"))) {\r
-            String cdsResponse = (String) exchangeResponse.getIn().getBody();\r
-            logger.info("getWorkflowInputProperties, response from CDS:" + cdsResponse);\r
-            LoggingUtils.setResponseContext("0", "Get Blueprint workflow input properties", this.getClass().getName());\r
-            Date startTime = new Date();\r
-            LoggingUtils.setTimeContext(startTime, new Date());\r
-            return parseCdsResponse(cdsResponse);\r
-        } else {\r
-            logger.error("CDS getWorkflowInputProperties FAILED");\r
-            return null;\r
+        try (ProducerTemplate producerTemplate = camelContext.createProducerTemplate()) {\r
+            Exchange exchangeResponse = producerTemplate\r
+                    .send("direct:get-blueprint-workflow-input-properties", ExchangeBuilder.anExchange(camelContext)\r
+                            .withBody(getCdsPayloadForWorkFlow(blueprintName, blueprintVersion, workflow))\r
+                            .withProperty("raiseHttpExceptionFlag", false).build());\r
+            if (HttpStatus.valueOf((Integer) exchangeResponse.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE))\r
+                    .is2xxSuccessful()) {\r
+                String cdsResponse = (String) exchangeResponse.getIn().getBody();\r
+                logger.info("getWorkflowInputProperties, response from CDS:" + cdsResponse);\r
+                LoggingUtils\r
+                        .setResponseContext("0", "Get Blueprint workflow input properties", this.getClass().getName());\r
+                Date startTime = new Date();\r
+                LoggingUtils.setTimeContext(startTime, new Date());\r
+                return parseCdsResponse(cdsResponse);\r
+            } else {\r
+                logger.error("CDS getWorkflowInputProperties FAILED");\r
+            }\r
+        } catch (IOException e) {\r
+            logger.error("IOException caught when trying to execute get-blueprint-workflow-input-properties flow", e);\r
         }\r
+        return null;\r
     }\r
 \r
     protected JsonObject parseCdsResponse(String response) {\r
@@ -133,8 +140,7 @@ public class CdsServices {
         return workFlowProperties;\r
     }\r
 \r
-    private JsonObject getInputProperties(JsonObject inputs, JsonObject dataTypes,\r
-                                          JsonObject inputObject) {\r
+    private JsonObject getInputProperties(JsonObject inputs, JsonObject dataTypes, JsonObject inputObject) {\r
         if (inputs == null) {\r
             return inputObject;\r
         }\r
@@ -164,7 +170,7 @@ public class CdsServices {
 \r
         String type = inputProperty.get("entry_schema").getAsJsonObject().get(\r
                 TYPE).getAsString();\r
-        if (dataTypes.get(type) != null) {\r
+        if (dataTypes != null && dataTypes.get(type) != null) {\r
             JsonObject jsonObject = new JsonObject();\r
             jsonObject.addProperty(TYPE, LIST);\r
             jsonObject.add(PROPERTIES, getPropertiesObject(type, dataTypes));\r
index 1956a96..98eeae2 100644 (file)
@@ -1,8 +1,8 @@
 /*-\r
  * ============LICENSE_START=======================================================\r
- * ONAP CLAMP\r
+ * ONAP POLICY-CLAMP\r
  * ================================================================================\r
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights\r
+ * Copyright (C) 2017-2018, 2021 AT&T Intellectual Property. All rights\r
  *                             reserved.\r
  * ================================================================================\r
  * Licensed under the Apache License, Version 2.0 (the "License");\r
@@ -30,6 +30,7 @@ import java.io.IOException;
 import java.util.Date;\r
 import org.apache.camel.CamelContext;\r
 import org.apache.camel.Exchange;\r
+import org.apache.camel.ProducerTemplate;\r
 import org.apache.camel.builder.ExchangeBuilder;\r
 import org.json.simple.JSONArray;\r
 import org.json.simple.JSONObject;\r
@@ -40,6 +41,7 @@ import org.onap.policy.clamp.clds.model.dcae.DcaeInventoryResponse;
 import org.onap.policy.clamp.clds.util.JsonUtils;\r
 import org.onap.policy.clamp.clds.util.LoggingUtils;\r
 import org.springframework.beans.factory.annotation.Autowired;\r
+import org.springframework.http.HttpStatus;\r
 import org.springframework.stereotype.Component;\r
 \r
 /**\r
@@ -107,29 +109,32 @@ public class DcaeInventoryServices {
             retryInterval = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL));\r
         }\r
         for (int i = 0; i < retryLimit; i++) {\r
-            Exchange myCamelExchange = ExchangeBuilder.anExchange(camelContext)\r
-                    .withProperty("blueprintResourceId", resourceUuid).withProperty("blueprintServiceId", serviceUuid)\r
-                    .withProperty("blueprintName", artifactName).withProperty("raiseHttpExceptionFlag", true).build();\r
             metricsLogger.info("Attempt n°" + i + " to contact DCAE inventory");\r
+            try (ProducerTemplate producerTemplate = camelContext.createProducerTemplate()) {\r
+                Exchange exchangeResponse = producerTemplate\r
+                        .send("direct:get-dcae-blueprint-inventory", ExchangeBuilder.anExchange(camelContext)\r
+                                .withProperty("blueprintResourceId", resourceUuid)\r
+                                .withProperty("blueprintServiceId", serviceUuid)\r
+                                .withProperty("blueprintName", artifactName)\r
+                                .withProperty("raiseHttpExceptionFlag", false).build());\r
 \r
-            Exchange exchangeResponse = camelContext.createProducerTemplate()\r
-                    .send("direct:get-dcae-blueprint-inventory", myCamelExchange);\r
-\r
-            if (Integer.valueOf(200).equals(exchangeResponse.getIn().getHeader("CamelHttpResponseCode"))) {\r
-                String dcaeResponse = (String) exchangeResponse.getIn().getBody();\r
-                int totalCount = getTotalCountFromDcaeInventoryResponse(dcaeResponse);\r
-                metricsLogger.info("getDcaeInformation complete: totalCount returned=" + totalCount);\r
-                if (totalCount > 0) {\r
-                    logger.info("getDcaeInformation, answer from DCAE inventory:" + dcaeResponse);\r
-                    LoggingUtils.setResponseContext("0", "Get Dcae Information success", this.getClass().getName());\r
-                    Date startTime = new Date();\r
-                    LoggingUtils.setTimeContext(startTime, new Date());\r
-                    return getItemsFromDcaeInventoryResponse(dcaeResponse);\r
-                } else {\r
-                    logger.info("Dcae inventory totalCount returned is 0, so waiting " + retryInterval\r
-                            + "ms before retrying ...");\r
-                    // wait for a while and try to connect to DCAE again\r
-                    Thread.sleep(retryInterval);\r
+                if (HttpStatus.valueOf((Integer) exchangeResponse.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE))\r
+                        .is2xxSuccessful()) {\r
+                    String dcaeResponse = (String) exchangeResponse.getIn().getBody();\r
+                    int totalCount = getTotalCountFromDcaeInventoryResponse(dcaeResponse);\r
+                    metricsLogger.info("getDcaeInformation complete: totalCount returned=" + totalCount);\r
+                    if (totalCount > 0) {\r
+                        logger.info("getDcaeInformation, answer from DCAE inventory:" + dcaeResponse);\r
+                        LoggingUtils.setResponseContext("0", "Get Dcae Information success", this.getClass().getName());\r
+                        Date startTime = new Date();\r
+                        LoggingUtils.setTimeContext(startTime, new Date());\r
+                        return getItemsFromDcaeInventoryResponse(dcaeResponse);\r
+                    } else {\r
+                        logger.info("Dcae inventory totalCount returned is 0, so waiting " + retryInterval\r
+                                + "ms before retrying ...");\r
+                        // wait for a while and try to connect to DCAE again\r
+                        Thread.sleep(retryInterval);\r
+                    }\r
                 }\r
             }\r
         }\r
index 1a936bb..4142841 100644 (file)
@@ -25,10 +25,11 @@ package org.onap.policy.clamp.policy;
 
 import com.att.eelf.configuration.EELFLogger;
 import com.att.eelf.configuration.EELFManager;
+import java.io.IOException;
 import java.util.LinkedHashMap;
-import java.util.Map;
 import org.apache.camel.CamelContext;
 import org.apache.camel.Exchange;
+import org.apache.camel.ProducerTemplate;
 import org.apache.camel.builder.ExchangeBuilder;
 import org.onap.policy.clamp.clds.config.ClampProperties;
 import org.onap.policy.clamp.clds.sdc.controller.installer.BlueprintMicroService;
@@ -37,6 +38,7 @@ import org.onap.policy.clamp.loop.template.PolicyModel;
 import org.onap.policy.clamp.loop.template.PolicyModelsService;
 import org.onap.policy.models.pdp.concepts.PdpGroups;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
 import org.springframework.stereotype.Component;
 import org.yaml.snakeyaml.DumperOptions;
 import org.yaml.snakeyaml.Yaml;
@@ -55,9 +57,11 @@ public class PolicyEngineServices {
 
     private final PolicyModelsService policyModelsService;
 
+    private static final String RAISE_EXCEPTION_FLAG = "raiseHttpExceptionFlag";
+
     private static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyEngineServices.class);
-    private static int retryInterval = 0;
-    private static int retryLimit = 1;
+    private int retryInterval = 0;
+    private int retryLimit = 1;
 
     public static final String POLICY_RETRY_INTERVAL = "policy.retry.interval";
     public static final String POLICY_RETRY_LIMIT = "policy.retry.limit";
@@ -131,8 +135,7 @@ public class PolicyEngineServices {
             return;
         }
 
-        LinkedHashMap<String, Object> policyTypesMap = (LinkedHashMap<String, Object>) loadedYaml
-                .get("policy_types");
+        LinkedHashMap<String, Object> policyTypesMap = (LinkedHashMap<String, Object>) loadedYaml.get("policy_types");
         policyTypesMap.forEach((key, value) ->
                 this.createPolicyModelFromPolicyEngine(key,
                         ((String) ((LinkedHashMap<String, Object>) value).get("version"))));
@@ -146,7 +149,7 @@ public class PolicyEngineServices {
      */
     public String downloadAllPolicyModels() {
         return callCamelRoute(
-                ExchangeBuilder.anExchange(camelContext).withProperty("raiseHttpExceptionFlag", true).build(),
+                ExchangeBuilder.anExchange(camelContext).withProperty(RAISE_EXCEPTION_FLAG, true).build(),
                 "direct:get-all-policy-models", "Get all policies models");
     }
 
@@ -167,7 +170,7 @@ public class PolicyEngineServices {
         Yaml yamlParser = new Yaml(options);
         String responseBody = callCamelRoute(
                 ExchangeBuilder.anExchange(camelContext).withProperty("policyModelType", policyType)
-                        .withProperty("policyModelVersion", policyVersion).withProperty("raiseHttpExceptionFlag", true)
+                        .withProperty("policyModelVersion", policyVersion).withProperty(RAISE_EXCEPTION_FLAG, false)
                         .build(), "direct:get-policy-tosca-model",
                 "Get one policy");
 
@@ -176,7 +179,7 @@ public class PolicyEngineServices {
             return null;
         }
 
-        return yamlParser.dump((Map<String, Object>) yamlParser.load(responseBody));
+        return yamlParser.dump(yamlParser.load(responseBody));
     }
 
     /**
@@ -185,7 +188,7 @@ public class PolicyEngineServices {
     public void downloadPdpGroups() {
         String responseBody =
                 callCamelRoute(
-                        ExchangeBuilder.anExchange(camelContext).withProperty("raiseHttpExceptionFlag", true).build(),
+                        ExchangeBuilder.anExchange(camelContext).withProperty(RAISE_EXCEPTION_FLAG, false).build(),
                         "direct:get-all-pdp-groups", "Get Pdp Groups");
 
         if (responseBody == null || responseBody.isEmpty()) {
@@ -198,17 +201,21 @@ public class PolicyEngineServices {
 
     private String callCamelRoute(Exchange exchange, String camelFlow, String logMsg) {
         for (int i = 0; i < retryLimit; i++) {
-            Exchange exchangeResponse = camelContext.createProducerTemplate().send(camelFlow, exchange);
-            if (Integer.valueOf(200).equals(exchangeResponse.getIn().getHeader("CamelHttpResponseCode"))) {
-                return (String) exchangeResponse.getIn().getBody();
-            } else {
-                logger.info(logMsg + " query " + retryInterval + "ms before retrying ...");
-                // wait for a while and try to connect to DCAE again
-                try {
+            try (ProducerTemplate producerTemplate = camelContext.createProducerTemplate()) {
+                Exchange exchangeResponse = producerTemplate.send(camelFlow, exchange);
+                if (HttpStatus.valueOf((Integer) exchangeResponse.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE))
+                        .is2xxSuccessful()) {
+                    return (String) exchangeResponse.getIn().getBody();
+                } else {
+                    logger.info(logMsg + " query " + retryInterval + "ms before retrying ...");
+                    // wait for a while and try to connect to DCAE again
                     Thread.sleep(retryInterval);
-                } catch (InterruptedException e) {
-                    Thread.currentThread().interrupt();
+
                 }
+            } catch (IOException e) {
+                logger.error("IOException caught when trying to call Camel flow:" + camelFlow, e);
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
             }
         }
         return "";
index 8a1bb1a..6718475 100644 (file)
@@ -1,8 +1,8 @@
 /*-
  * ============LICENSE_START=======================================================
- * ONAP CLAMP
+ * ONAP POLICY-CLAMP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights
  *                             reserved.
  * Modifications Copyright (C) 2020 Huawei Technologies Co., Ltd.
  * ================================================================================
@@ -81,12 +81,10 @@ public class OperationalPolicyRepresentationBuilder {
                     .getAsJsonObject().get(ANY_OF).getAsJsonArray().addAll(createAnyOfArray(modelJson, true));
 
             // update CDS recipe and payload information to schema
-            JsonArray actors = jsonSchema.get(PROPERTIES).getAsJsonObject()
+            for (JsonElement actor : jsonSchema.get(PROPERTIES).getAsJsonObject()
                     .get("operational_policy").getAsJsonObject().get(PROPERTIES).getAsJsonObject().get("policies")
                     .getAsJsonObject().get(ITEMS).getAsJsonObject().get(PROPERTIES).getAsJsonObject().get("actor")
-                    .getAsJsonObject().get(ANY_OF).getAsJsonArray();
-
-            for (JsonElement actor : actors) {
+                    .getAsJsonObject().get(ANY_OF).getAsJsonArray()) {
                 if ("CDS".equalsIgnoreCase(actor.getAsJsonObject().get(TITLE).getAsString())) {
                     actor.getAsJsonObject().get(PROPERTIES).getAsJsonObject().get(RECIPE).getAsJsonObject()
                             .get(ANY_OF).getAsJsonArray()
@@ -141,8 +139,8 @@ public class OperationalPolicyRepresentationBuilder {
     private static JsonArray createBlankEntry() {
         JsonArray result = new JsonArray();
         JsonObject blankObject = new JsonObject();
-        blankObject.addProperty("title", "User defined");
-        blankObject.add("properties", new JsonObject());
+        blankObject.addProperty(TITLE, "User defined");
+        blankObject.add(PROPERTIES, new JsonObject());
         result.add(blankObject);
         return result;
     }
@@ -224,7 +222,7 @@ public class OperationalPolicyRepresentationBuilder {
                 for (Entry<String, JsonElement> workflowsEntry : workflows.entrySet()) {
                     JsonObject obj = new JsonObject();
                     obj.addProperty(TITLE, workflowsEntry.getKey());
-                    obj.addProperty(TYPE, "object");
+                    obj.addProperty(TYPE, TYPE_OBJECT);
                     obj.add(PROPERTIES, createPayloadProperty(workflowsEntry.getValue().getAsJsonObject(),
                             controllerProperties, workflowsEntry.getKey()));
                     schemaArray.add(obj);
@@ -239,7 +237,7 @@ public class OperationalPolicyRepresentationBuilder {
                                                     JsonObject controllerProperties, String workFlowName) {
         JsonObject payload = new JsonObject();
         payload.addProperty(TITLE, "Payload");
-        payload.addProperty(TYPE, "object");
+        payload.addProperty(TYPE, TYPE_OBJECT);
         payload.add(PROPERTIES, createInputPropertiesForPayload(workFlow, controllerProperties,
                                                                 workFlowName));
         JsonObject properties = new JsonObject();
@@ -302,7 +300,7 @@ public class OperationalPolicyRepresentationBuilder {
             String key = entry.getKey();
             JsonObject inputProperty = inputs.getAsJsonObject(key);
             if (key.equalsIgnoreCase(workFlowName + "-properties")) {
-                addDataFields(entry.getValue().getAsJsonObject().get("properties").getAsJsonObject(),
+                addDataFields(entry.getValue().getAsJsonObject().get(PROPERTIES).getAsJsonObject(),
                         dataObj, workFlowName);
             } else {
                 dataObj.add(entry.getKey(),
@@ -326,7 +324,7 @@ public class OperationalPolicyRepresentationBuilder {
                 listProperties.add(PROPERTIES, getProperties(cdsProperty.get(PROPERTIES).getAsJsonObject()));
                 property.add(ITEMS, listProperties);
             }
-        } else if (TYPE_OBJECT.equalsIgnoreCase(type)) {
+        } else if (cdsProperty != null && TYPE_OBJECT.equalsIgnoreCase(type)) {
             property.addProperty(TYPE, TYPE_OBJECT);
             property.add(PROPERTIES, getProperties(cdsProperty.get(PROPERTIES).getAsJsonObject()));
         } else {
index 0e7fe6c..f406e5e 100644 (file)
@@ -37,6 +37,7 @@ import org.junit.runner.RunWith;
 import org.onap.policy.clamp.clds.Application;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.http.HttpStatus;
 import org.springframework.test.context.junit4.SpringRunner;
 
 @RunWith(SpringRunner.class)
@@ -99,7 +100,8 @@ public class DcaeInventoryResponseCacheTestItCase {
         Exchange exchange = ExchangeBuilder.anExchange(camelContext).build();
         Exchange exchangeResponse = camelContext.createProducerTemplate()
                 .send("direct:get-all-dcae-blueprint-inventory", exchange);
-        assertThat(exchangeResponse.getIn().getHeader("CamelHttpResponseCode")).isEqualTo(200);
+        assertThat(HttpStatus.valueOf((Integer) exchangeResponse.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE))
+                .is2xxSuccessful()).isTrue();
         Set<DcaeInventoryResponse> blueprint = inventoryCache.getAllBlueprintsPerLoopId("testAsdcServiceId");
         assertThat(blueprint.size()).isEqualTo(2);
 
index 2155977..921ba18 100644 (file)
@@ -1,8 +1,8 @@
 /*-
  * ============LICENSE_START=======================================================
- * ONAP CLAMP
+ * ONAP POLICY-CLAMP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights
  *                             reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -66,13 +66,7 @@ export default class DeployLoopModal extends React.Component {
        }
        getInitialKeyValue(temporaryPropertiesJson) {
                const deployJsonList = temporaryPropertiesJson["dcaeDeployParameters"];
-               let initialKey;
-               Object.keys(deployJsonList)
-                       .filter((obj) => Object.keys(deployJsonList).indexOf(obj) === 0)
-                       .map(obj =>
-                               initialKey = obj
-               );
-               return initialKey;
+               return Object.keys(deployJsonList).find((obj) => Object.keys(deployJsonList).indexOf(obj) === 0);
        }
        componentWillReceiveProps(newProps) {
                this.setState({
@@ -143,7 +137,7 @@ export default class DeployLoopModal extends React.Component {
 
                const deployJsonList = this.state.temporaryPropertiesJson["dcaeDeployParameters"];
                var indents = [];
-               Object.keys(deployJsonList).map((item,key) =>
+               Object.keys(deployJsonList).forEach(item =>
                        indents.push(<Tab eventKey={item} title={item}>
                                {this.renderDeployParam(deployJsonList[item])}
                                </Tab>)
@@ -152,7 +146,7 @@ export default class DeployLoopModal extends React.Component {
        }
        renderDeployParam(deployJson) {
                var indents = [];
-               Object.keys(deployJson).map((item,key) =>
+               Object.keys(deployJson).forEach(item =>
                indents.push(<FormStyled>
                                <Form.Label>{item}</Form.Label>
                                <Form.Control type="text" name={item} onChange={this.handleChange} defaultValue={deployJson[item]}></Form.Control>