Consolidate PolicyRestAdapter setup
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / CreateBrmsRawPolicy.java
index 7290f4c..bb46fd6 100644 (file)
@@ -2,14 +2,14 @@
  * ============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.
  * ================================================================================
  * 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 +20,8 @@
 
 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.File;
 import java.io.IOException;
@@ -34,15 +36,6 @@ import java.util.ArrayList;
 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.pap.xacml.rest.controller.BRMSDictionaryController;
-import org.onap.policy.rest.adapter.PolicyRestAdapter;
-
-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;
@@ -57,9 +50,16 @@ 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.pap.xacml.rest.controller.BRMSDictionaryController;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
 
 public class CreateBrmsRawPolicy extends Policy {
 
+    private static final String EMPTY_STRING = "";
+
     public CreateBrmsRawPolicy() {
         super();
     }
@@ -73,14 +73,14 @@ public class CreateBrmsRawPolicy extends Policy {
     // Saving the Configurations file at server location for CreateBrmsRawPolicy policy.
     protected void saveConfigurations(String policyName, String jsonBody) {
 
-            if (policyName.endsWith(".xml")) {
-                policyName = policyName.substring(0,
-                            policyName.lastIndexOf(".xml"));
-            }
-        try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")){
+        if (policyName.endsWith(".xml")) {
+            policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
+        }
+        try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")) {
             out.println(jsonBody);
         } catch (Exception e) {
-            PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsRawPolicy", "Exception saving configurations file");
+            PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsRawPolicy",
+                    "Exception saving configurations file");
         }
     }
 
@@ -117,7 +117,7 @@ public class CreateBrmsRawPolicy 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;
         }
