Fixing the BRMS rule generation issue
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / CreateBrmsParamPolicy.java
index 047342a..3ed2ee3 100644 (file)
@@ -34,10 +34,13 @@ import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.UUID;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import javax.script.SimpleBindings;
+
 import org.apache.commons.io.FilenameUtils;
 import org.onap.policy.common.logging.eelf.MessageCodes;
 import org.onap.policy.common.logging.eelf.PolicyLogger;
@@ -48,6 +51,7 @@ import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
 import org.onap.policy.rest.adapter.PolicyRestAdapter;
 import org.onap.policy.rest.jpa.BRMSParamTemplate;
 
+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;
@@ -113,10 +117,8 @@ public class CreateBrmsParamPolicy extends Policy {
     
        // Utility to read json data from the existing file to a string
        static String readFile(String path, Charset encoding) throws IOException {
-
                byte[] encoded = Files.readAllBytes(Paths.get(path));
                return new String(encoded, encoding);
-
        }
        
        // Saving the Configurations file at server location for config policy.
@@ -132,8 +134,6 @@ public class CreateBrmsParamPolicy extends Policy {
                        policyAdapter.setJsonBody(expandedBody);
                        policyAdapter.setConfigBodyData(expandedBody);
                        out.close();
-                       
-
                } catch (Exception e) {
                        PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving configuration file");
                }
@@ -162,7 +162,7 @@ public class CreateBrmsParamPolicy extends Policy {
        }
 
        @Override
-       public Map<String, String> savePolicies() throws Exception {
+       public Map<String, String> savePolicies() throws PAPException {
                
                Map<String, String> successMap = new HashMap<>();
                if(isPolicyExists()){
@@ -189,8 +189,10 @@ public class CreateBrmsParamPolicy extends Policy {
        private String getValueFromDictionary(String templateName){
                String ruleTemplate = null;
                CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
-               String queryString="from BRMSParamTemplate where param_template_name= '"+templateName+"'";
-               List<Object> result = dbConnection.getDataByQuery(queryString);
+               String queryString="from BRMSParamTemplate where param_template_name= :templateName";
+               SimpleBindings params = new SimpleBindings();
+               params.put("templateName", templateName);
+               List<Object> result = dbConnection.getDataByQuery(queryString, params);
                if(!result.isEmpty()){
                        BRMSParamTemplate template = (BRMSParamTemplate) result.get(0);
                        ruleTemplate = template.getRule();
@@ -202,7 +204,7 @@ public class CreateBrmsParamPolicy extends Policy {
                Map<String, String> mapFieldType= new HashMap<>();
                if(rule!=null){
                        try {
-                               String params = "";
+                               StringBuilder params = new StringBuilder();
                                Boolean flag = false;
                                Boolean comment = false;
                                String lines[] = rule.split("\n");
@@ -227,6 +229,7 @@ public class CreateBrmsParamPolicy extends Policy {
                                                                line = line.split("\\/\\*")[0]
                                                                                + line.split("\\*\\/")[1].replace("*/", "");
                                                        } catch (Exception e) {
+                                                               LOGGER.debug(e);
                                                                line = line.split("\\/\\*")[0];
                                                        }
                                                } else {
@@ -238,6 +241,7 @@ public class CreateBrmsParamPolicy extends Policy {
                                                try {
                                                        line = line.split("\\*\\/")[1].replace("*/", "");
                                                } catch (Exception e) {
+                                                       LOGGER.debug(e);
                                                        line = "";
                                                }
                                        }
@@ -245,19 +249,19 @@ public class CreateBrmsParamPolicy extends Policy {
                                                continue;
                                        }
                                        if (flag) {
-                                               params = params + line;
+                                               params.append(line);
                                        }
-                                       if (line.contains("declare Params")) {
-                                               params = params + line;
+                                       if (line.contains("declare PapParams")) {
+                                               params.append(line);
                                                flag = true;
                                        }
                                        if (line.contains("end") && flag) {
                                                break;
                                        }
                                }
-                               params = params.replace("declare Params", "").replace("end", "")
+                               String param = params.toString().replace("declare PapParams", "").replace("end", "")
                                                .replaceAll("\\s+", "");
-                               String[] components = params.split(":");
+                               String[] components = param.split(":");
                                String caption = "";
                                for (int i = 0; i < components.length; i++) {
                                        String type = "";
@@ -271,6 +275,7 @@ public class CreateBrmsParamPolicy extends Policy {
                                        try {
                                                nextComponent = components[i + 1];
                                        } catch (Exception e) {
+                                               LOGGER.debug(e);
                                                nextComponent = components[i];
                                        }
                                        //If the type is of type String then we add the UI Item and type to the map. 
@@ -296,7 +301,7 @@ public class CreateBrmsParamPolicy extends Policy {
        // separately because the fully configured policy is used for multiple
        // things
        @Override
-       public boolean prepareToSave() throws Exception {
+       public boolean prepareToSave() throws PAPException {
                
                if (isPreparedToSave()) {
                        // we have already done this
@@ -327,16 +332,16 @@ public class CreateBrmsParamPolicy extends Policy {
                        
                        //Get the type of the UI Fields. 
                        Map<String,String> typeOfUIField=findType(valueFromDictionary);
-                       String generatedRule=null;
-                       String body = "";
+                       StringBuilder generatedRule = new StringBuilder();
+                       StringBuilder body = new StringBuilder();
                        
                        try {
                                
                                try {
-                                       body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
-                                                               "<$%BRMSParamTemplate=" + tempateValue + "%$> \n */ \n";
-                                       body = body +  valueFromDictionary + "\n";
-                                       generatedRule = "rule \"" +policyName.substring(0, policyName.replace(".xml", "").lastIndexOf(".")) +".Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();";
+                                       body.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
+                                                               "<$%BRMSParamTemplate=" + tempateValue + "%$> \n */ \n");
+                                       body.append(valueFromDictionary + "\n");
+                                       generatedRule.append("rule \"" +policyName.substring(0, policyName.replace(".xml", "").lastIndexOf(".")) +".PapParams\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tPapParams params = new PapParams();");
                                        
                                        //We first read the map data structure(ruleAndUIValue) received from the PAP-ADMIN
                                        //We ignore if the key is "templateName as we are interested only in the UI fields and its value. 
@@ -353,24 +358,23 @@ public class CreateBrmsParamPolicy extends Policy {
                                                                        if(fieldType.getValue()=="String")
                                                                        {
                                                                                //Type is String
-                                                                               generatedRule = generatedRule + "\n\t\tparams.set"
+                                                                               generatedRule.append("\n\t\tparams.set"
                                                                                                + key + "(\""
-                                                                                               + entry.getValue() + "\");";
+                                                                                               + entry.getValue() + "\");");
                                                                        }
                                                                        else{
-                                                                               generatedRule = generatedRule + "\n\t\tparams.set"
+                                                                           generatedRule.append("\n\t\tparams.set"
                                                                                                + key  + "("
-                                                                                               +  entry.getValue() + ");";
+                                                                                               +  entry.getValue() + ");");
                                                                        }
                                                                }
                                                        }
                                                }
                                        }
                                        
-                                       generatedRule = generatedRule
-                                                       + "\n\t\tinsert(params);\nend";
+                                       generatedRule.append("\n\t\tinsert(params);\nend");
                                        LOGGER.info("New rule generated with :" + generatedRule);
-                                       body = body + generatedRule;
+                                       body.append(generatedRule);
                                } catch (Exception e) {
                                        PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
                                }
@@ -379,10 +383,10 @@ public class CreateBrmsParamPolicy extends Policy {
                                PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
                        }
                        
-                       saveConfigurations(policyName,body);
+                       saveConfigurations(policyName,body.toString());
                        
                        // Make sure the filename ends with an extension
-                       if (policyName.endsWith(".xml") == false) {
+                       if (!policyName.endsWith(".xml")) {
                                policyName = policyName + ".xml";
                        }
 
@@ -421,7 +425,7 @@ public class CreateBrmsParamPolicy 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);
@@ -528,14 +532,14 @@ public class CreateBrmsParamPolicy extends Policy {
                assignment2.setAttributeId("URLID");
                assignment2.setCategory(CATEGORY_RESOURCE);
                assignment2.setIssuer("");
-               AttributeValueType AttributeValue = new AttributeValueType();
-               AttributeValue.setDataType(URI_DATATYPE);
+               AttributeValueType attributeValue = new AttributeValueType();
+               attributeValue.setDataType(URI_DATATYPE);
 
                String content = CONFIG_URL + "/Config/"+ getConfigFile(policyName);
 
-               AttributeValue.getContent().add(content);
+               attributeValue.getContent().add(content);
                assignment2.setExpression(new ObjectFactory()
-                               .createAttributeValue(AttributeValue));
+                               .createAttributeValue(attributeValue));
                advice.getAttributeAssignmentExpression().add(assignment2);
 
                // Policy Name Assignment
@@ -616,8 +620,8 @@ public class CreateBrmsParamPolicy extends Policy {
         
         // 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 (Entry<String, String> map : dynamicFieldConfigAttributes.entrySet()) {
+                       advice.getAttributeAssignmentExpression().add(createResponseAttributes("key:"+map.getKey(), map.getValue()));
                }
                
                //Risk Attributes