Consolidate PolicyRestAdapter setup
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / ConfigPolicy.java
index eed73f6..1cab716 100644 (file)
@@ -2,14 +2,16 @@
  * ============LICENSE_START=======================================================
  * ONAP-PAP-REST
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
+ * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modified Copyright (C) 2019 Bell Canada.
  * ================================================================================
  * 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.
@@ -20,6 +22,9 @@
 
 package org.onap.policy.pap.xacml.rest.components;
 
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.std.IdentifierImpl;
+
 import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileWriter;
@@ -31,17 +36,6 @@ import java.nio.file.Paths;
 import java.util.HashMap;
 import java.util.Map;
 
-import org.apache.commons.io.FilenameUtils;
-import org.onap.policy.common.logging.eelf.MessageCodes;
-import org.onap.policy.common.logging.eelf.PolicyLogger;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.onap.policy.utils.PolicyUtils;
-
-import com.att.research.xacml.api.pap.PAPException;
-import com.att.research.xacml.std.IdentifierImpl;
-
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
@@ -56,6 +50,14 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
 
+import org.apache.commons.io.FilenameUtils;
+import org.onap.policy.common.logging.eelf.MessageCodes;
+import org.onap.policy.common.logging.eelf.PolicyLogger;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.utils.PolicyUtils;
+
 public class ConfigPolicy extends Policy {
 
     /**
@@ -74,51 +76,55 @@ public class ConfigPolicy extends Policy {
         super();
     }
 
-    public ConfigPolicy(PolicyRestAdapter policyAdapter){
+    public ConfigPolicy(PolicyRestAdapter policyAdapter) {
         this.policyAdapter = policyAdapter;
     }
 
     // Saving the Configurations file at server location for config policy.
     protected void saveConfigurations(String policyName) {
         String fileName = getConfigFile(policyName);
-        try(BufferedWriter bw = new BufferedWriter(new FileWriter(CONFIG_HOME + File.separator + fileName))) {
+        try (BufferedWriter bw = new BufferedWriter(new FileWriter(CONFIG_HOME + File.separator + fileName))) {
             bw.write(configBodyData);
             if (LOGGER.isDebugEnabled()) {
                 LOGGER.debug("Configuration is succesfully saved");
             }
         } catch (IOException e) {
-            LOGGER.error("Exception Occured while writing Configuration Data"+e);
+            LOGGER.error("Exception Occured while writing Configuration Data" + e);
         }
     }
 
-
     // Here we are adding the extension for the configurations file based on the
     // config type selection for saving.
     private String getConfigFile(String filename) {
+        filename = removeExtentsion(filename);
+        String id = policyAdapter.getConfigType();
+
+        if (id == null) {
+            return filename;
+        }
+        switch (id.toUpperCase()) {
+            case JSON_CONFIG:
+                return filename + ".json";
+            case XML_CONFIG:
+                return filename + ".xml";
+            case PROPERTIES_CONFIG:
+                return filename + ".properties";
+            case OTHER_CONFIG:
+                return filename + ".txt";
+            default:
+                return filename;
+
+        }
+    }
+
+    private String removeExtentsion(String filename) {
         filename = FilenameUtils.removeExtension(filename);
         if (filename.endsWith(".xml")) {
             filename = filename.substring(0, filename.length() - 4);
         }
-        String id = policyAdapter.getConfigType();
-
-        if (id != null) {
-            if (id.equalsIgnoreCase(JSON_CONFIG)) {
-                filename = filename + ".json";
-            }
-            if (id.equalsIgnoreCase(XML_CONFIG)) {
-                filename = filename + ".xml";
-            }
-            if (id.equalsIgnoreCase(PROPERTIES_CONFIG)) {
-                filename = filename + ".properties";
-            }
-            if (id.equalsIgnoreCase(OTHER_CONFIG)) {
-                filename = filename + ".txt";
-            }
-        }
         return filename;
     }
 
-
     // Validations for Config form
     /*
      * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
@@ -133,24 +139,30 @@ public class ConfigPolicy extends Policy {
          */
         configBodyData = policyAdapter.getConfigBodyData();
         String id = policyAdapter.getConfigType();
-        if (id != null) {
-            if (id.equals(JSON_CONFIG)) {
+        if (id == null) {
+            return isValidForm;
+        }
+        switch (id) {
+            case JSON_CONFIG:
                 if (!PolicyUtils.isJSONValid(configBodyData)) {
                     isValidForm = false;
                 }
-            } else if (id.equals(XML_CONFIG)) {
+                break;
+            case XML_CONFIG:
                 if (!PolicyUtils.isXMLValid(configBodyData)) {
                     isValidForm = false;
                 }
-            } else if (id.equals(PROPERTIES_CONFIG)) {
-                if (!PolicyUtils.isPropValid(configBodyData)||configBodyData.equals("")) {
+                break;
+            case PROPERTIES_CONFIG:
+                if (!PolicyUtils.isPropValid(configBodyData) || configBodyData.equals("")) {
                     isValidForm = false;
                 }
-            } else if (id.equals(OTHER_CONFIG)) {
+                break;
+            case OTHER_CONFIG:
                 if (configBodyData.equals("")) {
                     isValidForm = false;
                 }
-            }
+                break;
         }
         return isValidForm;
 
@@ -160,29 +172,29 @@ public class ConfigPolicy extends Policy {
     public Map<String, String> savePolicies() throws PAPException {
 
         Map<String, String> successMap = new HashMap<>();
-        if(isPolicyExists()){
+        if (isPolicyExists()) {
             successMap.put("EXISTS", "This Policy already exist on the PAP");
             return successMap;
         }
 
-        if(!isPreparedToSave()){
-            //Prep and configure the policy for saving
+        if (!isPreparedToSave()) {
+            // Prep and configure the policy for saving
             prepareToSave();
         }
 
         // Until here we prepared the data and here calling the method to create xml.
         Path newPolicyPath = null;
         newPolicyPath = Paths.get(policyAdapter.getNewFileName());
-        successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
+        successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
         return successMap;
     }
 
-    //This is the method for preparing the policy for saving.  We have broken it out
-    //separately because the fully configured policy is used for multiple things
+    // This is the method for preparing the policy for saving. We have broken it out
+    // separately because the fully configured policy is used for multiple things
     @Override
-    public boolean prepareToSave() throws PAPException{
+    public boolean prepareToSave() throws PAPException {
 
-        if(isPreparedToSave()){
+        if (isPreparedToSave()) {
             return true;
         }
 
@@ -213,9 +225,9 @@ public class ConfigPolicy extends Policy {
             AllOfType allOfOne = new AllOfType();
 
             String fileName = policyAdapter.getNewFileName();
-            String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
+            String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
             if ((name == null) || (name.equals(""))) {
-                name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
+                name = fileName.substring(fileName.lastIndexOf("/") + 1);
             }
             allOfOne.getMatch().add(createMatch("PolicyName", name));
             AllOfType allOf = new AllOfType();
@@ -268,9 +280,9 @@ public class ConfigPolicy extends Policy {
             accessMatch.setAttributeValue(accessAttributeValue);
             AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
             URI accessURI = null;
-            try{
+            try {
                 accessURI = new URI(ACTION_ID);
-            }catch(URISyntaxException e){
+            } catch (URISyntaxException e) {
                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
             }
             accessAttributeDesignator.setCategory(CATEGORY_ACTION);
@@ -287,9 +299,9 @@ public class ConfigPolicy extends Policy {
             configMatch.setAttributeValue(configAttributeValue);
             AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
             URI configURI = null;
-            try{
+            try {
                 configURI = new URI(RESOURCE_ID);
-            }catch(URISyntaxException e){
+            } catch (URISyntaxException e) {
                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
             }
             configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
@@ -364,9 +376,9 @@ public class ConfigPolicy extends Policy {
 
             fileName = FilenameUtils.removeExtension(fileName);
             fileName = fileName + ".xml";
-            String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
+            String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
             if ((name == null) || (name.equals(""))) {
-                name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
+                name = fileName.substring(fileName.lastIndexOf("/") + 1);
             }
             attributeValue3.getContent().add(name);
             assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
@@ -426,7 +438,7 @@ public class ConfigPolicy extends Policy {
             }
         }
 
-        //Risk Attributes
+        // Risk Attributes
         AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
         assignment8.setAttributeId("RiskType");
         assignment8.setCategory(CATEGORY_RESOURCE);