@@ -145,7 +145,7 @@ public class CreateBrmsRawPolicy extends Policy {
     // separately because the fully configured policy is used for multiple
     // things
     @Override
-    public boolean prepareToSave() throws PAPException {
+    public boolean prepareToSave() {
 
         if (isPreparedToSave()) {
             // we have already done this
@@ -158,7 +158,7 @@ public class CreateBrmsRawPolicy extends Policy {
 
         // Create the Instance for pojo, PolicyType object is used in
         // marshalling.
-        if (policyAdapter.getPolicyType().equals("Config")) {
+        if ("Config".equals(policyAdapter.getPolicyType())) {
             PolicyType policyConfig = new PolicyType();
 
             policyConfig.setVersion(Integer.toString(version));
@@ -170,12 +170,11 @@ public class CreateBrmsRawPolicy extends Policy {
         policyName = policyAdapter.getNewFileName();
 
         if (policyAdapter.getData() != null) {
-            //String jsonBody = policyAdapter.getJsonBody();
-            String configBody=policyAdapter.getConfigBodyData();
+            String configBody = policyAdapter.getConfigBodyData();
             saveConfigurations(policyName, configBody);
 
             // Make sure the filename ends with an extension
-            if (policyName.endsWith(".xml") == false) {
+            if (!policyName.endsWith(".xml")) {
                 policyName = policyName + ".xml";
             }
 
@@ -187,14 +186,12 @@ public class CreateBrmsRawPolicy extends Policy {
 
             AllOfType allOfOne = new AllOfType();
             String fileName = policyAdapter.getNewFileName();
-            String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
-            if ((name == null) || (name.equals(""))) {
-                name = fileName.substring(fileName.lastIndexOf("/") + 1,
-                        fileName.length());
+            String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
+            if (EMPTY_STRING.equals(name)) {
+                name = fileName.substring(fileName.lastIndexOf("/") + 1);
             }
             allOfOne.getMatch().add(createMatch("PolicyName", name));
 
-
             AllOfType allOf = new AllOfType();
 
             // Match for ONAPName
@@ -213,10 +210,10 @@ public class CreateBrmsRawPolicy extends Policy {
             anyOf.getAllOf().add(allOf);
 
             TargetType target = new TargetType();
-            ((TargetType) target).getAnyOf().add(anyOf);
+            target.getAnyOf().add(anyOf);
 
             // Adding the target to the policy element
-            configPolicy.setTarget((TargetType) target);
+            configPolicy.setTarget(target);
 
             RuleType rule = new RuleType();
             rule.setRuleId(policyAdapter.getRuleID());
@@ -237,12 +234,12 @@ public class CreateBrmsRawPolicy extends Policy {
             try {
                 accessURI = new URI(ACTION_ID);
             } catch (URISyntaxException e) {
-                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating ACCESS URI");
+                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy",
+                        "Exception creating ACCESS URI");
             }
             accessAttributeDesignator.setCategory(CATEGORY_ACTION);
             accessAttributeDesignator.setDataType(STRING_DATATYPE);
-            accessAttributeDesignator.setAttributeId(new IdentifierImpl(
-                    accessURI).stringValue());
+            accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
             accessMatch.setAttributeDesignator(accessAttributeDesignator);
             accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
 
@@ -259,13 +256,13 @@ public class CreateBrmsRawPolicy extends Policy {
             try {
                 configURI = new URI(RESOURCE_ID);
             } catch (URISyntaxException e) {
-                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating Config URI");
+                PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy",
+                        "Exception creating Config URI");
             }
 
             configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
             configAttributeDesignator.setDataType(STRING_DATATYPE);
-            configAttributeDesignator.setAttributeId(new IdentifierImpl(
-                    configURI).stringValue());
+            configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
             configMatch.setAttributeDesignator(configAttributeDesignator);
             configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
 
@@ -281,22 +278,18 @@ public class CreateBrmsRawPolicy extends Policy {
             rule.setTarget(targetInRule);
             rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
 
-            configPolicy
-                    .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
-                    .add(rule);
+            configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
             policyAdapter.setPolicyData(configPolicy);
 
         } else {
-            PolicyLogger.error("Unsupported data object."
-                    + policyAdapter.getData().getClass().getCanonicalName());
+            PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
         }
         setPreparedToSave(true);
         return true;
     }
 
     // Data required for Advice part is setting here.
-    private AdviceExpressionsType getAdviceExpressions(int version,
-            String fileName) {
+    private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
 
         // Policy Config ID Assignment
         AdviceExpressionsType advices = new AdviceExpressionsType();
@@ -307,12 +300,11 @@ public class CreateBrmsRawPolicy extends Policy {
         AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
         assignment1.setAttributeId("type");
         assignment1.setCategory(CATEGORY_RESOURCE);
-        assignment1.setIssuer("");
+        assignment1.setIssuer(EMPTY_STRING);
         AttributeValueType configNameAttributeValue = new AttributeValueType();
         configNameAttributeValue.setDataType(STRING_DATATYPE);
         configNameAttributeValue.getContent().add("Configuration");
-        assignment1.setExpression(new ObjectFactory()
-                .createAttributeValue(configNameAttributeValue));
+        assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
         advice.getAttributeAssignmentExpression().add(assignment1);
 
         // For Config file Url if configurations are provided.
@@ -320,107 +312,102 @@ public class CreateBrmsRawPolicy extends Policy {
         AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
         assignment2.setAttributeId("URLID");
         assignment2.setCategory(CATEGORY_RESOURCE);
-        assignment2.setIssuer("");
+        assignment2.setIssuer(EMPTY_STRING);
         AttributeValueType AttributeValue = new AttributeValueType();
         AttributeValue.setDataType(URI_DATATYPE);
 
         String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
 
         AttributeValue.getContent().add(content);
-        assignment2.setExpression(new ObjectFactory()
-                .createAttributeValue(AttributeValue));
+        assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
         advice.getAttributeAssignmentExpression().add(assignment2);
 
         // Policy Name Assignment
         AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
         assignment3.setAttributeId("PolicyName");
         assignment3.setCategory(CATEGORY_RESOURCE);
-        assignment3.setIssuer("");
+        assignment3.setIssuer(EMPTY_STRING);
         AttributeValueType attributeValue3 = new AttributeValueType();
         attributeValue3.setDataType(STRING_DATATYPE);
         fileName = FilenameUtils.removeExtension(fileName);
         fileName = fileName + ".xml";
         System.out.println(fileName);
-        String name = fileName.substring(fileName.lastIndexOf("\\") + 1,
-                fileName.length());
-        if ((name == null) || (name.equals(""))) {
-            name = fileName.substring(fileName.lastIndexOf("/") + 1,
-                    fileName.length());
+        String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
+        if (EMPTY_STRING.equals(name)) {
+            name = fileName.substring(fileName.lastIndexOf("/") + 1);
         }
         System.out.println(name);
         attributeValue3.getContent().add(name);
-        assignment3.setExpression(new ObjectFactory()
-                .createAttributeValue(attributeValue3));
+        assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
         advice.getAttributeAssignmentExpression().add(assignment3);
 
         // Version Number Assignment
         AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
         assignment4.setAttributeId("VersionNumber");
         assignment4.setCategory(CATEGORY_RESOURCE);
-        assignment4.setIssuer("");
+        assignment4.setIssuer(EMPTY_STRING);
         AttributeValueType configNameAttributeValue4 = new AttributeValueType();
         configNameAttributeValue4.setDataType(STRING_DATATYPE);
         configNameAttributeValue4.getContent().add(Integer.toString(version));
-        assignment4.setExpression(new ObjectFactory()
-                .createAttributeValue(configNameAttributeValue4));
+        assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
         advice.getAttributeAssignmentExpression().add(assignment4);
 
         // Onap Name Assignment
         AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
         assignment5.setAttributeId("matching:" + ONAPID);
         assignment5.setCategory(CATEGORY_RESOURCE);
-        assignment5.setIssuer("");
+        assignment5.setIssuer(EMPTY_STRING);
         AttributeValueType configNameAttributeValue5 = new AttributeValueType();
         configNameAttributeValue5.setDataType(STRING_DATATYPE);
         configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
-        assignment5.setExpression(new ObjectFactory()
-                .createAttributeValue(configNameAttributeValue5));
+        assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
         advice.getAttributeAssignmentExpression().add(assignment5);
 
-
-        //Config Name Assignment
+        // Config Name Assignment
         AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
         assignment6.setAttributeId("matching:" + CONFIGID);
         assignment6.setCategory(CATEGORY_RESOURCE);
-        assignment6.setIssuer("");
+        assignment6.setIssuer(EMPTY_STRING);
         AttributeValueType configNameAttributeValue6 = new AttributeValueType();
         configNameAttributeValue6.setDataType(STRING_DATATYPE);
         configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
         assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
         advice.getAttributeAssignmentExpression().add(assignment6);
 
-        // Adding Controller Information. 
-        if(policyAdapter.getBrmsController()!=null){
+        // Adding Controller Information.
+        if (policyAdapter.getBrmsController() != null) {
             BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
-            advice.getAttributeAssignmentExpression().add(
-                    createResponseAttributes("controller:"+ policyAdapter.getBrmsController(), 
-                                brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController()));
+            advice.getAttributeAssignmentExpression().add(createResponseAttributes(
+                    "controller:" + policyAdapter.getBrmsController(),
+                    brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController()));
         }
-        
-        // Adding Dependencies. 
-        if(policyAdapter.getBrmsDependency()!=null){
+
+        // Adding Dependencies.
+        if (policyAdapter.getBrmsDependency() != null) {
             BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
             ArrayList<String> dependencies = new ArrayList<>();
             StringBuilder key = new StringBuilder();
-            for(String dependencyName: policyAdapter.getBrmsDependency()){
+            for (String dependencyName : policyAdapter.getBrmsDependency()) {
                 dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency());
-                key.append(dependencyName + ",");
+                key.append(dependencyName).append(",");
             }
-            advice.getAttributeAssignmentExpression().add(
-                        createResponseAttributes("dependencies:"+key.toString(), dependencies.toString()));
+            advice.getAttributeAssignmentExpression()
+                    .add(createResponseAttributes("dependencies:" + key.toString(), dependencies.toString()));
         }
-        
-        // Dynamic Field Config Attributes. 
+
+        // Dynamic Field Config Attributes.
         Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
-        for (String keyField : dynamicFieldConfigAttributes.keySet()) {
-            advice.getAttributeAssignmentExpression().add(createResponseAttributes("key:"+keyField, dynamicFieldConfigAttributes.get(keyField)));
+        for (Map.Entry<String, String> entry : dynamicFieldConfigAttributes.entrySet()) {
+            String keyField = entry.getKey();
+            advice.getAttributeAssignmentExpression()
+                    .add(createResponseAttributes("key:" + keyField, entry.getValue()));
         }
 
-        //Risk Attributes
+        // Risk Attributes
         AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
         assignment8.setAttributeId("RiskType");
         assignment8.setCategory(CATEGORY_RESOURCE);
-        assignment8.setIssuer("");
+        assignment8.setIssuer(EMPTY_STRING);
 
         AttributeValueType configNameAttributeValue8 = new AttributeValueType();
         configNameAttributeValue8.setDataType(STRING_DATATYPE);
@@ -432,7 +419,7 @@ public class CreateBrmsRawPolicy extends Policy {
         AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
         assignment9.setAttributeId("RiskLevel");
         assignment9.setCategory(CATEGORY_RESOURCE);
-        assignment9.setIssuer("");
+        assignment9.setIssuer(EMPTY_STRING);
 
         AttributeValueType configNameAttributeValue9 = new AttributeValueType();
         configNameAttributeValue9.setDataType(STRING_DATATYPE);
@@ -444,7 +431,7 @@ public class CreateBrmsRawPolicy extends Policy {
         AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
         assignment10.setAttributeId("guard");
         assignment10.setCategory(CATEGORY_RESOURCE);
-        assignment10.setIssuer("");
+        assignment10.setIssuer(EMPTY_STRING);
 
         AttributeValueType configNameAttributeValue10 = new AttributeValueType();
         configNameAttributeValue10.setDataType(STRING_DATATYPE);
@@ -456,7 +443,7 @@ public class CreateBrmsRawPolicy extends Policy {
         AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
         assignment11.setAttributeId("TTLDate");
         assignment11.setCategory(CATEGORY_RESOURCE);
-        assignment11.setIssuer("");
+        assignment11.setIssuer(EMPTY_STRING);
 
         AttributeValueType configNameAttributeValue11 = new AttributeValueType();
         configNameAttributeValue11.setDataType(STRING_DATATYPE);
@@ -474,11 +461,11 @@ public class CreateBrmsRawPolicy extends Policy {
         return policyAdapter.getData();
     }
 
-    private AttributeAssignmentExpressionType  createResponseAttributes(String key, String value){
+    private AttributeAssignmentExpressionType createResponseAttributes(String key, String value) {
         AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
         assignment7.setAttributeId(key);
         assignment7.setCategory(CATEGORY_RESOURCE);
-        assignment7.setIssuer("");
+        assignment7.setIssuer(EMPTY_STRING);
         AttributeValueType configNameAttributeValue7 = new AttributeValueType();
         configNameAttributeValue7.setDataType(STRING_DATATYPE);
         configNameAttributeValue7.getContent().add(value);