Add encryption for passwords
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / SdcReq.java
index 08e196b..38e3b15 100644 (file)
 
 package org.onap.clamp.clds.client.req;
 
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
 import java.util.ArrayList;
 import java.util.Base64;
 import java.util.Iterator;
 import java.util.List;
-import java.util.Map;
 import java.util.Map.Entry;
 
 import org.apache.commons.codec.digest.DigestUtils;
@@ -39,158 +48,61 @@ import org.onap.clamp.clds.model.CldsSdcResource;
 import org.onap.clamp.clds.model.CldsSdcServiceDetail;
 import org.onap.clamp.clds.model.prop.Global;
 import org.onap.clamp.clds.model.prop.ModelProperties;
-import org.onap.clamp.clds.model.prop.StringMatch;
 import org.onap.clamp.clds.model.prop.Tca;
 import org.onap.clamp.clds.model.refprop.RefProp;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml;
+import org.onap.clamp.clds.util.CryptoUtils;
+import org.springframework.beans.factory.annotation.Autowired;
 
 /**
  * Construct a Sdc request given CLDS objects.
  */
 public class SdcReq {
+    @Autowired
+    protected CryptoUtils             cryptoUtils;
     protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(SdcReq.class);
     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
+    @Autowired
+    protected RefProp                 refProp;
 
     /**
-     * @param refProp
+     * Format the Blueprint from a Yaml
+     *
      * @param prop
-     * @return
+     *            The ModelProperties describing the clds model
+     * @param docText
+     *            The Yaml file that must be converted
+     *
+     * @return A String containing the BluePrint
      * @throws JsonParseException
+     *             In case of issues
      * @throws JsonMappingException
+     *             In case of issues
      * @throws IOException
+     *             In case of issues
      */
-    public static String formatBlueprint(RefProp refProp, ModelProperties prop, String docText)
+    public String formatBlueprint(ModelProperties prop, String docText)
             throws JsonParseException, JsonMappingException, IOException {
-
-        Global globalProp = prop.getGlobal();
-        String service = globalProp.getService();
-
         String yamlvalue = getYamlvalue(docText);
-
         String updatedBlueprint = "";
-        StringMatch stringMatch = prop.getType(StringMatch.class);
         Tca tca = prop.getType(Tca.class);
-        if (stringMatch.isFound()) {
-            prop.setCurrentModelElementId(stringMatch.getId());
-            ObjectMapper objectMapper = new ObjectMapper();
-            ObjectNode serviceConfigurations = objectMapper.createObjectNode();
-
-            StringMatchPolicyReq.appendServiceConfigurations(refProp, service, serviceConfigurations, stringMatch,
-                    prop);
-            logger.info("Value of serviceConfigurations:" + serviceConfigurations);
-            ObjectNode servConfNode = (ObjectNode) serviceConfigurations.get("serviceConfigurations");
-
-            // get updated blueprint by attaching service Conf from
-            // globalProperties
-            updatedBlueprint = getUpdatedBlueprintWithServiceConf(refProp, prop, yamlvalue, servConfNode);
-        } else if (tca.isFound()) {
-            prop.setCurrentModelElementId(tca.getId());
-            ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("tca.template", service);
-            ObjectNode content = rootNode.with("content");
-            TcaMPolicyReq.appendSignatures(refProp, service, content, tca, prop);
-            logger.info("Value of content:" + content);
-            // ObjectNode servConfNode =
-            // (ObjectNode)signatures.get("signatures");
-
-            // get updated blueprint by attaching service Conf from
-            // globalProperties
-            updatedBlueprint = getUpdatedBlueprintWithConfiguration(refProp, prop, yamlvalue, content);
+        if (tca.isFound()) {
+            updatedBlueprint = TcaRequestFormatter.updatedBlueprintWithConfiguration(refProp, prop, yamlvalue);
         }
-
         logger.info("value of blueprint:" + updatedBlueprint);
         return updatedBlueprint;
     }
 
-    private static String getUpdatedBlueprintWithServiceConf(RefProp refProp, ModelProperties prop, String yamlValue,
-            ObjectNode serviceConf) throws IOException {
-        Yaml yaml = new Yaml();
-
-        // Serialiaze Yaml file
-        Map<String, Map> loadedYaml = (Map<String, Map>) yaml.load(yamlValue);
-        // Get node templates information from Yaml
-        Map<String, Map> nodeTemplates = loadedYaml.get("node_templates");
-        logger.info("value of NodeTemplates:" + nodeTemplates);
-
-        // Get StringMatch Object information from node templates of Yaml
-        Map<String, Map> smObject = nodeTemplates.get("SM");
-        logger.info("value of StringMatch:" + smObject);
-
-        // Get Properties Object information from stringmatch of Yaml
-        Map<String, String> propsObject = smObject.get("properties");
-        logger.info("value of PropsObject:" + propsObject);
-
-        String deploymentJsonObject = propsObject.get("deployment_JSON");
-        logger.info("value of deploymentJson:" + deploymentJsonObject);
-
-        ObjectMapper mapper = new ObjectMapper();
-        ObjectNode deployJsonNode = (ObjectNode) mapper.readTree(deploymentJsonObject);
-        ObjectNode configurationObjectNode = (ObjectNode) deployJsonNode.get("configuration");
-
-        // "policyName":"example_model06.ClosedLoop_FRWL_SIG_0538e6f2_8c1b_4656_9999_3501b3c59ad7_StringMatch_",
-        String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
-        String policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
-        configurationObjectNode.put("policyName", policyName);
-
-        // "closedLoopControlName":"ClosedLoop-FRWL-SIG-0538e6f2-8c1b-4656-9999-3501b3c59ad7",
-        configurationObjectNode.put("closedLoopControlName", prop.getControlName());
-        configurationObjectNode.put("messageReaderConsumerGroup", prop.getModelName());
-        configurationObjectNode.set("serviceConfigurations", serviceConf);
-        propsObject.put("deployment_JSON", deployJsonNode.toString());
-        String blueprint = yaml.dump(loadedYaml);
-        logger.info("value of updated Yaml File:" + blueprint);
-
-        blueprint = yaml.dump(loadedYaml);
-        logger.info("value of updated Yaml File:" + blueprint);
-
-        return blueprint;
-    }
-
-    private static String getUpdatedBlueprintWithConfiguration(RefProp refProp, ModelProperties prop, String yamlValue,
-            ObjectNode serviceConf) throws JsonProcessingException, IOException {
-        String blueprint = "";
-        Yaml yaml = new Yaml();
-        // Serialiaze Yaml file
-        Map<String, Map> loadedYaml = (Map<String, Map>) yaml.load(yamlValue);
-        // Get node templates information from Yaml
-        Map<String, Map> nodeTemplates = loadedYaml.get("node_templates");
-        logger.info("value of NodeTemplates:" + nodeTemplates);
-        // Get Tca Object information from node templates of Yaml
-        Map<String, Map> tcaObject = nodeTemplates.get("MTCA");
-        logger.info("value of Tca:" + tcaObject);
-        // Get Properties Object information from tca of Yaml
-        Map<String, String> propsObject = tcaObject.get("properties");
-        logger.info("value of PropsObject:" + propsObject);
-        String deploymentJsonObject = propsObject.get("deployment_JSON");
-        logger.info("value of deploymentJson:" + deploymentJsonObject);
-
-        ObjectMapper mapper = new ObjectMapper();
-
-        ObjectNode deployJsonNode = (ObjectNode) mapper.readTree(deploymentJsonObject);
-
-        // "policyName":"example_model06.ClosedLoop_FRWL_SIG_0538e6f2_8c1b_4656_9999_3501b3c59ad7_Tca_",
-        String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
-        String policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
-        serviceConf.put("policyName", policyName);
-
-        deployJsonNode.set("configuration", serviceConf);
-        propsObject.put("deployment_JSON", deployJsonNode.toString());
-        blueprint = yaml.dump(loadedYaml);
-        logger.info("value of updated Yaml File:" + blueprint);
-
-        return blueprint;
-    }
-
-    public static String formatSdcLocationsReq(ModelProperties prop, String artifactName) {
+    /**
+     * Format the SDC Locations Request in the JSON Format
+     *
+     * @param prop
+     *            The ModelProperties describing the clds model
+     * @param artifactName
+     *            The name of the artifact
+     *
+     * @return SDC Locations request in the JSON Format
+     */
+    public String formatSdcLocationsReq(ModelProperties prop, String artifactName) {
         ObjectMapper objectMapper = new ObjectMapper();
         Global global = prop.getGlobal();
         List<String> locationsList = global.getLocation();
@@ -202,12 +114,27 @@ public class SdcReq {
         locationObject.put("artifactName", artifactName);
         locationObject.putPOJO("locations", locationsArrayNode);
         String locationJsonFormat = locationObject.toString();
-        logger.info("Value of locaation Json Artifact:" + locationsArrayNode);
+        logger.info("Value of location Json Artifact:" + locationsArrayNode);
         return locationJsonFormat;
     }
 
-    public static String formatSdcReq(String payloadData, String artifactName, String artifactLabel,
-            String artifactType) throws IOException {
+    /**
+     * Format the SDC Request
+     *
+     * @param payloadData
+     *            The ModelProperties describing the clds model
+     * @param artifactName
+     *            The name of the artifact
+     * @param artifactLabel
+     *            The Label of the artifact
+     * @param artifactType
+     *            The type of the artifact
+     * @return formatted SDC Request
+     * @throws IOException
+     *             In case of issues
+     */
+    public String formatSdcReq(String payloadData, String artifactName, String artifactLabel, String artifactType)
+            throws IOException {
         logger.info("artifact=" + payloadData);
         String base64Artifact = base64Encode(payloadData);
         return "{ \n" + "\"payloadData\" : \"" + base64Artifact + "\",\n" + "\"artifactLabel\" : \"" + artifactLabel
@@ -216,13 +143,22 @@ public class SdcReq {
                 + "} \n";
     }
 
-    public static String getSdcReqUrl(ModelProperties prop, String url) {
+    /**
+     * Get the SDC Request URL
+     *
+     * @param prop
+     *            The ModelProperties describing the clds model
+     * @param url
+     *            url
+     * @return SDC Request URL
+     */
+    public String getSdcReqUrl(ModelProperties prop, String url) {
         Global globalProps = prop.getGlobal();
         String serviceUUID = "";
         String resourceInstanceName = "";
         if (globalProps != null) {
             List<String> resourceVf = globalProps.getResourceVf();
-            if (resourceVf != null && resourceVf.size() > 0) {
+            if (resourceVf != null && !resourceVf.isEmpty()) {
                 resourceInstanceName = resourceVf.get(0);
             }
             if (globalProps.getService() != null) {
@@ -239,11 +175,12 @@ public class SdcReq {
      * @param prop
      * @param baseUrl
      * @param sdcCatalogServices
+     * @param execution
      * @return
-     * @throws Exception
+     * @throws GeneralSecurityException
      */
-    public static List<String> getSdcReqUrlsList(ModelProperties prop, String baseUrl,
-            SdcCatalogServices sdcCatalogServices, DelegateExecution execution) throws Exception {
+    public List<String> getSdcReqUrlsList(ModelProperties prop, String baseUrl, SdcCatalogServices sdcCatalogServices,
+            DelegateExecution execution) throws GeneralSecurityException {
         // TODO : refact and regroup with very similar code
         List<String> urlList = new ArrayList<>();
         Global globalProps = prop.getGlobal();
@@ -254,21 +191,20 @@ public class SdcReq {
                 List<String> resourceVfList = globalProps.getResourceVf();
                 String serviceUUID = sdcCatalogServices.getServiceUuidFromServiceInvariantId(serviceInvariantUUID);
                 String sdcServicesInformation = sdcCatalogServices.getSdcServicesInformation(serviceUUID);
-                CldsSdcServiceDetail CldsSdcServiceDetail = sdcCatalogServices
+                CldsSdcServiceDetail cldsSdcServiceDetail = sdcCatalogServices
                         .getCldsSdcServiceDetailFromJson(sdcServicesInformation);
-                if (CldsSdcServiceDetail != null && resourceVfList != null) {
-                    List<CldsSdcResource> CldsSdcResourcesList = CldsSdcServiceDetail.getResources();
-                    if (CldsSdcResourcesList != null && CldsSdcResourcesList.size() > 0) {
-                        for (CldsSdcResource CldsSdcResource : CldsSdcResourcesList) {
+                if (cldsSdcServiceDetail != null && resourceVfList != null) {
+                    List<CldsSdcResource> cldsSdcResourcesList = cldsSdcServiceDetail.getResources();
+                    if (cldsSdcResourcesList != null && !cldsSdcResourcesList.isEmpty()) {
+                        for (CldsSdcResource CldsSdcResource : cldsSdcResourcesList) {
                             if (CldsSdcResource != null && CldsSdcResource.getResoucreType() != null
-                                    && CldsSdcResource.getResoucreType().equalsIgnoreCase("VF")) {
-                                if (resourceVfList.contains(CldsSdcResource.getResourceInvariantUUID())) {
-                                    String normalizedResourceInstanceName = normalizeResourceInstanceName(
-                                            CldsSdcResource.getResourceInstanceName());
-                                    String svcUrl = baseUrl + "/" + serviceUUID + "/resourceInstances/"
-                                            + normalizedResourceInstanceName + "/artifacts";
-                                    urlList.add(svcUrl);
-                                }
+                                    && CldsSdcResource.getResoucreType().equalsIgnoreCase("VF")
+                                    && resourceVfList.contains(CldsSdcResource.getResourceInvariantUUID())) {
+                                String normalizedResourceInstanceName = normalizeResourceInstanceName(
+                                        CldsSdcResource.getResourceInstanceName());
+                                String svcUrl = baseUrl + "/" + serviceUUID + "/resourceInstances/"
+                                        + normalizedResourceInstanceName + "/artifacts";
+                                urlList.add(svcUrl);
                             }
                         }
                     }
@@ -286,7 +222,7 @@ public class SdcReq {
      * @param inText
      * @return
      */
-    public static String normalizeResourceInstanceName(String inText) {
+    public String normalizeResourceInstanceName(String inText) {
         return inText.replace(" ", "").replace("-", "").replace(".", "").toLowerCase();
     }
 
@@ -296,7 +232,7 @@ public class SdcReq {
      * @param data
      * @return
      */
-    public static String calculateMD5ByString(String data) {
+    public String calculateMD5ByString(String data) {
         String calculatedMd5 = DigestUtils.md5Hex(data);
         // encode base-64 result
         return base64Encode(calculatedMd5.getBytes());
@@ -308,7 +244,7 @@ public class SdcReq {
      * @param inText
      * @return
      */
-    public static String base64Encode(String inText) {
+    public String base64Encode(String inText) {
         return base64Encode(stringToByteArray(inText));
     }
 
@@ -318,7 +254,7 @@ public class SdcReq {
      * @param inText
      * @return
      */
-    public static byte[] stringToByteArray(String inText) {
+    public byte[] stringToByteArray(String inText) {
         return inText.getBytes(StandardCharsets.UTF_8);
     }
 
@@ -328,7 +264,7 @@ public class SdcReq {
      * @param bytes
      * @return
      */
-    public static String base64Encode(byte[] bytes) {
+    public String base64Encode(byte[] bytes) {
         Base64.Encoder encoder = Base64.getEncoder();
         return encoder.encodeToString(bytes);
     }
@@ -337,16 +273,26 @@ public class SdcReq {
      * Return SDC id and pw as a HTTP Basic Auth string (for example: Basic
      * dGVzdDoxMjM0NTY=).
      *
-     * @return
+     * @return The String with Basic Auth and password
+     * @throws GeneralSecurityException
+     *             In case of issue when decryting the SDC password
      */
-    public static String getSdcBasicAuth(RefProp refProp) {
+    public String getSdcBasicAuth() throws GeneralSecurityException {
         String sdcId = refProp.getStringValue("sdc.serviceUsername");
         String sdcPw = refProp.getStringValue("sdc.servicePassword");
-        String idPw = base64Encode(sdcId + ":" + sdcPw);
+        String password = cryptoUtils.decrypt(sdcPw);
+        String idPw = base64Encode(sdcId + ":" + password);
         return "Basic " + idPw;
     }
 
-    private static String getYamlvalue(String docText) throws IOException {
+    /**
+     * Method to get yaml/template properties value from json
+     *
+     * @param docText
+     * @return
+     * @throws IOException
+     */
+    public String getYamlvalue(String docText) throws IOException {
         ObjectMapper objectMapper = new ObjectMapper();
         String yamlFileValue = "";
         ObjectNode root = objectMapper.readValue(docText, ObjectNode.class);