aboutsummaryrefslogtreecommitdiffstats
path: root/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components
diff options
context:
space:
mode:
authorPamela Dragosh <pdragosh@research.att.com>2019-10-22 07:53:44 -0400
committerPamela Dragosh <pdragosh@research.att.com>2019-10-23 13:33:56 -0400
commit1e61676b77dd09659027b8984f050df7e8538526 (patch)
tree115053dba12b4b27a0f92de0e7648a672a66893a /ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components
parentf18fbfc026de9cf02126f57844c37abfee607394 (diff)
Consolidate PolicyRestAdapter setup
Put common code into PolicyEngineUtils that the controllers use to populate the PolicyRestController. Also some more sonar cleanup and formatting of XML files. Shortened 120 line characters. Removed some trailing spaces from comments. Fixed up one JUnit. Licenses. Issue-ID: POLICY-2133 Change-Id: Id7d8ac3ab60331535f048ec0f26aeb17a099414e Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
Diffstat (limited to 'ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components')
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java5
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java52
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java37
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java27
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java122
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java75
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java82
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java5
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java115
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java85
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java339
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java4
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java206
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java2
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java205
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java25
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java105
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java5
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java9
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java43
20 files changed, 749 insertions, 799 deletions
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java
index 780ed86c7..c4076b2ad 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java
@@ -21,6 +21,7 @@
package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.pap.PAPException;
+
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
@@ -32,6 +33,7 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
@@ -47,6 +49,7 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
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.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -82,7 +85,6 @@ public class ActionPolicy extends Policy {
List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
-
private CommonClassDao commonClassDao;
private static boolean isAttribute = false;
@@ -360,7 +362,6 @@ public class ActionPolicy extends Policy {
return obligations;
}
-
// if compound setting the inner apply here
protected ApplyType getInnerActionApply(String value1Label) {
ApplyType actionApply = new ApplyType();
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java
index 8ca4dfa01..233add1ad 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java
@@ -2,7 +2,7 @@
* ============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.
@@ -20,6 +20,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.File;
import java.io.IOException;
import java.io.PrintWriter;
@@ -32,16 +35,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 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 +49,13 @@ 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;
+
public class ClosedLoopPolicy extends Policy {
private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPolicy.class);
@@ -68,7 +68,7 @@ public class ClosedLoopPolicy extends Policy {
this.policyAdapter = policyAdapter;
}
- //save configuration of the policy based on the policyname
+ // save configuration of the policy based on the policyname
private void saveConfigurations(String policyName, String jsonBody) {
if (policyName.endsWith(".xml")) {
@@ -76,7 +76,7 @@ public class ClosedLoopPolicy extends Policy {
}
try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json")) {
String body = jsonBody;
- //Remove the trapMaxAge in Verification Signature
+ // Remove the trapMaxAge in Verification Signature
body = body.replace(",\"trapMaxAge\":null", "");
this.policyAdapter.setJsonBody(body);
out.println(body);
@@ -85,7 +85,7 @@ public class ClosedLoopPolicy extends Policy {
}
}
- //Utility to read json data from the existing file to a string
+ // 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));
@@ -93,7 +93,7 @@ public class ClosedLoopPolicy extends Policy {
}
- //create the configuration file based on the policy name on adding the extension as .json
+ // create the configuration file based on the policy name on adding the extension as .json
private String getConfigFile(String filename) {
filename = FilenameUtils.removeExtension(filename);
if (filename.endsWith(".xml")) {
@@ -124,13 +124,13 @@ public class ClosedLoopPolicy extends Policy {
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 {
if (isPreparedToSave()) {
- //we have already done this
+ // we have already done this
return true;
}
@@ -176,17 +176,13 @@ public class ClosedLoopPolicy extends Policy {
// Match for Onap
allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
// Match for riskType
- allOf.getMatch().add(
- createDynamicMatch("RiskType", policyAdapter.getRiskType()));
+ allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
// Match for riskLevel
- allOf.getMatch().add(
- createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
+ allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
// Match for riskguard
- allOf.getMatch().add(
- createDynamicMatch("guard", policyAdapter.getGuard()));
+ allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
// Match for ttlDate
- allOf.getMatch().add(
- createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
+ allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
AnyOfType anyOf = new AnyOfType();
anyOf.getAllOf().add(allOfOne);
@@ -340,7 +336,7 @@ public class ClosedLoopPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment5);
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
assignment6.setAttributeId("RiskType");
assignment6.setCategory(CATEGORY_RESOURCE);
@@ -389,7 +385,6 @@ public class ClosedLoopPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment9);
-
advices.getAdviceExpression().add(advice);
return advices;
}
@@ -399,5 +394,4 @@ public class ClosedLoopPolicy extends Policy {
return policyAdapter.getPolicyData();
}
-
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java
index d6b09086a..1cab7166a 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java
@@ -2,7 +2,7 @@
* ============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.
* ================================================================================
@@ -22,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;
@@ -33,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;
@@ -58,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 {
/**
@@ -93,7 +93,6 @@ public class ConfigPolicy extends Policy {
}
}
-
// Here we are adding the extension for the configurations file based on the
// config type selection for saving.
private String getConfigFile(String filename) {
@@ -103,8 +102,7 @@ public class ConfigPolicy extends Policy {
if (id == null) {
return filename;
}
- switch (id.toUpperCase())
- {
+ switch (id.toUpperCase()) {
case JSON_CONFIG:
return filename + ".json";
case XML_CONFIG:
@@ -127,7 +125,6 @@ public class ConfigPolicy extends Policy {
return filename;
}
-
// Validations for Config form
/*
* FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
@@ -181,7 +178,7 @@ public class ConfigPolicy extends Policy {
}
if (!isPreparedToSave()) {
- //Prep and configure the policy for saving
+ // Prep and configure the policy for saving
prepareToSave();
}
@@ -192,8 +189,8 @@ public class ConfigPolicy extends Policy {
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 {
@@ -441,7 +438,7 @@ public class ConfigPolicy extends Policy {
}
}
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
assignment8.setAttributeId("RiskType");
assignment8.setCategory(CATEGORY_RESOURCE);
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java
index 9809ad498..8321505de 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 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.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.components;
import java.util.HashMap;
@@ -34,25 +35,27 @@ import org.springframework.stereotype.Service;
@Service
public class CreateBRMSRuleTemplate {
- private static final Logger LOGGER = FlexLogger.getLogger(CreateBRMSRuleTemplate.class);
+ private static final Logger LOGGER = FlexLogger.getLogger(CreateBRMSRuleTemplate.class);
private static CommonClassDao commonClassDao;
@Autowired
- public CreateBRMSRuleTemplate(CommonClassDao commonClassDao){
+ public CreateBRMSRuleTemplate(CommonClassDao commonClassDao) {
CreateBRMSRuleTemplate.commonClassDao = commonClassDao;
}
- public CreateBRMSRuleTemplate() {}
+ public CreateBRMSRuleTemplate() {
+ }
public Map<String, String> addRule(String rule, String ruleName, String description, String userID) {
- Map<String,String> responseMap = new HashMap<>();
- if(rule!=null && !PolicyUtils.brmsRawValidate(rule).contains("[ERR")){
- List<Object> duplicateData = commonClassDao.checkDuplicateEntry(ruleName, "ruleName", BRMSParamTemplate.class);
- if(duplicateData!=null && !duplicateData.isEmpty()){
+ Map<String, String> responseMap = new HashMap<>();
+ if (rule != null && !PolicyUtils.brmsRawValidate(rule).contains("[ERR")) {
+ List<Object> duplicateData =
+ commonClassDao.checkDuplicateEntry(ruleName, "ruleName", BRMSParamTemplate.class);
+ if (duplicateData != null && !duplicateData.isEmpty()) {
LOGGER.error("Import new service failed. Service already exists");
responseMap.put("DBError", "EXISTS");
return responseMap;
- }else{
+ } else {
BRMSParamTemplate brmsParamTemplate = new BRMSParamTemplate();
brmsParamTemplate.setDescription(description);
brmsParamTemplate.setRuleName(ruleName);
@@ -63,7 +66,7 @@ public class CreateBRMSRuleTemplate {
LOGGER.info("Template created with " + ruleName + " by " + userID);
}
responseMap.put("success", "success");
- }else{
+ } else {
LOGGER.debug("Error during validating the rule for creating record for BRMS Param Template");
responseMap.put("error", "VALIDATION");
}
@@ -73,8 +76,8 @@ public class CreateBRMSRuleTemplate {
public static boolean validateRuleParams(String rule) {
CreateBrmsParamPolicy policy = new CreateBrmsParamPolicy();
Map<String, String> paramValues = policy.findType(rule);
- for(String key : paramValues.keySet()) {
- if(!PolicyUtils.SUCCESS.equals(PolicyUtils.policySpecialCharValidator(key))){
+ for (String key : paramValues.keySet()) {
+ if (!PolicyUtils.SUCCESS.equals(PolicyUtils.policySpecialCharValidator(key))) {
return false;
}
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java
index 6a0c92650..7be1d39b0 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 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.
@@ -20,6 +20,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.File;
import java.io.IOException;
import java.io.PrintWriter;
@@ -41,19 +44,6 @@ 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;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController;
-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;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
@@ -68,6 +58,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.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController;
+import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.jpa.BRMSParamTemplate;
+
public class CreateBrmsParamPolicy extends Policy {
private static final Logger LOGGER = FlexLogger.getLogger(CreateBrmsParamPolicy.class);
@@ -91,19 +91,18 @@ public class CreateBrmsParamPolicy extends Policy {
copyMap.put("policyVersion", policyAdapter.getHighestVersion().toString());
copyMap.put("unique", ("p" + policyName + UUID.randomUUID().toString()).replaceAll("[^A-Za-z0-9]", ""));
- //Finding all the keys in the Map data-structure.
+ // Finding all the keys in the Map data-structure.
Iterator<String> iterator = copyMap.keySet().iterator();
Pattern p;
Matcher m;
while (iterator.hasNext()) {
- //Converting the first character of the key into a lower case.
+ // Converting the first character of the key into a lower case.
String input = iterator.next();
- String output = Character.toLowerCase(input.charAt(0)) +
- (input.length() > 1 ? input.substring(1) : "");
- //Searching for a pattern in the String using the key.
+ String output = Character.toLowerCase(input.charAt(0)) + (input.length() > 1 ? input.substring(1) : "");
+ // Searching for a pattern in the String using the key.
p = Pattern.compile("\\$\\{" + output + "\\}");
m = p.matcher(ruleContents);
- //Replacing the value with the inputs provided by the user in the editor.
+ // Replacing the value with the inputs provided by the user in the editor.
String finalInput = copyMap.get(input);
if (finalInput.contains("$")) {
finalInput = finalInput.replace("$", "\\$");
@@ -113,7 +112,6 @@ public class CreateBrmsParamPolicy extends Policy {
return ruleContents;
}
-
// 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));
@@ -137,7 +135,6 @@ public class CreateBrmsParamPolicy extends Policy {
}
}
-
// Here we are adding the extension for the configurations file based on the
// config type selection for saving.
private String getConfigFile(String filename) {
@@ -222,8 +219,7 @@ public class CreateBrmsParamPolicy extends Policy {
if (line.contains("*/")) {
try {
comment = false;
- line = line.split("\\/\\*")[0]
- + line.split("\\*\\/")[1].replace("*/", "");
+ line = line.split("\\/\\*")[0] + line.split("\\*\\/")[1].replace("*/", "");
} catch (Exception e) {
LOGGER.debug(e);
line = line.split("\\/\\*")[0];
@@ -255,8 +251,8 @@ public class CreateBrmsParamPolicy extends Policy {
break;
}
}
- String param = params.toString().replace("declare Params", "").replace("end", "")
- .replaceAll("\\s+", "");
+ String param =
+ params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", "");
String[] components = param.split(":");
String caption = "";
for (int i = 0; i < components.length; i++) {
@@ -274,7 +270,7 @@ public class CreateBrmsParamPolicy extends Policy {
LOGGER.debug(e);
nextComponent = components[i];
}
- //If the type is of type String then we add the UI Item and type to the map.
+ // If the type is of type String then we add the UI Item and type to the map.
if (nextComponent.startsWith("String")) {
type = "String";
mapFieldType.put(caption, type);
@@ -330,10 +326,8 @@ public class CreateBrmsParamPolicy extends Policy {
StringBuilder body = new StringBuilder();
try {
- body.append(
- "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI " +
- "purpose. \n\t " +
- "<$%BRMSParamTemplate=" + templateValue + "%$> \n");
+ body.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI "
+ + "purpose. \n\t " + "<$%BRMSParamTemplate=" + templateValue + "%$> \n");
body.append("<%$Values=");
for (Map.Entry<String, String> entry : ruleAndUIValue.entrySet()) {
String uiKey = entry.getKey();
@@ -344,8 +338,8 @@ public class CreateBrmsParamPolicy extends Policy {
body.append("$%> \n*/ \n");
body.append(valueFromDictionary + "\n");
} catch (Exception e) {
- PolicyLogger
- .error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy",
+ "Exception saving policy");
}
saveConfigurations(policyName, body.toString());
@@ -366,12 +360,10 @@ public class CreateBrmsParamPolicy extends Policy {
String fileName = policyAdapter.getNewFileName();
String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
if ((name == null) || (name.equals(""))) {
- name = fileName.substring(fileName.lastIndexOf("/") + 1
- );
+ name = fileName.substring(fileName.lastIndexOf("/") + 1);
}
allOfOne.getMatch().add(createMatch("PolicyName", name));
-
AllOfType allOf = new AllOfType();
// Match for ONAPName
@@ -419,8 +411,7 @@ public class CreateBrmsParamPolicy extends Policy {
}
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);
@@ -459,24 +450,20 @@ public class CreateBrmsParamPolicy 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
+ // Policy Config ID Assignment
AdviceExpressionsType advices = new AdviceExpressionsType();
AdviceExpressionType advice = new AdviceExpressionType();
advice.setAdviceId("BRMSPARAMID");
@@ -489,8 +476,7 @@ public class CreateBrmsParamPolicy extends Policy {
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.
@@ -505,8 +491,7 @@ public class CreateBrmsParamPolicy extends Policy {
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
@@ -518,15 +503,12 @@ public class CreateBrmsParamPolicy extends Policy {
attributeValue3.setDataType(STRING_DATATYPE);
fileName = FilenameUtils.removeExtension(fileName);
fileName = fileName + ".xml";
- String name = fileName.substring(fileName.lastIndexOf("\\") + 1
- );
+ String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
if ((name == null) || (name.equals(""))) {
- name = fileName.substring(fileName.lastIndexOf("/") + 1
- );
+ name = fileName.substring(fileName.lastIndexOf("/") + 1);
}
attributeValue3.getContent().add(name);
- assignment3.setExpression(new ObjectFactory()
- .createAttributeValue(attributeValue3));
+ assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
advice.getAttributeAssignmentExpression().add(assignment3);
// Version Number Assignment
@@ -537,8 +519,7 @@ public class CreateBrmsParamPolicy extends Policy {
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
@@ -549,12 +530,10 @@ public class CreateBrmsParamPolicy extends Policy {
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);
@@ -564,16 +543,15 @@ public class CreateBrmsParamPolicy extends Policy {
configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
advice.getAttributeAssignmentExpression().add(assignment6);
- // Adding Controller Information.
+ // 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.
+ // Adding Dependencies.
if (policyAdapter.getBrmsDependency() != null) {
BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
ArrayList<String> dependencies = new ArrayList<>();
@@ -582,18 +560,18 @@ public class CreateBrmsParamPolicy extends Policy {
dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency());
key.append(dependencyName + ",");
}
- 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 (Entry<String, String> map : dynamicFieldConfigAttributes.entrySet()) {
advice.getAttributeAssignmentExpression()
.add(createResponseAttributes("key:" + map.getKey(), map.getValue()));
}
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
assignment8.setAttributeId("RiskType");
assignment8.setCategory(CATEGORY_RESOURCE);
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java
index efa28b2bb..bb46fd6a9 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java
@@ -2,7 +2,7 @@
* ============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.
@@ -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,6 +50,11 @@ 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 {
@@ -76,8 +74,7 @@ public class CreateBrmsRawPolicy extends Policy {
protected void saveConfigurations(String policyName, String jsonBody) {
if (policyName.endsWith(".xml")) {
- policyName = policyName.substring(0,
- policyName.lastIndexOf(".xml"));
+ policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
}
try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")) {
out.println(jsonBody);
@@ -195,7 +192,6 @@ public class CreateBrmsRawPolicy extends Policy {
}
allOfOne.getMatch().add(createMatch("PolicyName", name));
-
AllOfType allOf = new AllOfType();
// Match for ONAPName
@@ -243,8 +239,7 @@ public class CreateBrmsRawPolicy extends Policy {
}
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);
@@ -267,8 +262,7 @@ public class CreateBrmsRawPolicy extends Policy {
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);
@@ -284,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();
@@ -314,8 +304,7 @@ public class CreateBrmsRawPolicy extends Policy {
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.
@@ -330,8 +319,7 @@ public class CreateBrmsRawPolicy extends Policy {
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
@@ -350,8 +338,7 @@ public class CreateBrmsRawPolicy extends Policy {
}
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
@@ -362,8 +349,7 @@ public class CreateBrmsRawPolicy extends Policy {
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
@@ -374,12 +360,10 @@ public class CreateBrmsRawPolicy extends Policy {
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);
@@ -390,16 +374,15 @@ public class CreateBrmsRawPolicy extends Policy {
assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
advice.getAttributeAssignmentExpression().add(assignment6);
- // Adding Controller Information.
+ // 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.
+ // Adding Dependencies.
if (policyAdapter.getBrmsDependency() != null) {
BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
ArrayList<String> dependencies = new ArrayList<>();
@@ -408,11 +391,11 @@ public class CreateBrmsRawPolicy extends Policy {
dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency());
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 (Map.Entry<String, String> entry : dynamicFieldConfigAttributes.entrySet()) {
String keyField = entry.getKey();
@@ -420,7 +403,7 @@ public class CreateBrmsRawPolicy extends Policy {
.add(createResponseAttributes("key:" + keyField, entry.getValue()));
}
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
assignment8.setAttributeId("RiskType");
assignment8.setCategory(CATEGORY_RESOURCE);
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java
index e74cc3359..a980e70d8 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java
@@ -2,7 +2,7 @@
* ============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.
@@ -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.PrintWriter;
@@ -30,16 +32,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 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;
@@ -54,40 +46,47 @@ 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;
+
public class CreateClosedLoopPerformanceMetrics extends Policy {
- private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class);
+ private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class);
public CreateClosedLoopPerformanceMetrics() {
super();
}
- public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter){
+ public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter) {
this.policyAdapter = policyAdapter;
}
- //save configuration of the policy based on the policyname
+ // save configuration of the policy based on the policyname
private void saveConfigurations(String policyName, final String jsonBody) {
- if(policyName.endsWith(".xml")){
- policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
- }
- try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "."+ policyName +".json")){
+ if (policyName.endsWith(".xml")) {
+ policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
+ }
+ try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "." + policyName + ".json")) {
out.println(jsonBody);
policyAdapter.setJsonBody(jsonBody);
policyAdapter.setConfigBodyData(jsonBody);
} catch (Exception e) {
- LOGGER.error("Exception Occured"+e);
+ LOGGER.error("Exception Occured" + e);
}
}
- //getting the policy name and setting to configuration on adding .json
+ // getting the policy name and setting to configuration on adding .json
private String getConfigFile(String filename) {
filename = FilenameUtils.removeExtension(filename);
if (filename.endsWith(".xml")) {
filename = filename.substring(0, filename.length() - 4);
}
- filename = filename +".json";
+ filename = filename + ".json";
return filename;
}
@@ -95,13 +94,13 @@ public class CreateClosedLoopPerformanceMetrics 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();
}
@@ -109,18 +108,18 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
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()){
- //we have already done this
+ if (isPreparedToSave()) {
+ // we have already done this
return true;
}
@@ -148,7 +147,6 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
policyName = policyName + ".xml";
}
-
PolicyType configPolicy = (PolicyType) policyAdapter.getData();
configPolicy.setDescription(policyAdapter.getPolicyDescription());
@@ -167,17 +165,13 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
// Adding the matches to AllOfType element Match for Onap
allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
// Match for riskType
- allOf.getMatch().add(
- createDynamicMatch("RiskType", policyAdapter.getRiskType()));
+ allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
// Match for riskLevel
- allOf.getMatch().add(
- createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
+ allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
// Match for riskguard
- allOf.getMatch().add(
- createDynamicMatch("guard", policyAdapter.getGuard()));
+ allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
// Match for ttlDate
- allOf.getMatch().add(
- createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
+ allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
// Match for ServiceType
allOf.getMatch().add(createMatch("ServiceType", policyAdapter.getServiceType()));
@@ -210,7 +204,8 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
try {
accessURI = new URI(ACTION_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating ACCESS URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics",
+ "Exception creating ACCESS URI");
}
accessAttributeDesignator.setCategory(CATEGORY_ACTION);
accessAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -229,7 +224,8 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
try {
configURI = new URI(RESOURCE_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating Config URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics",
+ "Exception creating Config URI");
}
configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
configAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -286,7 +282,7 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
AttributeValueType AttributeValue = new AttributeValueType();
AttributeValue.setDataType(URI_DATATYPE);
- String content = CONFIG_URL +"/Config/"+ getConfigFile(policyName);
+ String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
AttributeValue.getContent().add(content);
assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
@@ -344,7 +340,7 @@ public class CreateClosedLoopPerformanceMetrics extends Policy {
advice.getAttributeAssignmentExpression().add(assignment6);
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
assignment7.setAttributeId("RiskType");
assignment7.setCategory(CATEGORY_RESOURCE);
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java
index 103928cbc..9b8854ff8 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java
@@ -22,6 +22,7 @@
package org.onap.policy.pap.xacml.rest.components;
import com.google.gson.Gson;
+
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
@@ -36,6 +37,7 @@ import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
+
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.onap.policy.common.logging.eelf.MessageCodes;
@@ -55,7 +57,6 @@ public class CreateNewMicroServiceModel {
private MicroServiceModels newModel = null;
private HashMap<String, MSAttributeObject> classMap = new HashMap<>();
-
private MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) {
@@ -145,7 +146,6 @@ public class CreateNewMicroServiceModel {
try {
-
utils.parseTosca(fileName);
MSAttributeObject msAttributes = new MSAttributeObject();
@@ -269,7 +269,6 @@ public class CreateNewMicroServiceModel {
}
mainClass = classMap.get(this.newModel.getModelName());
-
if (".yml".equalsIgnoreCase(type)) {
newModel.setDependency("[]");
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java
index 87c9f9108..0f52b9bae 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -20,6 +20,8 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.google.gson.Gson;
+
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
@@ -47,24 +49,22 @@ import org.onap.policy.rest.util.MSAttributeObject;
import org.onap.policy.rest.util.MSModelUtils;
import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
-import com.google.gson.Gson;
-
public class CreateNewOptimizationModel {
private static final Logger logger = FlexLogger.getLogger(CreateNewOptimizationModel.class);
private OptimizationModels newModel = null;
- private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
+ private HashMap<String, MSAttributeObject> classMap = new HashMap<>();
private static final String EXTRACTDIR = "ExtractDir";
private static final String SUCCESS = "success";
-
MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
public CreateNewOptimizationModel() {
super();
}
- public CreateNewOptimizationModel(String importFile, String modelName, String description, String version, String randomID) {
+ public CreateNewOptimizationModel(String importFile, String modelName, String description, String version,
+ String randomID) {
this.newModel = new OptimizationModels();
this.newModel.setVersion(version);
@@ -76,14 +76,14 @@ public class CreateNewOptimizationModel {
String cleanUpFile = null;
Map<String, MSAttributeObject> tempMap = new HashMap<>();
- //Need to delete the file
- if (importFile.contains(".zip")){
+ // Need to delete the file
+ if (importFile.contains(".zip")) {
extractFolder(randomID + ".zip");
File directory = new File(EXTRACTDIR + File.separator + randomID);
List<File> fileList = listModelFiles(directory.toString());
- //get all the files from a director
- for (File file : fileList){
- if (file.isFile()){
+ // get all the files from a director
+ for (File file : fileList) {
+ if (file.isFile()) {
processYmlModel(file.toString(), modelName);
}
}
@@ -96,32 +96,32 @@ public class CreateNewOptimizationModel {
} catch (IOException e) {
logger.error("Failed to unzip model file " + randomID, e);
}
- }else {
- if(importFile.contains(".yml")){
+ } else {
+ if (importFile.contains(".yml")) {
- processYmlModel(EXTRACTDIR + File.separator + randomID+".yml", modelName);
- cleanUpFile = EXTRACTDIR + File.separator + randomID+".yml";
+ processYmlModel(EXTRACTDIR + File.separator + randomID + ".yml", modelName);
+ cleanUpFile = EXTRACTDIR + File.separator + randomID + ".yml";
- }else{
- tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID+".xmi", MODEL_TYPE.XMI);
+ } else {
+ tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID + ".xmi", MODEL_TYPE.XMI);
classMap.putAll(tempMap);
- cleanUpFile = EXTRACTDIR + File.separator + randomID+".xmi";
+ cleanUpFile = EXTRACTDIR + File.separator + randomID + ".xmi";
}
File deleteFile = new File(cleanUpFile);
deleteFile.delete();
}
}
- private void processYmlModel(String fileName, String modelName){
+ private void processYmlModel(String fileName, String modelName) {
try {
utils.parseTosca(fileName);
- MSAttributeObject msAttributes= new MSAttributeObject();
+ MSAttributeObject msAttributes = new MSAttributeObject();
msAttributes.setClassName(modelName);
- LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>();
+ LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
returnAttributeList.put(modelName, utils.getAttributeString());
msAttributes.setAttribute(returnAttributeList);
@@ -129,24 +129,24 @@ public class CreateNewOptimizationModel {
msAttributes.setMatchingSet(utils.getMatchableValues());
- LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>();
+ LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
returnReferenceList.put(modelName, utils.getReferenceAttributes());
msAttributes.setRefAttribute(returnReferenceList);
- if(!"".equals(utils.getListConstraints())){
- LinkedHashMap<String, String> enumList =new LinkedHashMap<>();
- String[] listArray=utils.getListConstraints().split("#");
- for(String str:listArray){
- String[] strArr= str.split("=");
- if(strArr.length>1){
+ if (!"".equals(utils.getListConstraints())) {
+ LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
+ String[] listArray = utils.getListConstraints().split("#");
+ for (String str : listArray) {
+ String[] strArr = str.split("=");
+ if (strArr.length > 1) {
enumList.put(strArr[0], strArr[1]);
}
}
msAttributes.setEnumType(enumList);
}
- classMap=new LinkedHashMap<>();
+ classMap = new LinkedHashMap<>();
classMap.put(modelName, msAttributes);
} catch (Exception e) {
@@ -174,13 +174,13 @@ public class CreateNewOptimizationModel {
int buffer = 2048;
File file = new File(zipFile);
- try(ZipFile zip = new ZipFile(EXTRACTDIR + File.separator +file);){
- String newPath = zipFile.substring(0, zipFile.length() - 4);
+ try (ZipFile zip = new ZipFile(EXTRACTDIR + File.separator + file);) {
+ String newPath = zipFile.substring(0, zipFile.length() - 4);
new File(newPath).mkdir();
Enumeration zipFileEntries = zip.entries();
// Process each entry
- while (zipFileEntries.hasMoreElements()){
+ while (zipFileEntries.hasMoreElements()) {
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
@@ -189,13 +189,13 @@ public class CreateNewOptimizationModel {
destinationParent.mkdirs();
- if (!entry.isDirectory()){
+ if (!entry.isDirectory()) {
int currentByte;
byte[] data = new byte[buffer];
- try(FileOutputStream fos = new FileOutputStream(destFile);
+ try (FileOutputStream fos = new FileOutputStream(destFile);
BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
- BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {
+ BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {
while ((currentByte = is.read(data, 0, buffer)) != -1) {
dest.write(data, 0, currentByte);
@@ -204,7 +204,7 @@ public class CreateNewOptimizationModel {
}
}
- if (currentEntry.endsWith(".zip")){
+ if (currentEntry.endsWith(".zip")) {
extractFolder(destFile.getAbsolutePath());
}
}
@@ -218,38 +218,40 @@ public class CreateNewOptimizationModel {
Map<String, String> successMap = new HashMap<>();
MSAttributeObject mainClass;
- if (!classMap.containsKey(this.newModel.getModelName())){
- logger.error("Model Provided does not contain the service name provided in request. Unable to import new model");
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request");
+ if (!classMap.containsKey(this.newModel.getModelName())) {
+ logger.error(
+ "Model Provided does not contain the service name provided in request. Unable to import new model");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel",
+ "Unable to pull out required values, file missing service name provided in request");
successMap.put("error", "MISSING");
return successMap;
}
mainClass = classMap.get(this.newModel.getModelName());
newModel.setDependency("[]");
- if(mainClass.getSubClass() != null){
- String value = new Gson().toJson(mainClass.getSubClass());
- newModel.setSubattributes(value);
+ if (mainClass.getSubClass() != null) {
+ String value = new Gson().toJson(mainClass.getSubClass());
+ newModel.setSubattributes(value);
}
- if(mainClass.getAttribute() != null){
- String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", "");
- int equalsIndexForAttributes= attributes.indexOf('=');
- String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1);
+ if (mainClass.getAttribute() != null) {
+ String attributes = mainClass.getAttribute().toString().replace("{", "").replace("}", "");
+ int equalsIndexForAttributes = attributes.indexOf('=');
+ String atttributesAfterFirstEquals = attributes.substring(equalsIndexForAttributes + 1);
this.newModel.setAttributes(atttributesAfterFirstEquals);
}
- if(mainClass.getRefAttribute() != null){
- String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
- int equalsIndex= refAttributes.indexOf('=');
- String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1);
+ if (mainClass.getRefAttribute() != null) {
+ String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
+ int equalsIndex = refAttributes.indexOf('=');
+ String refAttributesAfterFirstEquals = refAttributes.substring(equalsIndex + 1);
this.newModel.setRefattributes(refAttributesAfterFirstEquals);
}
- if(mainClass.getEnumType() != null){
+ if (mainClass.getEnumType() != null) {
this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
}
- if(mainClass.getMatchingSet() != null){
+ if (mainClass.getMatchingSet() != null) {
this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
}
@@ -258,14 +260,15 @@ public class CreateNewOptimizationModel {
}
- public Map<String, String> saveImportService(){
+ public Map<String, String> saveImportService() {
String modelName = this.newModel.getModelName();
String importedBy = "API";
String version = this.newModel.getVersion();
Map<String, String> successMap = new HashMap<>();
CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
- List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+version);
- if(result.isEmpty()){
+ List<Object> result =
+ dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + version);
+ if (result.isEmpty()) {
OptimizationModels model = new OptimizationModels();
model.setModelName(modelName);
model.setVersion(version);
@@ -283,7 +286,7 @@ public class CreateNewOptimizationModel {
model.setUserCreatedBy(userInfo);
dbConnection.save(model);
successMap.put(SUCCESS, SUCCESS);
- }else{
+ } else {
successMap.put("DBError", "EXISTS");
logger.error("Import new service failed. Service already exists");
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java
index da5c6aea1..ed1d551b4 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java
@@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.XACML3;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.std.IdentifierImpl;
+
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
@@ -40,6 +41,25 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
+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;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
+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 oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
+
import org.apache.commons.lang3.StringEscapeUtils;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
@@ -63,25 +83,6 @@ import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine;
import org.onap.policy.xacml.util.XACMLPolicyScanner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-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;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
-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 oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
-
@Component
public class DecisionPolicy extends Policy {
@@ -103,7 +104,6 @@ public class DecisionPolicy extends Policy {
private static final String POLICY_NAME = "PolicyName";
private static final String DESCRIPTION = "description";
-
List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<>();
List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
@@ -154,16 +154,15 @@ public class DecisionPolicy extends Policy {
private void readRawPolicyData() {
Object policy;
if ("API".equalsIgnoreCase(policyAdapter.getApiflag())) {
- policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils
- .unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8)));
+ policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(
+ StringEscapeUtils.unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8)));
} else {
policy = XACMLPolicyScanner.readPolicy(
new ByteArrayInputStream(policyAdapter.getRawXacmlPolicy().getBytes(StandardCharsets.UTF_8)));
}
String policyRawDesc;
if (policy instanceof PolicySetType) {
- policyRawDesc =
- ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
+ policyRawDesc = ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
((PolicySetType) policy).setDescription(policyRawDesc);
} else {
policyRawDesc = ((PolicyType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
@@ -204,13 +203,13 @@ public class DecisionPolicy extends Policy {
}
policyName = policyAdapter.getNewFileName();
- if(policyAdapter.getRuleProvider().equals(GUARD_YAML) ||
- policyAdapter.getRuleProvider().equals(GUARD_BL_YAML) ||
- policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)){
+ if (policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML)
+ || policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)) {
Map<String, String> yamlParams = new HashMap<>();
- String blackListEntryType = policyAdapter.getBlackListEntryType() != null
- ? policyAdapter.getBlackListEntryType() : "Use Manual Entry";
+ String blackListEntryType =
+ policyAdapter.getBlackListEntryType() != null ? policyAdapter.getBlackListEntryType()
+ : "Use Manual Entry";
String description = policyAdapter.getPolicyDescription() != null ? policyAdapter.getPolicyDescription()
: "YAML Guard Policy";
yamlParams.put(DESCRIPTION, description + "@blEntry@" + blackListEntryType + "@blEntry@");
@@ -428,8 +427,7 @@ public class DecisionPolicy extends Policy {
yamlSpecs.put("guardActiveStart", constraints.getActive_time_range().get("start"));
yamlSpecs.put("guardActiveEnd", constraints.getActive_time_range().get("end"));
String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent, yamlSpecs,
- constraints.getBlacklist(),
- guard.getMatch_parameters().getTargets());
+ constraints.getBlacklist(), guard.getMatch_parameters().getTargets());
// Convert the Policy into Stream input to Policy Adapter.
Object policy = XACMLPolicyScanner
@@ -713,7 +711,8 @@ public class DecisionPolicy extends Policy {
if (!attributeId.startsWith("S_")) {
ApplyType innerDecisionApply = generateApplyTypeDataType(functionKey);
AttributeDesignatorType attributeDesignator = generateAttributeDesignatorDataType(functionKey);
- AttributeValueType decisionConditionAttributeValue = generateAttributeValueTypeDataType(functionKey);
+ AttributeValueType decisionConditionAttributeValue =
+ generateAttributeValueTypeDataType(functionKey);
if (attributeId != null) {
attributeDesignator.setCategory(CATEGORY_RESOURCE);
@@ -793,7 +792,6 @@ public class DecisionPolicy extends Policy {
dataTypeList.add(dataType);
}
-
private String getDataType(String key) {
DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
@@ -826,8 +824,7 @@ public class DecisionPolicy extends Policy {
private AttributeDesignatorType generateAttributeDesignatorDataType(String functionKey) {
AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
- switch(functionKey.toLowerCase())
- {
+ switch (functionKey.toLowerCase()) {
case "integer":
attributeDesignator.setDataType(INTEGER_DATATYPE);
break;
@@ -839,8 +836,7 @@ public class DecisionPolicy extends Policy {
private ApplyType generateApplyTypeDataType(String functionKey) {
ApplyType applyType = new ApplyType();
- switch(functionKey.toLowerCase())
- {
+ switch (functionKey.toLowerCase()) {
case "integer":
applyType.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
break;
@@ -852,8 +848,7 @@ public class DecisionPolicy extends Policy {
private AttributeValueType generateAttributeValueTypeDataType(String functionKey) {
AttributeValueType applyType = new AttributeValueType();
- switch(functionKey.toLowerCase())
- {
+ switch (functionKey.toLowerCase()) {
case "integer":
applyType.setDataType(INTEGER_DATATYPE);
break;
@@ -864,8 +859,10 @@ public class DecisionPolicy extends Policy {
}
private void applyTwoTextFieldRuleAttribute(ApplyType decisionApply, String value1, String functionKey) {
- decisionApply.getExpression().add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey)));
- decisionApply.getExpression().add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey)));
+ decisionApply.getExpression()
+ .add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey)));
+ decisionApply.getExpression()
+ .add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey)));
}
private ApplyType generateApplyTypeDataType(String value1, String functionKey) {
@@ -874,10 +871,8 @@ public class DecisionPolicy extends Policy {
attributeDesignator.setCategory(CATEGORY_RESOURCE);
// Here set actual field values
- attributeDesignator
- .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8));
- innerApply.getExpression()
- .add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
+ attributeDesignator.setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8));
+ innerApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
return innerApply;
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java
index 228dc83d2..01c211cdb 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java
@@ -26,6 +26,7 @@ import com.att.research.xacml.std.IdentifierImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonpatch.diff.JsonDiff;
+
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
@@ -41,11 +42,27 @@ import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.script.SimpleBindings;
+
+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;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
+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;
@@ -66,19 +83,6 @@ import org.onap.policy.rest.jpa.TermList;
import org.onap.policy.rest.jpa.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-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;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
-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;
@Component
public class FirewallConfigPolicy extends Policy {
@@ -114,11 +118,11 @@ public class FirewallConfigPolicy extends Policy {
LOGGER.debug("Configuration is succesfully saved");
}
} catch (IOException e) {
- LOGGER.error("Save of configuration to file" +fileName+ "failed",e);
+ LOGGER.error("Save of configuration to file" + fileName + "failed", e);
}
}
- //Utility to read json data from the existing file to a string
+ // 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);
@@ -127,11 +131,11 @@ public class FirewallConfigPolicy extends Policy {
@Override
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()){
+ if (!isPreparedToSave()) {
prepareToSave();
}
@@ -139,9 +143,10 @@ public class FirewallConfigPolicy extends Policy {
Path newPolicyPath = null;
newPolicyPath = Paths.get(policyAdapter.getNewFileName());
Boolean dbIsUpdated = false;
- if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){
+ if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())) {
if (policyAdapter.isEditPolicy()) {
- dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
+ dbIsUpdated =
+ updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody());
} else {
try {
dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody());
@@ -153,14 +158,14 @@ public class FirewallConfigPolicy extends Policy {
dbIsUpdated = true;
}
- if(dbIsUpdated) {
- successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
+ if (dbIsUpdated) {
+ successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
} else {
PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
- //remove the new json file
+ // remove the new json file
String jsonBody = policyAdapter.getPrevJsonBody();
- if (jsonBody!=null){
+ if (jsonBody != null) {
saveConfigurations(policyName, jsonBody);
} else {
saveConfigurations(policyName, "");
@@ -171,13 +176,13 @@ public class FirewallConfigPolicy extends Policy {
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()){
- //we have already done this
+ if (isPreparedToSave()) {
+ // we have already done this
return true;
}
@@ -196,13 +201,13 @@ public class FirewallConfigPolicy extends Policy {
}
policyName = policyAdapter.getNewFileName();
- //String oldPolicyName = policyName.replace(".xml", "");
+ // String oldPolicyName = policyName.replace(".xml", "");
String scope = policyName.substring(0, policyName.indexOf('.'));
- String dbPolicyName = policyName.substring(policyName.indexOf('.')+1).replace(".xml", "");
+ String dbPolicyName = policyName.substring(policyName.indexOf('.') + 1).replace(".xml", "");
- int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.')+1));
- dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.')+1);
- if(oldversion > 1){
+ int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.') + 1));
+ dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.') + 1);
+ if (oldversion > 1) {
oldversion = oldversion - 1;
dbPolicyName = dbPolicyName + oldversion + ".xml";
}
@@ -277,7 +282,8 @@ public class FirewallConfigPolicy extends Policy {
try {
accessURI = new URI(ACTION_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy",
+ "Exception creating ACCESS URI");
}
accessAttributeDesignator.setCategory(CATEGORY_ACTION);
accessAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -298,7 +304,8 @@ public class FirewallConfigPolicy extends Policy {
try {
configURI = new URI(RESOURCE_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy",
+ "Exception creating Config URI");
}
configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
@@ -332,7 +339,7 @@ public class FirewallConfigPolicy extends Policy {
// Data required for Advice part is setting here.
private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
- //Firewall Config ID Assignment
+ // Firewall Config ID Assignment
AdviceExpressionsType advices = new AdviceExpressionsType();
AdviceExpressionType advice = new AdviceExpressionType();
advice.setAdviceId("firewallConfigID");
@@ -349,7 +356,7 @@ public class FirewallConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment1);
// For Config file Url if configurations are provided.
- //URL ID Assignment
+ // URL ID Assignment
AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
assignment2.setAttributeId("URLID");
assignment2.setCategory(CATEGORY_RESOURCE);
@@ -365,7 +372,7 @@ public class FirewallConfigPolicy extends Policy {
assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
advice.getAttributeAssignmentExpression().add(assignment2);
- //Policy Name Assignment
+ // Policy Name Assignment
AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
assignment3.setAttributeId("PolicyName");
assignment3.setCategory(CATEGORY_RESOURCE);
@@ -382,7 +389,7 @@ public class FirewallConfigPolicy extends Policy {
assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
advice.getAttributeAssignmentExpression().add(assignment3);
- //Version Number Assignment
+ // Version Number Assignment
AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
assignment4.setAttributeId("VersionNumber");
assignment4.setCategory(CATEGORY_RESOURCE);
@@ -393,7 +400,7 @@ public class FirewallConfigPolicy extends Policy {
assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
advice.getAttributeAssignmentExpression().add(assignment4);
- //Onap Name Assignment
+ // Onap Name Assignment
AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
assignment5.setAttributeId("matching:" + ONAPID);
assignment5.setCategory(CATEGORY_RESOURCE);
@@ -403,7 +410,7 @@ public class FirewallConfigPolicy extends Policy {
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);
@@ -414,7 +421,7 @@ public class FirewallConfigPolicy extends Policy {
assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
advice.getAttributeAssignmentExpression().add(assignment6);
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
assignment7.setAttributeId("RiskType");
assignment7.setCategory(CATEGORY_RESOURCE);
@@ -466,19 +473,18 @@ public class FirewallConfigPolicy extends Policy {
return advices;
}
-
- private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException {
+ private Boolean insertFirewallDicionaryData(String jsonBody) throws SQLException {
CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
JsonObject json = null;
if (jsonBody != null) {
- //Read jsonBody to JsonObject
+ // Read jsonBody to JsonObject
json = stringToJson(jsonBody);
JsonArray firewallRules = null;
JsonArray serviceGroup = null;
JsonArray addressGroup = null;
- //insert data into tables
+ // insert data into tables
try {
firewallRules = json.getJsonArray("firewallRuleList");
serviceGroup = json.getJsonArray("serviceGroups");
@@ -487,28 +493,28 @@ public class FirewallConfigPolicy extends Policy {
* Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
*/
if (firewallRules != null) {
- for(int i = 0;i<firewallRules.size();i++) {
+ for (int i = 0; i < firewallRules.size(); i++) {
/*
* Populate ArrayLists with values from the JSON
*/
- //create the JSON object from the JSON Array for each iteration through the for loop
+ // create the JSON object from the JSON Array for each iteration through the for loop
JsonObject ruleListobj = firewallRules.getJsonObject(i);
- //get values from JSON fields of firewallRulesList Array
+ // get values from JSON fields of firewallRulesList Array
String ruleName = ruleListobj.get("ruleName").toString();
String action = ruleListobj.get("action").toString();
String description = ruleListobj.get("description").toString();
List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
- if(result != null && !result.isEmpty()){
+ if (result != null && !result.isEmpty()) {
TermList termEntry = (TermList) result.get(0);
dbConnection.delete(termEntry);
}
- //getting fromZone Array field from the firewallRulesList
+ // getting fromZone Array field from the firewallRulesList
JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
String fromZoneString = null;
- for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) {
+ for (int fromZoneIndex = 0; fromZoneIndex < fromZoneArray.size(); fromZoneIndex++) {
String value = fromZoneArray.get(fromZoneIndex).toString();
value = value.replace("\"", "");
if (fromZoneString != null) {
@@ -517,12 +523,12 @@ public class FirewallConfigPolicy extends Policy {
fromZoneString = value;
}
}
- String fromZoneInsert = "'"+fromZoneString+"'";
+ String fromZoneInsert = "'" + fromZoneString + "'";
- //getting toZone Array field from the firewallRulesList
+ // getting toZone Array field from the firewallRulesList
JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
String toZoneString = null;
- for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) {
+ for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
String value = toZoneArray.get(toZoneIndex).toString();
value = value.replace("\"", "");
if (toZoneString != null) {
@@ -531,19 +537,19 @@ public class FirewallConfigPolicy extends Policy {
toZoneString = value;
}
}
- String toZoneInsert = "'"+toZoneString+"'";
+ String toZoneInsert = "'" + toZoneString + "'";
- //getting sourceList Array fields from the firewallRulesList
+ // getting sourceList Array fields from the firewallRulesList
JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
String srcListString = null;
- for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) {
+ for (int srcListIndex = 0; srcListIndex < srcListArray.size(); srcListIndex++) {
JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
String type = srcListObj.get("type").toString().replace("\"", "");
String value = null;
- if(type.equals("REFERENCE")||type.equals("GROUP")){
+ if (type.equals("REFERENCE") || type.equals("GROUP")) {
value = srcListObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = srcListObj.get("value").toString();
@@ -552,19 +558,19 @@ public class FirewallConfigPolicy extends Policy {
srcListString = getLeftOrRight(srcListString, value);
}
- String srcListInsert = "'"+srcListString+"'";
+ String srcListInsert = "'" + srcListString + "'";
- //getting destinationList Array fields from the firewallRulesList
+ // getting destinationList Array fields from the firewallRulesList
JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
String destListString = null;
- for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) {
+ for (int destListIndex = 0; destListIndex < destListArray.size(); destListIndex++) {
JsonObject destListObj = destListArray.getJsonObject(destListIndex);
String type = destListObj.get("type").toString().replace("\"", "");
String value = null;
- if(type.equals("REFERENCE")||type.equals("GROUP")){
+ if (type.equals("REFERENCE") || type.equals("GROUP")) {
value = destListObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = destListObj.get("value").toString();
@@ -572,19 +578,20 @@ public class FirewallConfigPolicy extends Policy {
destListString = getLeftOrRight(destListString, value);
}
- String destListInsert = "'"+destListString+"'";
+ String destListInsert = "'" + destListString + "'";
- //getting destServices Array fields from the firewallRulesList
+ // getting destServices Array fields from the firewallRulesList
JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
String destPortListString = null;
- for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
+ for (int destPortListIndex = 0; destPortListIndex < destServicesArray
+ .size(); destPortListIndex++) {
JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
String type = destServicesObj.get("type").toString().replace("\"", "");
String value = null;
- if(type.equals("REFERENCE")||type.equals("GROUP")){
+ if (type.equals("REFERENCE") || type.equals("GROUP")) {
value = destServicesObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = destServicesObj.get("value").toString();
@@ -592,7 +599,7 @@ public class FirewallConfigPolicy extends Policy {
destPortListString = getLeftOrRight(destPortListString, value);
}
- String destPortListInsert = "'"+destPortListString+"'";
+ String destPortListInsert = "'" + destPortListString + "'";
/*
* Create Queries to INSERT data into database tables and execute
@@ -624,35 +631,35 @@ public class FirewallConfigPolicy extends Policy {
* Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
*/
if (serviceGroup != null) {
- for(int i = 0; i < serviceGroup.size() ; i++) {
+ for (int i = 0; i < serviceGroup.size(); i++) {
/*
* Populate ArrayLists with values from the JSON
*/
- //create the JSON object from the JSON Array for each iteration through the for loop
+ // create the JSON object from the JSON Array for each iteration through the for loop
JsonObject svcGroupListobj = serviceGroup.getJsonObject(i);
String serviceListName = svcGroupListobj.get("name").toString();
String description = null;
- if (svcGroupListobj.containsKey("description")){
+ if (svcGroupListobj.containsKey("description")) {
description = svcGroupListobj.get("description").toString();
}
- //getting members Array from the serviceGroup
+ // getting members Array from the serviceGroup
JsonArray membersArray = svcGroupListobj.getJsonArray("members");
- //String type = svcGroupListobj.get("type").toString();
+ // String type = svcGroupListobj.get("type").toString();
Boolean isServiceGroup = false;
- if (membersArray!=null){
+ if (membersArray != null) {
String membersType = membersArray.getJsonObject(0).get("type").toString();
if (membersType.contains("REFERENCE")) {
isServiceGroup = true;
}
}
- //Insert values into GROUPSERVICELIST table if name begins with Group
+ // Insert values into GROUPSERVICELIST table if name begins with Group
if (isServiceGroup) {
saveGroupServiceListTableToDb(dbConnection, serviceListName, membersArray);
- } else { //Insert JSON data serviceList table, protollist table, and portlist table
+ } else { // Insert JSON data serviceList table, protollist table, and portlist table
String type = svcGroupListobj.get("type").toString();
String transportProtocol = svcGroupListobj.get("transportProtocol").toString();
String ports = svcGroupListobj.get("ports").toString();
@@ -660,7 +667,8 @@ public class FirewallConfigPolicy extends Policy {
/*
* Create Queries to INSERT data into database table and execute
*/
- saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol, ports);
+ saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol,
+ ports);
saveProtocolListToDb(dbConnection, transportProtocol);
@@ -673,19 +681,19 @@ public class FirewallConfigPolicy extends Policy {
* Inserting addressGroup data into the ADDRESSGROUP table
*/
if (addressGroup != null) {
- for(int i = 0; i < addressGroup.size(); i++) {
+ for (int i = 0; i < addressGroup.size(); i++) {
/*
* Populate ArrayLists with values from the JSON
*/
- //create the JSON object from the JSON Array for each iteration through the for loop
+ // create the JSON object from the JSON Array for each iteration through the for loop
JsonObject addressGroupObj = addressGroup.getJsonObject(i);
- //create JSON array for members
+ // create JSON array for members
JsonArray membersArray = addressGroupObj.getJsonArray("members");
String addressGroupName = addressGroupObj.get("name").toString();
String description = null;
- if (addressGroupObj.containsKey("description")){
+ if (addressGroupObj.containsKey("description")) {
description = addressGroupObj.get("description").toString();
}
@@ -697,7 +705,7 @@ public class FirewallConfigPolicy extends Policy {
prefixIP = getName(prefixIP, membersObj, type);
}
- String prefixList = "'"+prefixIP+"'";
+ String prefixList = "'" + prefixIP + "'";
Boolean isAddressGroup = type.contains("REFERENCE");
@@ -709,8 +717,9 @@ public class FirewallConfigPolicy extends Policy {
}
}
removeDuplicateValuesFromLookup(dbConnection);
- }catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values");
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy",
+ "Exception getting Json values");
return false;
}
return true;
@@ -729,33 +738,34 @@ public class FirewallConfigPolicy extends Policy {
+ "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;";
dbConnection.updateQuery(protoDelete);
- //PortList Table
+ // PortList Table
String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 "
+ "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; ";
dbConnection.updateQuery(portListDelete);
- //PrefixList Table
+ // PrefixList Table
String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 "
+ "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND "
+ "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; ";
dbConnection.updateQuery(prefixListDelete);
- //GroupServiceList
+ // GroupServiceList
String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 "
+ "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND "
+ "groupservicelist.serviceList = g1.serviceList; ";
dbConnection.updateQuery(groupServiceDelete);
}
- private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName, JsonArray membersArray) {
+ private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName,
+ JsonArray membersArray) {
String name = null;
- for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) {
+ for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
JsonObject membersObj = membersArray.getJsonObject(membersIndex);
String type = membersObj.get("type").toString().replace("\"", "");
name = getName(name, membersObj, type);
}
- String nameInsert = "'"+name+"'";
+ String nameInsert = "'" + name + "'";
GroupServiceList groupServiceEntry = new GroupServiceList();
groupServiceEntry.setGroupName(serviceListName);
groupServiceEntry.setServiceList(nameInsert);
@@ -764,9 +774,9 @@ public class FirewallConfigPolicy extends Policy {
private String getName(String name, JsonObject membersObj, String type) {
String value;
- if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){
+ if (type.equals("REFERENCE") || type.equals("GROUP") || type.equals("SERVICE")) {
value = membersObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = membersObj.get("value").toString();
@@ -789,7 +799,6 @@ public class FirewallConfigPolicy extends Policy {
return name;
}
-
private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
JsonObject oldJson = null;
@@ -800,7 +809,7 @@ public class FirewallConfigPolicy extends Policy {
oldJson = stringToJson(prevJsonBody);
newJson = stringToJson(jsonBody);
- //if no changes to the json then return true
+ // if no changes to the json then return true
if (oldJson != null && oldJson.equals(newJson)) {
return true;
}
@@ -813,12 +822,12 @@ public class FirewallConfigPolicy extends Policy {
serviceGroup = newJson.getJsonArray("serviceGroups");
addressGroup = newJson.getJsonArray("addressGroups");
- //insert data into tables
+ // insert data into tables
try {
JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody);
- for (int i = 0; i<jsonDiff.size(); i++) {
- //String path = jsonDiff.get(i).asText();
+ for (int i = 0; i < jsonDiff.size(); i++) {
+ // String path = jsonDiff.get(i).asText();
String jsonpatch = jsonDiff.get(i).toString();
JsonObject patchObj = stringToJson(jsonpatch);
@@ -829,29 +838,29 @@ public class FirewallConfigPolicy extends Policy {
/*
* Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables
*/
- for(int ri = 0; ri < firewallRules.size(); ri++) {
+ for (int ri = 0; ri < firewallRules.size(); ri++) {
/*
* Populate ArrayLists with values from the JSON
*/
- //create the JSON object from the JSON Array for each iteration through the for loop
+ // create the JSON object from the JSON Array for each iteration through the for loop
JsonObject ruleListobj = firewallRules.getJsonObject(ri);
- //get values from JSON fields of firewallRulesList Array
+ // get values from JSON fields of firewallRulesList Array
String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\'');
String action = ruleListobj.get("action").toString().replace('"', '\'');
String description = ruleListobj.get("description").toString().replace('"', '\'');
List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName);
- if(result != null && !result.isEmpty()){
+ if (result != null && !result.isEmpty()) {
TermList termEntry = (TermList) result.get(0);
dbConnection.delete(termEntry);
}
- //getting fromZone Array field from the firewallRulesList
+ // getting fromZone Array field from the firewallRulesList
JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones");
String fromZoneString = null;
- for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) {
+ for (int fromZoneIndex = 0; fromZoneIndex < fromZoneArray.size(); fromZoneIndex++) {
String value = fromZoneArray.get(fromZoneIndex).toString();
value = value.replace("\"", "");
@@ -863,13 +872,12 @@ public class FirewallConfigPolicy extends Policy {
}
}
- String fromZoneInsert = "'"+fromZoneString+"'";
+ String fromZoneInsert = "'" + fromZoneString + "'";
- //getting toZone Array field from the firewallRulesList
+ // getting toZone Array field from the firewallRulesList
JsonArray toZoneArray = ruleListobj.getJsonArray("toZones");
String toZoneString = null;
-
for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) {
String value = toZoneArray.get(toZoneIndex).toString();
value = value.replace("\"", "");
@@ -882,18 +890,18 @@ public class FirewallConfigPolicy extends Policy {
}
}
- String toZoneInsert = "'"+toZoneString+"'";
- //getting sourceList Array fields from the firewallRulesList
+ String toZoneInsert = "'" + toZoneString + "'";
+ // getting sourceList Array fields from the firewallRulesList
JsonArray srcListArray = ruleListobj.getJsonArray("sourceList");
String srcListString = null;
- for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) {
+ for (int srcListIndex = 0; srcListIndex < srcListArray.size(); srcListIndex++) {
JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex);
String type = srcListObj.get("type").toString().replace("\"", "");
String value = null;
- if(type.equals("REFERENCE")||type.equals("GROUP")){
+ if (type.equals("REFERENCE") || type.equals("GROUP")) {
value = srcListObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = srcListObj.get("value").toString();
@@ -902,19 +910,19 @@ public class FirewallConfigPolicy extends Policy {
srcListString = getLeftOrRight(srcListString, value);
}
- String srcListInsert = "'"+srcListString+"'";
+ String srcListInsert = "'" + srcListString + "'";
- //getting destinationList Array fields from the firewallRulesList
+ // getting destinationList Array fields from the firewallRulesList
JsonArray destListArray = ruleListobj.getJsonArray("destinationList");
String destListString = null;
- for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) {
+ for (int destListIndex = 0; destListIndex < destListArray.size(); destListIndex++) {
JsonObject destListObj = destListArray.getJsonObject(destListIndex);
String type = destListObj.get("type").toString().replace("\"", "");
String value = null;
- if(type.equals("REFERENCE")||type.equals("GROUP")){
+ if (type.equals("REFERENCE") || type.equals("GROUP")) {
value = destListObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = destListObj.get("value").toString();
@@ -922,19 +930,20 @@ public class FirewallConfigPolicy extends Policy {
destListString = getLeftOrRight(destListString, value);
}
- String destListInsert = "'"+destListString+"'";
+ String destListInsert = "'" + destListString + "'";
- //getting destServices Array fields from the firewallRulesList
+ // getting destServices Array fields from the firewallRulesList
JsonArray destServicesArray = ruleListobj.getJsonArray("destServices");
String destPortListString = null;
- for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) {
+ for (int destPortListIndex = 0; destPortListIndex < destServicesArray
+ .size(); destPortListIndex++) {
JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex);
String type = destServicesObj.get("type").toString().replace("\"", "");
String value = null;
- if(type.equals("REFERENCE")||type.equals("GROUP")){
+ if (type.equals("REFERENCE") || type.equals("GROUP")) {
value = destServicesObj.get("name").toString();
- } else if (type.equalsIgnoreCase("ANY")){
+ } else if (type.equalsIgnoreCase("ANY")) {
value = null;
} else {
value = destServicesObj.get("value").toString();
@@ -942,7 +951,7 @@ public class FirewallConfigPolicy extends Policy {
destPortListString = getLeftOrRight(destPortListString, value);
}
- String destPortListInsert = "'"+destPortListString+"'";
+ String destPortListInsert = "'" + destPortListString + "'";
/*
* Create Queries to INSERT data into database tables and execute
@@ -966,8 +975,9 @@ public class FirewallConfigPolicy extends Policy {
termEntry.setUserCreatedBy(userInfo);
dbConnection.save(termEntry);
- List<Object> actionResult = dbConnection.getDataById(ActionList.class, "actionName", action);
- if(actionResult == null || actionResult.isEmpty()){
+ List<Object> actionResult =
+ dbConnection.getDataById(ActionList.class, "actionName", action);
+ if (actionResult == null || actionResult.isEmpty()) {
saveActionListToDb(dbConnection, action);
}
}
@@ -975,61 +985,66 @@ public class FirewallConfigPolicy extends Policy {
if (path.contains("serviceGroups")) {
/*
- * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables
+ * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList
+ * tables
*/
- for(int si = 0; si < serviceGroup.size(); si++) {
+ for (int si = 0; si < serviceGroup.size(); si++) {
/*
* Populate ArrayLists with values from the JSON
*/
- //create the JSON object from the JSON Array for each iteration through the for loop
+ // create the JSON object from the JSON Array for each iteration through the for loop
JsonObject svcGroupListobj = serviceGroup.getJsonObject(si);
String groupName = svcGroupListobj.get("name").toString().replace('"', '\'');
String description = null;
- if (svcGroupListobj.containsKey("description")){
+ if (svcGroupListobj.containsKey("description")) {
description = svcGroupListobj.get("description").toString().replace('"', '\'');
}
JsonArray membersArray = svcGroupListobj.getJsonArray("members");
Boolean isServiceGroup = false;
- if (membersArray!=null){
+ if (membersArray != null) {
String membersType = membersArray.getJsonObject(0).get("type").toString();
if (membersType.contains("REFERENCE")) {
isServiceGroup = true;
}
}
- //Insert values into GROUPSERVICELIST table if name begins with Group
+ // Insert values into GROUPSERVICELIST table if name begins with Group
if (isServiceGroup) {
- List<Object> result = dbConnection.getDataById(GroupServiceList.class, "name", groupName);
- if(result != null && !result.isEmpty()){
+ List<Object> result =
+ dbConnection.getDataById(GroupServiceList.class, "name", groupName);
+ if (result != null && !result.isEmpty()) {
GroupServiceList groupEntry = (GroupServiceList) result.get(0);
dbConnection.delete(groupEntry);
}
saveGroupServiceListTableToDb(dbConnection, groupName, membersArray);
- } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table
+ } else { // Insert JSON data serviceGroup table, protocollist table, and portlist table
String type = svcGroupListobj.get("type").toString().replace('"', '\'');
- String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
+ String transportProtocol =
+ svcGroupListobj.get("transportProtocol").toString().replace('"', '\'');
String ports = svcGroupListobj.get("ports").toString().replace('"', '\'');
List<Object> result = dbConnection.getDataById(ServiceList.class, "name", groupName);
- if(result != null && !result.isEmpty()){
+ if (result != null && !result.isEmpty()) {
ServiceList serviceEntry = (ServiceList) result.get(0);
dbConnection.delete(serviceEntry);
}
- saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol, ports);
+ saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol,
+ ports);
- List<Object> protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol);
- if(protocolResult == null || protocolResult.isEmpty()){
+ List<Object> protocolResult =
+ dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol);
+ if (protocolResult == null || protocolResult.isEmpty()) {
saveProtocolListToDb(dbConnection, transportProtocol);
}
List<Object> portResult = dbConnection.getDataById(PortList.class, "portName", ports);
- if(portResult == null || portResult.isEmpty()){
+ if (portResult == null || portResult.isEmpty()) {
savePortListToDb(dbConnection, ports);
}
}
@@ -1040,45 +1055,47 @@ public class FirewallConfigPolicy extends Policy {
/*
* Inserting addressGroup data into the ADDRESSGROUP table
*/
- for(int ai=0; ai < addressGroup.size() ; ai++) {
+ for (int ai = 0; ai < addressGroup.size(); ai++) {
/*
* Populate ArrayLists with values from the JSON
*/
- //create the JSON object from the JSON Array for each iteration through the for loop
+ // create the JSON object from the JSON Array for each iteration through the for loop
JsonObject addressGroupObj = addressGroup.getJsonObject(ai);
- //create JSON array for members
+ // create JSON array for members
JsonArray membersArray = addressGroupObj.getJsonArray("members");
String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\'');
String description = null;
- if (addressGroupObj.containsKey("description")){
+ if (addressGroupObj.containsKey("description")) {
description = addressGroupObj.get("description").toString().replace('"', '\'');
}
String prefixIP = null;
String type = null;
- for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) {
+ for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) {
JsonObject membersObj = membersArray.getJsonObject(membersIndex);
type = membersObj.get("type").toString().replace("\"", "");
prefixIP = getName(prefixIP, membersObj, type);
}
- String prefixList = "'"+prefixIP+"'";
+ String prefixList = "'" + prefixIP + "'";
Boolean isAddressGroup = type.contains("REFERENCE");
if (isAddressGroup) {
- List<Object> result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName);
- if(result != null && !result.isEmpty()){
+ List<Object> result =
+ dbConnection.getDataById(AddressGroup.class, "name", addressGroupName);
+ if (result != null && !result.isEmpty()) {
AddressGroup addressGroupEntry = (AddressGroup) result.get(0);
dbConnection.delete(addressGroupEntry);
}
saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList);
} else {
- List<Object> result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName);
- if(result != null && !result.isEmpty()){
+ List<Object> result =
+ dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName);
+ if (result != null && !result.isEmpty()) {
PrefixList prefixListEntry = (PrefixList) result.get(0);
dbConnection.delete(prefixListEntry);
}
@@ -1088,8 +1105,9 @@ public class FirewallConfigPolicy extends Policy {
}
}
removeDuplicateValuesFromLookup(dbConnection);
- }catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries");
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy",
+ "Exception executing Firewall queries");
return false;
}
return true;
@@ -1120,7 +1138,8 @@ public class FirewallConfigPolicy extends Policy {
dbConnection.save(protocolEntry);
}
- private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type, String transportProtocol, String ports) {
+ private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type,
+ String transportProtocol, String ports) {
ServiceList serviceListEntry = new ServiceList();
serviceListEntry.setServiceName(groupName);
serviceListEntry.setServiceDescription(description);
@@ -1131,7 +1150,8 @@ public class FirewallConfigPolicy extends Policy {
dbConnection.save(serviceListEntry);
}
- private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) {
+ private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description,
+ String prefixList) {
PrefixList newPrefixList = new PrefixList();
newPrefixList.setPrefixListName(addressGroupName);
newPrefixList.setDescription(description);
@@ -1139,7 +1159,8 @@ public class FirewallConfigPolicy extends Policy {
dbConnection.save(newPrefixList);
}
- private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) {
+ private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description,
+ String prefixList) {
AddressGroup newAddressGroup = new AddressGroup();
newAddressGroup.setGroupName(addressGroupName);
newAddressGroup.setDescription(description);
@@ -1148,7 +1169,7 @@ public class FirewallConfigPolicy extends Policy {
}
private JsonObject stringToJson(String jsonString) {
- //Read jsonBody to JsonObject
+ // Read jsonBody to JsonObject
StringReader in = new StringReader(jsonString);
JsonReader jsonReader = Json.createReader(in);
JsonObject json = jsonReader.readObject();
@@ -1164,7 +1185,7 @@ public class FirewallConfigPolicy extends Policy {
oldJason = JsonLoader.fromString(oldJson);
updatedJason = JsonLoader.fromString(json);
} catch (IOException e) {
- LOGGER.error("Exception Occured"+e);
+ LOGGER.error("Exception Occured" + e);
}
return JsonDiff.asJson(oldJason, updatedJason);
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java
index fc08b643e..f565254f1 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java
@@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.api.pap.PDPPolicy;
import com.att.research.xacml.util.XACMLProperties;
+
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
@@ -34,7 +35,9 @@ import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+
import javax.persistence.PersistenceException;
+
import org.apache.commons.io.FilenameUtils;
import org.hibernate.Query;
import org.hibernate.Session;
@@ -70,7 +73,6 @@ public class HandleIncomingNotifications {
public static final String OTHER_CONFIG = "OTHER";
public static final String AUDIT_USER = "audit";
-
private static SessionFactory sessionfactory;
@Autowired
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java
index 26c7ed834..5120d25fa 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java
@@ -2,7 +2,7 @@
* ============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.
@@ -20,6 +20,12 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.std.IdentifierImpl;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Splitter;
+
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
@@ -33,22 +39,6 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.lang.StringUtils;
-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.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
-import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.onap.policy.rest.jpa.MicroServiceModels;
-
-import com.att.research.xacml.api.pap.PAPException;
-import com.att.research.xacml.std.IdentifierImpl;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.common.base.Splitter;
-
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;
@@ -61,7 +51,17 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
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 oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.lang.StringUtils;
+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.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.jpa.MicroServiceModels;
public class MicroServiceConfigPolicy extends Policy {
@@ -70,7 +70,7 @@ public class MicroServiceConfigPolicy extends Policy {
private static Map<String, String> mapAttribute = new HashMap<>();
private static Map<String, String> mapMatch = new HashMap<>();
- private static synchronized Map<String, String> getMatchMap () {
+ private static synchronized Map<String, String> getMatchMap() {
return mapMatch;
}
@@ -82,34 +82,33 @@ public class MicroServiceConfigPolicy extends Policy {
super();
}
- public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter){
+ public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter) {
this.policyAdapter = policyAdapter;
}
- //save configuration of the policy based on the policyname
+ // save configuration of the policy based on the policyname
private void saveConfigurations(String policyName, String jsonBody) {
- if(policyName.endsWith(".xml")){
- policyName = policyName.replace(".xml", "");
- }
- try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json")){
+ if (policyName.endsWith(".xml")) {
+ policyName = policyName.replace(".xml", "");
+ }
+ try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json")) {
out.println(jsonBody);
} catch (Exception e) {
- LOGGER.error("Exception Occured While writing Configuration data"+e);
+ LOGGER.error("Exception Occured While writing Configuration data" + e);
}
}
-
@Override
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();
}
@@ -117,18 +116,18 @@ public class MicroServiceConfigPolicy extends Policy {
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()){
- //we have already done this
+ if (isPreparedToSave()) {
+ // we have already done this
return true;
}
@@ -156,7 +155,6 @@ public class MicroServiceConfigPolicy extends Policy {
policyName = policyName + ".xml";
}
-
PolicyType configPolicy = (PolicyType) policyAdapter.getData();
configPolicy.setDescription(policyAdapter.getPolicyDescription());
@@ -170,32 +168,33 @@ public class MicroServiceConfigPolicy extends Policy {
name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
}
- //setup values for pulling out matching attributes
+ // setup values for pulling out matching attributes
ObjectMapper mapper = new ObjectMapper();
String matching = null;
Map<String, String> matchMap = null;
try {
JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody());
- if (policyAdapter.getTtlDate()==null){
+ if (policyAdapter.getTtlDate() == null) {
policyAdapter.setTtlDate("NA");
}
- if (policyAdapter.getServiceType().contains("-v")){
+ if (policyAdapter.getServiceType().contains("-v")) {
matching = getValueFromDictionary(policyAdapter.getServiceType());
} else {
- String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""});
+ String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(),
+ new String[] {"\""}, new String[] {""});
matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion);
}
- if (matching != null && !matching.isEmpty()){
+ if (matching != null && !matching.isEmpty()) {
matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching);
- setMatchMap(matchMap);
- if(policyAdapter.getJsonBody() != null){
- pullMatchValue(rootNode);
+ setMatchMap(matchMap);
+ if (policyAdapter.getJsonBody() != null) {
+ pullMatchValue(rootNode);
}
}
} catch (IOException e1) {
throw new PAPException(e1);
}
-
+
// Match for policyName
allOfOne.getMatch().add(createMatch("PolicyName", name));
@@ -203,7 +202,7 @@ public class MicroServiceConfigPolicy extends Policy {
// Adding the matches to AllOfType element Match for Onap
allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
- if (matchMap==null || matchMap.isEmpty()){
+ if (matchMap == null || matchMap.isEmpty()) {
// Match for ConfigName
allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
// Match for Service
@@ -212,29 +211,25 @@ public class MicroServiceConfigPolicy extends Policy {
allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid()));
// Match for location
allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation()));
- }else {
- for (Entry<String, String> matchValue : matchMap.entrySet()){
+ } else {
+ for (Entry<String, String> matchValue : matchMap.entrySet()) {
String value = matchValue.getValue();
String key = matchValue.getKey().trim();
- if (value.contains("matching-true")){
- if (mapAttribute.containsKey(key)){
+ if (value.contains("matching-true")) {
+ if (mapAttribute.containsKey(key)) {
allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
}
}
}
}
// Match for riskType
- allOf.getMatch().add(
- createDynamicMatch("RiskType", policyAdapter.getRiskType()));
+ allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
// Match for riskLevel
- allOf.getMatch().add(
- createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
+ allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
// Match for riskguard
- allOf.getMatch().add(
- createDynamicMatch("guard", policyAdapter.getGuard()));
+ allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
// Match for ttlDate
- allOf.getMatch().add(
- createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
+ allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
AnyOfType anyOf = new AnyOfType();
anyOf.getAllOf().add(allOfOne);
@@ -265,7 +260,8 @@ public class MicroServiceConfigPolicy extends Policy {
try {
accessURI = new URI(ACTION_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating ACCESS URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy",
+ "Exception creating ACCESS URI");
}
accessAttributeDesignator.setCategory(CATEGORY_ACTION);
accessAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -284,7 +280,8 @@ public class MicroServiceConfigPolicy extends Policy {
try {
configURI = new URI(RESOURCE_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating Config URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy",
+ "Exception creating Config URI");
}
configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
configAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -317,34 +314,36 @@ public class MicroServiceConfigPolicy extends Policy {
private void pullMatchValue(JsonNode rootNode) {
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
String newValue = null;
- while (fieldsIterator.hasNext()) {
- Map.Entry<String, JsonNode> field = fieldsIterator.next();
- final String key = field.getKey();
- final JsonNode value = field.getValue();
- if (value.isContainerNode() && !value.isArray()) {
- pullMatchValue(value); // RECURSIVE CALL
- } else {
- newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
- mapAttribute.put(key, newValue);
- }
- }
-
- }
-
- private String getValueFromDictionary(String service){
- String ruleTemplate=null;
- String modelName = service.split("-v")[0];
- String modelVersion = service.split("-v")[1];
-
- CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
- List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+modelVersion);
- if(result != null && !result.isEmpty()){
- MicroServiceModels model = (MicroServiceModels) result.get(0);
- ruleTemplate = model.getAnnotation();
- }
- return ruleTemplate;
- }
-
+ while (fieldsIterator.hasNext()) {
+ Map.Entry<String, JsonNode> field = fieldsIterator.next();
+ final String key = field.getKey();
+ final JsonNode value = field.getValue();
+ if (value.isContainerNode() && !value.isArray()) {
+ pullMatchValue(value); // RECURSIVE CALL
+ } else {
+ newValue = StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""},
+ new String[] {"", "", ""});
+ mapAttribute.put(key, newValue);
+ }
+ }
+
+ }
+
+ private String getValueFromDictionary(String service) {
+ String ruleTemplate = null;
+ String modelName = service.split("-v")[0];
+ String modelVersion = service.split("-v")[1];
+
+ CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
+ List<Object> result =
+ dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName + ":" + modelVersion);
+ if (result != null && !result.isEmpty()) {
+ MicroServiceModels model = (MicroServiceModels) result.get(0);
+ ruleTemplate = model.getAnnotation();
+ }
+ return ruleTemplate;
+ }
+
// Data required for Advice part is setting here.
private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
AdviceExpressionsType advices = new AdviceExpressionsType();
@@ -372,12 +371,12 @@ public class MicroServiceConfigPolicy extends Policy {
AttributeValueType AttributeValue = new AttributeValueType();
AttributeValue.setDataType(URI_DATATYPE);
String configName;
- if(policyName.endsWith(".xml")){
+ if (policyName.endsWith(".xml")) {
configName = policyName.replace(".xml", "");
- }else{
+ } else {
configName = policyName;
}
- String content = CONFIG_URL +"/Config/" + configName + ".json";
+ String content = CONFIG_URL + "/Config/" + configName + ".json";
AttributeValue.getContent().add(content);
assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
@@ -427,16 +426,16 @@ public class MicroServiceConfigPolicy extends Policy {
assignment7.setAttributeId("matching:service");
assignment7.setCategory(CATEGORY_RESOURCE);
assignment7.setIssuer("");
-
+
AttributeValueType configNameAttributeValue7 = new AttributeValueType();
configNameAttributeValue7.setDataType(STRING_DATATYPE);
configNameAttributeValue7.getContent().add(policyAdapter.getServiceType());
assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
-
+
advice.getAttributeAssignmentExpression().add(assignment7);
Map<String, String> matchMap = getMatchMap();
- if (matchMap==null || matchMap.isEmpty()){
+ if (matchMap == null || matchMap.isEmpty()) {
AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
assignment6.setAttributeId("matching:" + CONFIGID);
assignment6.setCategory(CATEGORY_RESOURCE);
@@ -449,7 +448,6 @@ public class MicroServiceConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment6);
-
AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
assignment8.setAttributeId("matching:uuid");
assignment8.setCategory(CATEGORY_RESOURCE);
@@ -474,28 +472,28 @@ public class MicroServiceConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment9);
} else {
- for (Entry<String, String> matchValue : matchMap.entrySet()){
+ for (Entry<String, String> matchValue : matchMap.entrySet()) {
String value = matchValue.getValue();
String key = matchValue.getKey().trim();
- if (value.contains("matching-true")){
- if (mapAttribute.containsKey(key)){
+ if (value.contains("matching-true")) {
+ if (mapAttribute.containsKey(key)) {
AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
assignment9.setAttributeId("matching:" + key);
assignment9.setCategory(CATEGORY_RESOURCE);
assignment9.setIssuer("");
-
+
AttributeValueType configNameAttributeValue9 = new AttributeValueType();
configNameAttributeValue9.setDataType(STRING_DATATYPE);
configNameAttributeValue9.getContent().add(mapAttribute.get(key));
assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
-
+
advice.getAttributeAssignmentExpression().add(assignment9);
-
+
}
}
}
}
-
+
AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
assignment10.setAttributeId("Priority");
assignment10.setCategory(CATEGORY_RESOURCE);
@@ -508,7 +506,7 @@ public class MicroServiceConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment10);
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
assignment11.setAttributeId("RiskType");
assignment11.setCategory(CATEGORY_RESOURCE);
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java
index 2e2a74015..34dd73c57 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java
@@ -21,6 +21,7 @@
package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.util.XACMLProperties;
+
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
@@ -31,6 +32,7 @@ import java.util.Base64;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
+
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.XACMLRestProperties;
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java
index 2719a155b..82a6c4b83 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-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.
@@ -20,6 +20,12 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.std.IdentifierImpl;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Splitter;
+
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
@@ -33,22 +39,6 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.lang.StringUtils;
-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.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
-import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.onap.policy.rest.jpa.OptimizationModels;
-
-import com.att.research.xacml.api.pap.PAPException;
-import com.att.research.xacml.std.IdentifierImpl;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.common.base.Splitter;
-
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;
@@ -61,7 +51,17 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
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 oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.lang.StringUtils;
+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.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.jpa.OptimizationModels;
public class OptimizationConfigPolicy extends Policy {
@@ -70,7 +70,7 @@ public class OptimizationConfigPolicy extends Policy {
private static Map<String, String> mapAttribute = new HashMap<>();
private static Map<String, String> mapMatch = new HashMap<>();
- private static synchronized Map<String, String> getMatchMap () {
+ private static synchronized Map<String, String> getMatchMap() {
return mapMatch;
}
@@ -82,36 +82,35 @@ public class OptimizationConfigPolicy extends Policy {
super();
}
- public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter){
+ public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter) {
this.policyAdapter = policyAdapter;
}
- //save configuration of the policy based on the policyname
+ // save configuration of the policy based on the policyname
private void saveConfigurations(String policyName, String jsonBody) {
- if(policyName.endsWith(".xml")){
+ if (policyName.endsWith(".xml")) {
policyName = policyName.replace(".xml", "");
}
- try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json");){
+ try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json");) {
out.println(jsonBody);
} catch (Exception e) {
- LOGGER.error("Exception Occured While writing Configuration data"+e);
+ LOGGER.error("Exception Occured While writing Configuration data" + e);
}
}
-
@Override
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();
}
@@ -119,18 +118,18 @@ public class OptimizationConfigPolicy extends Policy {
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()){
- //we have already done this
+ if (isPreparedToSave()) {
+ // we have already done this
return true;
}
@@ -158,7 +157,6 @@ public class OptimizationConfigPolicy extends Policy {
policyName = policyName + ".xml";
}
-
PolicyType configPolicy = (PolicyType) policyAdapter.getData();
configPolicy.setDescription(policyAdapter.getPolicyDescription());
@@ -172,32 +170,33 @@ public class OptimizationConfigPolicy extends Policy {
name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
}
- //setup values for pulling out matching attributes
+ // setup values for pulling out matching attributes
ObjectMapper mapper = new ObjectMapper();
String matching = null;
Map<String, String> matchMap = null;
try {
JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody());
- if (policyAdapter.getTtlDate()==null){
+ if (policyAdapter.getTtlDate() == null) {
policyAdapter.setTtlDate("NA");
}
- if (policyAdapter.getServiceType().contains("-v")){
+ if (policyAdapter.getServiceType().contains("-v")) {
matching = getValueFromDictionary(policyAdapter.getServiceType());
} else {
- String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""});
+ String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(),
+ new String[] {"\""}, new String[] {""});
matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion);
}
- if (matching != null && !matching.isEmpty()){
+ if (matching != null && !matching.isEmpty()) {
matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching);
setMatchMap(matchMap);
- if(policyAdapter.getJsonBody() != null){
- pullMatchValue(rootNode);
+ if (policyAdapter.getJsonBody() != null) {
+ pullMatchValue(rootNode);
}
}
} catch (IOException e1) {
throw new PAPException(e1);
}
-
+
// Match for policyName
allOfOne.getMatch().add(createMatch("PolicyName", name));
@@ -205,28 +204,24 @@ public class OptimizationConfigPolicy extends Policy {
// Adding the matches to AllOfType element Match for Onap
allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
- if (matchMap!=null && !matchMap.isEmpty()) {
- for (Entry<String, String> matchValue : matchMap.entrySet()){
+ if (matchMap != null && !matchMap.isEmpty()) {
+ for (Entry<String, String> matchValue : matchMap.entrySet()) {
String value = matchValue.getValue();
String key = matchValue.getKey().trim();
- if (value.contains("matching-true") && mapAttribute.containsKey(key)){
+ if (value.contains("matching-true") && mapAttribute.containsKey(key)) {
allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key)));
}
}
}
// Match for riskType
- allOf.getMatch().add(
- createDynamicMatch("RiskType", policyAdapter.getRiskType()));
+ allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
// Match for riskLevel
- allOf.getMatch().add(
- createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
+ allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
// Match for riskguard
- allOf.getMatch().add(
- createDynamicMatch("guard", policyAdapter.getGuard()));
+ allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
// Match for ttlDate
- allOf.getMatch().add(
- createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
+ allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
AnyOfType anyOf = new AnyOfType();
anyOf.getAllOf().add(allOfOne);
@@ -257,7 +252,8 @@ public class OptimizationConfigPolicy extends Policy {
try {
accessURI = new URI(ACTION_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating ACCESS URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy",
+ "Exception creating ACCESS URI");
}
accessAttributeDesignator.setCategory(CATEGORY_ACTION);
accessAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -276,7 +272,8 @@ public class OptimizationConfigPolicy extends Policy {
try {
configURI = new URI(RESOURCE_ID);
} catch (URISyntaxException e) {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating Config URI");
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy",
+ "Exception creating Config URI");
}
configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
configAttributeDesignator.setDataType(STRING_DATATYPE);
@@ -309,34 +306,36 @@ public class OptimizationConfigPolicy extends Policy {
private void pullMatchValue(JsonNode rootNode) {
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
String newValue = null;
- while (fieldsIterator.hasNext()) {
- Map.Entry<String, JsonNode> field = fieldsIterator.next();
- final String key = field.getKey();
- final JsonNode value = field.getValue();
- if (value.isContainerNode() && !value.isArray()) {
- pullMatchValue(value); // RECURSIVE CALL
- } else {
- newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
- mapAttribute.put(key, newValue);
- }
- }
-
- }
-
- private String getValueFromDictionary(String service){
- String ruleTemplate=null;
- String modelName = service.split("-v")[0];
- String modelVersion = service.split("-v")[1];
-
- CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
- List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+modelVersion);
- if(result != null && !result.isEmpty()){
- OptimizationModels model = (OptimizationModels) result.get(0);
- ruleTemplate = model.getAnnotation();
- }
- return ruleTemplate;
- }
-
+ while (fieldsIterator.hasNext()) {
+ Map.Entry<String, JsonNode> field = fieldsIterator.next();
+ final String key = field.getKey();
+ final JsonNode value = field.getValue();
+ if (value.isContainerNode() && !value.isArray()) {
+ pullMatchValue(value); // RECURSIVE CALL
+ } else {
+ newValue = StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""},
+ new String[] {"", "", ""});
+ mapAttribute.put(key, newValue);
+ }
+ }
+
+ }
+
+ private String getValueFromDictionary(String service) {
+ String ruleTemplate = null;
+ String modelName = service.split("-v")[0];
+ String modelVersion = service.split("-v")[1];
+
+ CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
+ List<Object> result =
+ dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + modelVersion);
+ if (result != null && !result.isEmpty()) {
+ OptimizationModels model = (OptimizationModels) result.get(0);
+ ruleTemplate = model.getAnnotation();
+ }
+ return ruleTemplate;
+ }
+
// Data required for Advice part is setting here.
private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
AdviceExpressionsType advices = new AdviceExpressionsType();
@@ -366,18 +365,18 @@ public class OptimizationConfigPolicy extends Policy {
AttributeValueType attributeValue = new AttributeValueType();
attributeValue.setDataType(URI_DATATYPE);
String configName;
- if(policyName.endsWith(".xml")){
+ if (policyName.endsWith(".xml")) {
configName = policyName.replace(".xml", "");
- }else{
+ } else {
configName = policyName;
}
- String content = CONFIG_URL +"/Config/" + configName + ".json";
+ String content = CONFIG_URL + "/Config/" + configName + ".json";
attributeValue.getContent().add(content);
assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue));
advice.getAttributeAssignmentExpression().add(assignment2);
- //PolicyName Attribute Assignment
+ // PolicyName Attribute Assignment
AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
assignment3.setAttributeId("PolicyName");
assignment3.setCategory(CATEGORY_RESOURCE);
@@ -395,7 +394,7 @@ public class OptimizationConfigPolicy extends Policy {
assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
advice.getAttributeAssignmentExpression().add(assignment3);
- //VersionNumber Attribute Assignment
+ // VersionNumber Attribute Assignment
AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
assignment4.setAttributeId("VersionNumber");
assignment4.setCategory(CATEGORY_RESOURCE);
@@ -408,7 +407,7 @@ public class OptimizationConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment4);
- //OnapName Attribute Assignment
+ // OnapName Attribute Assignment
AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
assignment5.setAttributeId("matching:" + ONAPID);
assignment5.setCategory(CATEGORY_RESOURCE);
@@ -421,41 +420,41 @@ public class OptimizationConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment5);
- //ServiceType Attribute Assignment
+ // ServiceType Attribute Assignment
AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
assignment7.setAttributeId("matching:service");
assignment7.setCategory(CATEGORY_RESOURCE);
assignment7.setIssuer("");
-
+
AttributeValueType configNameAttributeValue7 = new AttributeValueType();
configNameAttributeValue7.setDataType(STRING_DATATYPE);
configNameAttributeValue7.getContent().add(policyAdapter.getServiceType());
assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
-
+
advice.getAttributeAssignmentExpression().add(assignment7);
// Add matching attribute assignments if exist
Map<String, String> matchMap = getMatchMap();
- if (matchMap!=null && !matchMap.isEmpty()) {
- for (Entry<String, String> matchValue : matchMap.entrySet()){
+ if (matchMap != null && !matchMap.isEmpty()) {
+ for (Entry<String, String> matchValue : matchMap.entrySet()) {
String value = matchValue.getValue();
String key = matchValue.getKey().trim();
- if (value.contains("matching-true") && mapAttribute.containsKey(key)){
+ if (value.contains("matching-true") && mapAttribute.containsKey(key)) {
AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
assignment9.setAttributeId("matching:" + key);
assignment9.setCategory(CATEGORY_RESOURCE);
assignment9.setIssuer("");
-
+
AttributeValueType configNameAttributeValue9 = new AttributeValueType();
configNameAttributeValue9.setDataType(STRING_DATATYPE);
configNameAttributeValue9.getContent().add(mapAttribute.get(key));
assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
-
+
advice.getAttributeAssignmentExpression().add(assignment9);
}
}
}
-
+
// Priority Attribute Assignment
AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
assignment10.setAttributeId("Priority");
@@ -469,7 +468,7 @@ public class OptimizationConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment10);
- //RiskType Attribute Assignment
+ // RiskType Attribute Assignment
AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
assignment11.setAttributeId("RiskType");
assignment11.setCategory(CATEGORY_RESOURCE);
@@ -482,7 +481,7 @@ public class OptimizationConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment11);
- //RiskLevel Attribute Assignment
+ // RiskLevel Attribute Assignment
AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
assignment12.setAttributeId("RiskLevel");
assignment12.setCategory(CATEGORY_RESOURCE);
@@ -495,7 +494,7 @@ public class OptimizationConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment12);
- //Guard Attribute Assignment
+ // Guard Attribute Assignment
AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
assignment13.setAttributeId("guard");
assignment13.setCategory(CATEGORY_RESOURCE);
@@ -508,7 +507,7 @@ public class OptimizationConfigPolicy extends Policy {
advice.getAttributeAssignmentExpression().add(assignment13);
- //TTLDate Attribute Assignment
+ // TTLDate Attribute Assignment
AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
assignment14.setAttributeId("TTLDate");
assignment14.setCategory(CATEGORY_RESOURCE);
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java
index 549d26b28..278e1e866 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 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.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,6 +21,12 @@
package org.onap.policy.pap.xacml.rest.components;
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.std.IdentifierImpl;
+import com.att.research.xacml.util.XACMLProperties;
+import com.att.research.xacmlatt.pdp.policy.PolicyDef;
+import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef;
+
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
@@ -30,6 +36,13 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
+
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+
import org.apache.commons.io.FilenameUtils;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
@@ -38,16 +51,6 @@ import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.XACMLRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.xacml.util.XACMLPolicyWriter;
-import com.att.research.xacml.api.pap.PAPException;
-import com.att.research.xacml.std.IdentifierImpl;
-import com.att.research.xacml.util.XACMLProperties;
-import com.att.research.xacmlatt.pdp.policy.PolicyDef;
-import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
public abstract class Policy {
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java
index 9a39b6ed1..25c900393 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java
@@ -24,6 +24,7 @@ package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.api.pap.PDPPolicy;
import com.att.research.xacml.util.XACMLProperties;
+
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
@@ -36,7 +37,9 @@ import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
+
import javax.persistence.PersistenceException;
+
import org.apache.commons.io.FilenameUtils;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
@@ -86,15 +89,12 @@ public class PolicyDBDao {
public static final String PDPENTITY_SELECT =
"SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted";
public static final String GROUP_NOT_FOUND = "The group could not be found with id ";
- public static final String FOUND_IN_DB_NOT_DEL =
- " were found in the database that are not deleted";
+ public static final String FOUND_IN_DB_NOT_DEL = " were found in the database that are not deleted";
public static final String MORE_THAN_ONE_PDP = "Somehow, more than one pdp with the same id ";
- public static final String DELETED_STATUS_FOUND =
- " and deleted status were found in the database";
+ public static final String DELETED_STATUS_FOUND = " and deleted status were found in the database";
public static final String DUPLICATE_GROUPID = "Somehow, more than one group with the same id ";
public static final String PDP_ID = "pdpId";
- public static final String QUERY_FAILED_FOR_GROUP =
- "Query failed trying to check for existing group";
+ public static final String QUERY_FAILED_FOR_GROUP = "Query failed trying to check for existing group";
public static final String QUERY_FAILED_GET_GROUP = "Query failed trying to get group ";
public static final String SCOPE = "scope";
public static final String POLICYDBDAO_VAR = "PolicyDBDao";
@@ -106,7 +106,6 @@ public class PolicyDBDao {
private List<?> otherServers;
private PAPPolicyEngine papEngine;
-
/**
* Gets the current instance of PolicyDBDao.
*
@@ -140,8 +139,8 @@ public class PolicyDBDao {
public PolicyDBDao(String init) {
// not needed in this release
if (!register()) {
- PolicyLogger.error(
- "This server's PolicyDBDao instance could not be registered and may not reveive updates");
+ PolicyLogger
+ .error("This server's PolicyDBDao instance could not be registered and may not reveive updates");
}
otherServers = getRemotePolicyDBDaoList();
@@ -157,17 +156,15 @@ public class PolicyDBDao {
// waitTime in ms to wait for lock, or -1 to wait forever (no)
@SuppressWarnings("deprecation")
public void startTransactionSynced(Session session, int waitTime) {
- logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as "
- + "\n startTransactionSynced(" + session + "," + waitTime + ") called\n\n");
+ logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " + "\n startTransactionSynced("
+ + session + "," + waitTime + ") called\n\n");
DatabaseLockEntity lock = null;
session.beginTransaction();
try {
if (logger.isDebugEnabled()) {
- logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock"
- + "\n\n");
+ logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" + "\n\n");
}
- lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1,
- LockMode.PESSIMISTIC_WRITE);
+ lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, LockMode.PESSIMISTIC_WRITE);
if (logger.isDebugEnabled()) {
logger.debug("\n\nstartTransactionSynced():" + "\n GOT the DB lock" + "\n\n");
}
@@ -201,8 +198,7 @@ public class PolicyDBDao {
try {
session.close();
} catch (Exception e) {
- logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
- + "Error While Closing Connection/Statement" + e);
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e);
}
}
return policyDBDaoEntityList;
@@ -222,11 +218,9 @@ public class PolicyDBDao {
public PolicyDBDaoTransaction getNewAuditTransaction() {
logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called");
// Use the standard transaction wait time in ms
- int auditWaitMs = Integer
- .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
+ int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT));
// Use the (extended) audit timeout time in ms
- int auditTimeoutMs = Integer
- .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
+ int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT));
return new PolicyDbDaoTransactionInstance(auditTimeoutMs, auditWaitMs);
}
@@ -237,8 +231,7 @@ public class PolicyDBDao {
* @param two A String or null to compare
*/
public static boolean stringEquals(String one, String two) {
- logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two
- + ") called");
+ logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two + ") called");
if (one == null && two == null) {
return true;
}
@@ -272,8 +265,7 @@ public class PolicyDBDao {
urlUserPass[2] = commaSplit[2];
}
if (urlUserPass[1] == null || "".equals(urlUserPass[1])) {
- String usernamePropertyValue =
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
+ String usernamePropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
if (usernamePropertyValue != null) {
urlUserPass[1] = usernamePropertyValue;
}
@@ -332,8 +324,7 @@ public class PolicyDBDao {
}
}
}
- logger.debug(
- "\nPolicyDBDao.register. Database locking and concurrency control is initialized\n");
+ logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n");
PolicyDBDaoEntity foundPolicyDBDaoEntity = null;
Criteria cr = session.createCriteria(PolicyDBDaoEntity.class);
cr.add(Restrictions.eq("policyDBDaoUrl", url[0]));
@@ -394,8 +385,8 @@ public class PolicyDBDao {
* This method is called during all pushPolicy transactions and makes sure the file system group
* is in sync with the database groupentity
*/
- public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup,
- GroupEntity groupentity) throws PAPException, PolicyDBException {
+ public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, GroupEntity groupentity)
+ throws PAPException, PolicyDBException {
HashMap<String, PDPPolicy> currentPolicyMap = new HashMap<>();
HashSet<String> newPolicyIdSet = new HashSet<>();
@@ -415,23 +406,19 @@ public class PolicyDBDao {
// convert PolicyEntity object to PDPPolicy
String name = pdpPolicyId.replace(".xml", "");
name = name.substring(0, name.lastIndexOf('.'));
- InputStream policyStream =
- new ByteArrayInputStream(policy.getPolicyData().getBytes());
+ InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes());
pdpGroup.copyPolicyToFile(pdpPolicyId, name, policyStream);
- URI location =
- Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId)
- .toUri();
+ URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri();
StdPDPPolicy newPolicy = null;
try {
newPolicy = new StdPDPPolicy(pdpPolicyId, true,
removeExtensionAndVersionFromPolicyName(pdpPolicyId), location);
newPolicySet.add(newPolicy);
- logger.info("Adding new policy to PDPGroup - " + newPolicy.getId()
- + ", Location - " + location);
+ logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() + ", Location - " + location);
} catch (Exception e) {
logger.debug(e);
- PolicyLogger.error(
- "PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object "
+ PolicyLogger
+ .error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object "
+ e.getMessage());
}
}
@@ -450,15 +437,13 @@ public class PolicyDBDao {
}
}
- logger.info(
- "PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync");
+ logger.info("PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync");
pdpGroup.setPolicies(newPolicySet);
return pdpGroup;
}
- public String removeExtensionAndVersionFromPolicyName(String originalPolicyName)
- throws PolicyDBException {
+ public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) throws PolicyDBException {
return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0];
}
@@ -468,8 +453,7 @@ public class PolicyDBDao {
* @param originalPolicyName: a policy file name ex: Config_policy.2.xml
* @return An array [0]: The policy name, [1]: the policy version, as a string
*/
- public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName)
- throws PolicyDBException {
+ public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException {
String policyName = originalPolicyName;
String[] nameAndVersion = new String[2];
try {
@@ -513,8 +497,7 @@ public class PolicyDBDao {
deleteAllGroupTables();
auditGroups(papEngine2);
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
- "auditLocalDatabase() error");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "auditLocalDatabase() error");
logger.error("Exception Occured" + e);
}
}
@@ -534,8 +517,7 @@ public class PolicyDBDao {
if (groupQueryList != null && !groupQueryList.isEmpty()) {
GroupEntity dbgroup = (GroupEntity) groupQueryList.get(0);
updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup);
- logger.info(
- "Group was updated during file system audit: " + updatedGroup.toString());
+ logger.info("Group was updated during file system audit: " + updatedGroup.toString());
}
} catch (PAPException | PolicyDBException e) {
logger.error(e);
@@ -543,8 +525,7 @@ public class PolicyDBDao {
logger.error(e);
PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
"Caught Exception trying to check if group exists groupQuery.getResultList()");
- throw new PersistenceException(
- "Query failed trying to check if group " + group.getId() + " exists");
+ throw new PersistenceException("Query failed trying to check if group " + group.getId() + " exists");
}
session.getTransaction().commit();
@@ -571,8 +552,7 @@ public class PolicyDBDao {
final Criteria configDataQuery = session.createCriteria(cl.getName());
@SuppressWarnings("unchecked")
final List<T> configDataResult = configDataQuery.list();
- Path webappsPath = Paths
- .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), type);
+ Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), type);
for (final T configData : configDataResult) {
String configName = null;
@@ -588,8 +568,7 @@ public class PolicyDBDao {
} else {
configName = ((ActionBodyEntity) configData).getActionBodyName();
configBody = (((ActionBodyEntity) configData).getActionBody() != null)
- ? ((ActionBodyEntity) configData).getActionBody()
- .getBytes(StandardCharsets.UTF_8)
+ ? ((ActionBodyEntity) configData).getActionBody().getBytes(StandardCharsets.UTF_8)
: "".getBytes();
}
Path filePath = Paths.get(webappsPath.toString(), configName);
@@ -662,15 +641,13 @@ public class PolicyDBDao {
for (PDPPolicy policy : policies) {
try {
- String[] stringArray =
- getNameScopeAndVersionFromPdpPolicy(policy.getId());
+ String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId());
if (stringArray == null) {
throw new IllegalArgumentException(
"Invalid input - policyID must contain name, scope and version");
}
List<PolicyEntity> policyEntityList;
- Query getPolicyEntitiesQuery =
- session.getNamedQuery("PolicyEntity.findByNameAndScope");
+ Query getPolicyEntitiesQuery = session.getNamedQuery("PolicyEntity.findByNameAndScope");
getPolicyEntitiesQuery.setParameter("name", stringArray[0]);
getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]);
@@ -694,8 +671,7 @@ public class PolicyDBDao {
}
} catch (Exception e) {
session.getTransaction().rollback();
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
- "Exception auditGroups outer catch");
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception auditGroups outer catch");
session.close();
return;
}
@@ -717,9 +693,8 @@ public class PolicyDBDao {
// config type selection for saving.
public String getConfigFile(String inputFilename, String configType) {
String filename = inputFilename;
- logger.debug(
- "getConfigFile(String filename, String scope, String configType) as getConfigFile("
- + filename + ", " + configType + ") called");
+ logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile(" + filename
+ + ", " + configType + ") called");
filename = FilenameUtils.removeExtension(filename);
String id = configType;
@@ -812,7 +787,6 @@ public class PolicyDBDao {
return papEngine;
}
-
public static boolean isJunit() {
return isJunit;
}
@@ -830,8 +804,7 @@ public class PolicyDBDao {
return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy);
}
- String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName)
- throws PolicyDBException {
+ String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException {
return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName);
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java
index dbb2fa830..250029a89 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java
@@ -21,8 +21,11 @@
package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.pap.PAPException;
+
import java.util.List;
+
import javax.persistence.PersistenceException;
+
import org.onap.policy.rest.dao.PolicyDBException;
import org.onap.policy.rest.jpa.GroupEntity;
import org.onap.policy.rest.jpa.PdpEntity;
@@ -70,7 +73,6 @@ public interface PolicyDBDaoTransaction {
*/
public void close();
-
/**
* Create a new PDP group in the database
*
@@ -162,7 +164,6 @@ public interface PolicyDBDaoTransaction {
public StdPDPGroup addPolicyToGroup(String group, String policyID, String requestType, String username)
throws PolicyDBException;
-
/**
* Delete an existing PDP groupPolicyDBException
*
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java
index f63649ddc..347db92d7 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java
@@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.components;
import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.api.pap.PDPPolicy;
import com.att.research.xacml.util.XACMLProperties;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -36,14 +37,17 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
+
import javax.persistence.PersistenceException;
import javax.persistence.RollbackException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
+
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.hibernate.Query;
@@ -71,7 +75,6 @@ import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
-
@Component
public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
@@ -88,7 +91,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
private static final String PDP_NOTIFICATION = "pdp";
private static final String GROUP_NOTIFICATION = "group";
-
private static final String DECISIONMS_MODEL = "MicroService_Model";
private static boolean isJunit = false;
Session session;
@@ -115,7 +117,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
private static SessionFactory sessionfactory;
-
/**
* Instantiates a new policy DB dao transaction instance.
*
@@ -629,7 +630,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
}
}
-
public PolicyEntity getPolicy(int policyId) {
return getPolicy(policyId, null, null);
}
@@ -835,7 +835,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction {
return configDataString;
}
-
@Override
public void close() {
synchronized (emLock) {
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java
index 7a0f708d8..6ef7a8f18 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java
@@ -2,7 +2,7 @@
* ============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.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.components;
import java.util.List;
@@ -31,8 +32,8 @@ import org.yaml.snakeyaml.constructor.Constructor;
public class SafePolicyBuilder {
- private SafePolicyBuilder(){
- //Private Constructor.
+ private SafePolicyBuilder() {
+ // Private Constructor.
}
public static ControlLoopGuard loadYamlGuard(String specification) {
@@ -45,40 +46,42 @@ public class SafePolicyBuilder {
return (ControlLoopGuard) obj;
}
- public static String generateXacmlGuard(String xacmlFileContent,Map<String, String> generateMap, List<String> blacklist, List<String> targets) {
- //Setup default values and Targets.
- StringBuilder targetRegex= new StringBuilder(".*|");
- if(targets!=null && !targets.isEmpty()){
+ public static String generateXacmlGuard(String xacmlFileContent, Map<String, String> generateMap,
+ List<String> blacklist, List<String> targets) {
+ // Setup default values and Targets.
+ StringBuilder targetRegex = new StringBuilder(".*|");
+ if (targets != null && !targets.isEmpty()) {
targetRegex = new StringBuilder();
- for(String t : targets){
+ for (String t : targets) {
targetRegex.append(t + "|");
}
}
- if(generateMap.get("clname")==null|| generateMap.get("clname").isEmpty()){
- generateMap.put("clname",".*");
+ if (generateMap.get("clname") == null || generateMap.get("clname").isEmpty()) {
+ generateMap.put("clname", ".*");
}
- generateMap.put("targets", targetRegex.toString().substring(0, targetRegex.length()-1));
+ generateMap.put("targets", targetRegex.toString().substring(0, targetRegex.length() - 1));
// Replace values.
- for(Map.Entry<String,String> map: generateMap.entrySet()){
- Pattern p = Pattern.compile("\\$\\{" +map.getKey() +"\\}");
+ for (Map.Entry<String, String> map : generateMap.entrySet()) {
+ Pattern p = Pattern.compile("\\$\\{" + map.getKey() + "\\}");
Matcher m = p.matcher(xacmlFileContent);
String finalInput = map.getValue();
- if(finalInput.contains("$")){
+ if (finalInput.contains("$")) {
finalInput = finalInput.replace("$", "\\$");
}
- xacmlFileContent=m.replaceAll(finalInput);
+ xacmlFileContent = m.replaceAll(finalInput);
}
- if(blacklist!=null && !blacklist.isEmpty()){
+ if (blacklist != null && !blacklist.isEmpty()) {
StringBuilder rule = new StringBuilder();
- for(String blackListName : blacklist){
- if(blackListName.contains("$")){
+ for (String blackListName : blacklist) {
+ if (blackListName.contains("$")) {
blackListName = blackListName.replace("$", "\\$");
}
- rule.append("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">"+blackListName+"</AttributeValue>");
+ rule.append("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">" + blackListName
+ + "</AttributeValue>");
}
Pattern p = Pattern.compile("\\$\\{blackListElement\\}");
Matcher m = p.matcher(xacmlFileContent);
- xacmlFileContent=m.replaceAll(rule.toString());
+ xacmlFileContent = m.replaceAll(rule.toString());
}
PolicyLogger.info("Generated XACML from the YAML Spec: \n" + xacmlFileContent);
return xacmlFileContent;