From fc5c07705edc4dcb7083b39116a43844bb6a1490 Mon Sep 17 00:00:00 2001 From: Ravindra Bakkamanthala Date: Mon, 5 Jun 2017 22:42:02 -0400 Subject: [PATCH] Fixed the Policy API issues and Bugfixes Change-Id: I6e8b54442421b6ebd0ff88426fc6e5f3a36b0690 Signed-off-by: Ravindra Bakkamanthala --- .../controlloop/policy/guard/Constraint.java | 22 +- .../controlloop/policy/guard/ControlLoopGuard.java | 7 +- .../controlloop/policy/guard/GuardPolicy.java | 8 +- .../compiler/ControlLoopGuardCompilerTest.java | 2 +- .../policy/guard/ControlLoopGuardBuilderTest.java | 4 +- .../policy/guard/ControlLoopGuardTest.java | 6 +- .../policy/pap/xacml/rest/XACMLPapServlet.java | 64 +-- .../pap/xacml/rest/components/ActionPolicy.java | 23 +- .../pap/xacml/rest/components/AutoPushPolicy.java | 4 +- .../rest/components/CreateBrmsParamPolicy.java | 138 ++----- .../xacml/rest/components/CreateBrmsRawPolicy.java | 10 +- ...eModel.java => CreateNewMicroServiceModel.java} | 130 ++---- .../pap/xacml/rest/components/DecisionPolicy.java | 156 ++++--- .../policy/pap/xacml/rest/components/Policy.java | 12 +- .../pap/xacml/rest/components/PolicyDBDao.java | 38 +- .../xacml/rest/components/SafePolicyBuilder.java | 26 +- .../MicroServiceDictionaryController.java | 2 +- .../rest/controller/PushPolicyController.java | 24 -- .../xacml/rest/elk/client/ElkConnectorImpl.java | 2 +- .../pap/xacml/rest/handler/DeleteHandler.java | 4 +- .../rest/policycontroller/PolicyCreation.java | 9 +- .../pap/xacml/rest/service/ImportService.java | 8 +- .../resources/Decision_GuardBLPolicyTemplate.xml | 62 +-- .../resources}/Decision_GuardPolicyTemplate.xml | 0 .../openecomp/policy/pdp/rest/PapUrlResolver.java | 1 - .../openecomp/policy/pdp/rest/XACMLPdpLoader.java | 2 +- .../policy/pdp/rest/api/services/PAPServices.java | 7 + .../api/services/PolicyEngineImportService.java | 6 +- .../policy/pdp/rest/config/PDPApiAuth.java | 6 +- .../openecomp/policy/rest/adapter/YAMLParams.java | 9 + ECOMP-SDK-APP/xacml.admin.properties | 2 +- .../policy/admin/PolicyManagerServlet.java | 140 ++++--- .../policy/admin/PolicyRestController.java | 17 +- .../controller/CreateBRMSParamController.java | 21 +- .../controller/DecisionPolicyController.java | 20 +- .../controller/PolicyValidationController.java | 314 ++++++++------ .../Windows/PDPTabWindows/AddorEditPDPtoGroup.html | 2 +- .../PushtabWindow/removeGroupPoliciesWindow.html | 2 +- .../BRMSParamDictGridController.js | 2 +- .../CLPepOptionsDictGridController.js | 2 +- .../CLServiceDictGridController.js | 2 +- .../CLSiteDictGridController.js | 2 +- .../CLVarbindDictGridController.js | 2 +- .../CLVnfTypeDictGridController.js | 2 +- .../CLVsclActionDictGridController.js | 2 +- .../ActionPolicyController.js | 1 + .../DCAEMicroServicePolicyController.js | 7 +- .../DecisionPolicyController.js | 26 +- .../PolicyTemplates/ActionPolicyTemplate.html | 2 +- .../ClosedLoopFaultPolicyTemplate.html | 2 +- .../PolicyTemplates/DecisionPolicyTemplate.html | 81 +++- .../Editor/PolicyTemplates/PolicyTypeTemplate.html | 2 +- .../policyApp/policy-models/policy_AutoPush.html | 13 +- .../policyApp/policy-models/policy_Dictionary.html | 25 +- .../policy-models/policy_PDPManagement.html | 13 +- .../app/policyApp/policy-models/policy_Roles.html | 21 +- .../org/openecomp/policy/api/RuleProvider.java | 6 +- .../org/openecomp/policy/std/StdPolicyEngine.java | 16 +- .../policyEngine/ClosedLoopPolicyClient.java | 26 +- .../ClosedLoopPolicyPerformanceMetricClient.java | 22 +- .../policyEngine/ConfigFirewallPolicyClient.java | 28 +- .../policyEngine/MicroServicesPolicyClient.java | 22 +- .../org/openecomp/policy/utils/PolicyUtils.java | 84 ++-- .../org/openecomp/policy/test/PolicyUtilsTest.java | 2 - .../src/files/install/elk/config/elasticsearch.yml | 460 ++++----------------- packages/base/src/files/install/elk/init.d/elkd | 4 +- .../install/mysql/data/161000_upgrade_script.sql | 2 +- .../install/mysql/data/170701_upgrade_script.sql | 4 +- .../servers/console/bin/xacml.admin.properties | 4 + .../install/servers/pap/bin/xacml.pap.properties | 2 + ....Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt | 2 +- ....Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.txt | 2 +- .../install/servers/pdp/bin/xacml.pdp.properties | 1 + 73 files changed, 1087 insertions(+), 1117 deletions(-) rename ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/{CreateNewMicroSerivceModel.java => CreateNewMicroServiceModel.java} (69%) rename packages/base/src/files/install/servers/pap/bin/Decision_GuardPolicyTemplate.xml => ECOMP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml (67%) rename ECOMP-PAP-REST/{ => src/main/resources}/Decision_GuardPolicyTemplate.xml (100%) diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java index 85ddf066d..42a04e7b7 100644 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java @@ -77,6 +77,13 @@ public class Constraint { this.blacklist = new LinkedList<>(blacklist); } + + public Constraint(Map time_in_range, List blacklist) { + if (time_in_range != null) { + this.time_in_range = Collections.unmodifiableMap(time_in_range); + } + this.blacklist = new LinkedList<>(blacklist); + } public Constraint(Integer num, String duration, List blacklist) { this.num = num; @@ -84,6 +91,13 @@ public class Constraint { this.blacklist = new LinkedList<>(blacklist); } + public Constraint(Integer num, String duration, Map time_in_range) { + this(num, duration); + if (time_in_range != null) { + this.time_in_range = Collections.unmodifiableMap(time_in_range); + } + } + public Constraint(Integer num, String duration, Map time_in_range, List blacklist) { this(num, duration); if (time_in_range != null) { @@ -102,13 +116,7 @@ public class Constraint { } public boolean isValid() { - if (num == null && duration != null) { - return false; - } - if (duration == null && num != null) { - return false; - } - return true; + return ((num == null && duration != null)|| (duration == null && num != null))? false : true; } @Override diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java index cfc904823..3df2a0885 100644 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java @@ -20,13 +20,12 @@ package org.openecomp.policy.controlloop.policy.guard; import java.util.LinkedList; -import java.util.List; public class ControlLoopGuard { private Guard guard; - private List guards; + private LinkedList guards; public ControlLoopGuard() { //DO Nothing Empty Constructor @@ -40,11 +39,11 @@ public class ControlLoopGuard { this.guard = guard; } - public List getGuards() { + public LinkedList getGuards() { return guards; } - public void setGuards(List guards) { + public void setGuards(LinkedList guards) { this.guards = guards; } diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java index 7eb8af6d1..a4d56ff07 100644 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java +++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java @@ -31,7 +31,7 @@ public class GuardPolicy { private String description; private String actor; private String recipe; - private List limit_constraints; + private LinkedList limit_constraints; public GuardPolicy() { //Do Nothing Empty Constructor. @@ -77,11 +77,11 @@ public class GuardPolicy { this.recipe = recipe; } - public List getLimit_constraints() { - return limit_constraints; + public LinkedList getLimit_constraints() { + return limit_constraints; } - public void setLimit_constraints(List limit_constraints) { + public void setLimit_constraints(LinkedList limit_constraints) { this.limit_constraints = limit_constraints; } diff --git a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java index 1e035edf4..e2701eefb 100644 --- a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java +++ b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java @@ -31,7 +31,7 @@ import org.junit.Test; import org.openecomp.policy.controlloop.guard.compiler.ControlLoopGuardCompiler; public class ControlLoopGuardCompilerTest { - + @Test public void testTest1() { try { diff --git a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java index 5df0266ec..3137a1232 100644 --- a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java +++ b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java @@ -142,12 +142,12 @@ public class ControlLoopGuardBuilderTest { fail(e.getMessage()); } } - + @Test public void test1() { this.test("src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml"); } - + @Test public void test2() { this.test("src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml"); diff --git a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.java b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.java index a09fd2112..4575e594f 100644 --- a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.java +++ b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.java @@ -19,7 +19,9 @@ */ package org.openecomp.policy.controlloop.policy.guard; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; @@ -35,7 +37,7 @@ import org.yaml.snakeyaml.constructor.Constructor; public class ControlLoopGuardTest { - + @Test public void testGuardvDNS() { this.test("src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml"); diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java index 685582e29..edbc2acb7 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java @@ -1343,7 +1343,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); auditLogger.info("Success"); - if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) { + if (policy != null && (policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) { PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); if (pushPolicyHandler.preSafetyCheck(policy, CONFIG_HOME)) { LOGGER.debug("Precheck Successful."); @@ -1801,10 +1801,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (papEngine.getPDP(pdpId) == null) { // this is a request to create a new PDP object try{ - acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut"); + acPutTransaction.addPdpToGroup(pdp == null ? "PDP is null" : pdp.getId(), group.getId(), pdp == null ? "PDP is null" : pdp.getName(), + pdp == null ? "PDP is null" : pdp.getDescription(), + pdp == null ? 0 : pdp.getJmxPort(),"XACMLPapServlet.doACPut"); } catch(Exception e){ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: " - +"pdp="+pdp.getId()+",to group="+group.getId()); + +"pdp="+ (pdp == null ? "PDP is null" : pdp.getId()) +",to group="+group.getId()); throw new PAPException(e.getMessage()); } papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort()); @@ -1813,7 +1815,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut"); } catch(Exception e){ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: " - +"pdp="+pdp.getId()); + +"pdp="+(pdp == null ? "PDP is null" : pdp.getId())); throw new PAPException(e.getMessage()); } // this is a request to update the pdp @@ -1867,7 +1869,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // The Path on the PAP side is not carried on the RESTful interface with the AC // (because it is local to the PAP) // so we need to fill that in before submitting the group for update - ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory()); + if(objectFromJSON != null){ + ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory()); + } try{ acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut"); } catch(Exception e){ @@ -2138,26 +2142,28 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList HttpURLConnection connection = null; try { // Open up the connection - connection = (HttpURLConnection)pdpURL.openConnection(); - // Setup our method and headers - connection.setRequestMethod("GET"); - connection.setConnectTimeout(heartbeatTimeout); - // Authentication - String encoding = CheckPDP.getEncoding(pdp.getId()); - if(encoding !=null){ - connection.setRequestProperty("Authorization", "Basic " + encoding); - } - // Do the connect - connection.connect(); - if (connection.getResponseCode() == 204) { - newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'"); + if(pdpURL != null){ + connection = (HttpURLConnection)pdpURL.openConnection(); + // Setup our method and headers + connection.setRequestMethod("GET"); + connection.setConnectTimeout(heartbeatTimeout); + // Authentication + String encoding = CheckPDP.getEncoding(pdp.getId()); + if(encoding !=null){ + connection.setRequestProperty("Authorization", "Basic " + encoding); } - } else { - // anything else is an unexpected result - newStatus = PDPStatus.Status.UNKNOWN.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId()); + // Do the connect + connection.connect(); + if (connection.getResponseCode() == 204) { + newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'"); + } + } else { + // anything else is an unexpected result + newStatus = PDPStatus.Status.UNKNOWN.toString(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId()); + } } } catch (UnknownHostException e) { newStatus = PDPStatus.Status.NO_SUCH_HOST.toString(); @@ -2173,7 +2179,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception"); } finally { // cleanup the connection - connection.disconnect(); + if(connection != null) + connection.disconnect(); } if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) { if (LOGGER.isDebugEnabled()) { @@ -2372,7 +2379,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } finally { // cleanup the connection - connection.disconnect(); + if(connection != null){ + connection.disconnect(); + } // tell the AC to update it's status info notifyAC(); } @@ -2436,7 +2445,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList disconnectedACs.add(acURL); } finally { // cleanup the connection - connection.disconnect(); + if(connection != null) + connection.disconnect(); } } // remove any ACs that are no longer connected diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java index 1884aab62..45ef01f6e 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java @@ -328,8 +328,7 @@ public class ActionPolicy extends Policy { // Add JSON_URL Assignment: String actionBody = getActionPolicyDict(comboDictValue).getBody(); - if (!actionBody.equals(null)) { - //if(!(actionBody==null || "".equals(actionBody))){ + if (actionBody != null) { AttributeAssignmentExpressionType assignmentJsonURL = new AttributeAssignmentExpressionType(); assignmentJsonURL.setAttributeId(BODY_ATTRIBUTEID); assignmentJsonURL.setCategory(CATEGORY_RESOURCE); @@ -342,7 +341,7 @@ public class ActionPolicy extends Policy { obligation.getAttributeAssignmentExpression().add(assignmentJsonURL); } - if(!getActionPolicyDict(comboDictValue).getHeader().equals(null)){ + if(getActionPolicyDict(comboDictValue).getHeader() != null){ String headerVal = getActionPolicyDict(comboDictValue).getHeader(); if(headerVal != null && !headerVal.equals("")){ // parse it on : to get number of headers @@ -484,21 +483,23 @@ public class ActionPolicy extends Policy { private Map createDropDownMap(){ JPAUtils jpaUtils = null; + Map dropDownMap = new HashMap<>(); try { jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf()); } catch (Exception e) { LOGGER.error("Exception Occured"+e); } - Map> functionMap = jpaUtils.getFunctionDatatypeMap(); - Map dropDownMap = new HashMap<>(); - for (Datatype id : functionMap.keySet()) { - List functionDefinitions = (List) functionMap - .get(id); - for (FunctionDefinition functionDef : functionDefinitions) { - dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid()); + if(jpaUtils != null){ + Map> functionMap = jpaUtils.getFunctionDatatypeMap(); + + for (Datatype id : functionMap.keySet()) { + List functionDefinitions = (List) functionMap + .get(id); + for (FunctionDefinition functionDef : functionDefinitions) { + dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid()); + } } } - return dropDownMap; } diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java index b9ed78ef6..b658483d2 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java @@ -136,9 +136,7 @@ public class AutoPushPolicy { //Get the current policies from the Group and Add the new one Set currentPoliciesInGroup = pdpGroup.getPolicies(); Set policies = new HashSet<>(); - if(policy!=null){ - policies.add(policy); - } + policies.add(policy); pdpGroup.copyPolicyToFile(policyId, new FileInputStream(Paths.get(policyToCreateUpdate).toFile())); //If the selected policy is in the group we must remove it because the name is default Iterator policyIterator = policies.iterator(); diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java index 535b2edd3..b9dc039fc 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java @@ -29,17 +29,11 @@ import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Map; -import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -50,11 +44,11 @@ import org.openecomp.policy.common.logging.eelf.PolicyLogger; import org.openecomp.policy.common.logging.flexlogger.FlexLogger; import org.openecomp.policy.common.logging.flexlogger.Logger; import org.openecomp.policy.pap.xacml.rest.controller.BRMSDictionaryController; -import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.jpa.BRMSParamTemplate; import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.util.XACMLProperties; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; @@ -74,14 +68,6 @@ public class CreateBrmsParamPolicy extends Policy { private static final Logger LOGGER = FlexLogger.getLogger(CreateBrmsParamPolicy.class); - /* - * These are the parameters needed for DB access from the PAP - */ - private static String papDbDriver = null; - private static String papDbUrl = null; - private static String papDbUser = null; - private static String papDbPassword = null; - public CreateBrmsParamPolicy() { super(); } @@ -92,38 +78,35 @@ public class CreateBrmsParamPolicy extends Policy { } - public String expandConfigBody(String ruleContents, Map brmsParamBody) { - - Set keySet= new HashSet<>(); - - Map copyMap=new HashMap<>(); - copyMap.putAll(brmsParamBody); - copyMap.put("policyName", policyName.substring(0, policyName.replace(".xml", "").lastIndexOf("."))); - copyMap.put("policyScope", policyAdapter.getDomainDir()); - 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. - keySet= copyMap.keySet(); - Iterator iterator = keySet.iterator(); - Pattern p; - Matcher m; - while(iterator.hasNext()) { - //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. - p=Pattern.compile("\\$\\{"+output+"\\}"); - m=p.matcher(ruleContents); - //Replacing the value with the inputs provided by the user in the editor. - String finalInput = copyMap.get(input); - if(finalInput.contains("$")){ - finalInput = finalInput.replace("$", "\\$"); - } - ruleContents=m.replaceAll(finalInput); + public String expandConfigBody(String ruleContents, Map brmsParamBody) { + + Map copyMap=new HashMap<>(); + copyMap.putAll(brmsParamBody); + copyMap.put("policyName", policyName.substring(0, policyName.replace(".xml", "").lastIndexOf("."))); + copyMap.put("policyScope", policyAdapter.getDomainDir()); + 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. + Iterator iterator = copyMap.keySet().iterator(); + Pattern p; + Matcher m; + while(iterator.hasNext()) { + //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. + p=Pattern.compile("\\$\\{"+output+"\\}"); + m=p.matcher(ruleContents); + //Replacing the value with the inputs provided by the user in the editor. + String finalInput = copyMap.get(input); + if(finalInput.contains("$")){ + finalInput = finalInput.replace("$", "\\$"); } - return ruleContents; + ruleContents=m.replaceAll(finalInput); + } + return ruleContents; } @@ -194,13 +177,9 @@ public class CreateBrmsParamPolicy extends Policy { // xml. Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - - Boolean dbIsUpdated = true; - - successMap = new HashMap<>(); - if (dbIsUpdated) { - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); - } else { + successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + if(successMap == null){ + successMap = new HashMap<>(); PolicyLogger.error("Failed to Update the Database Dictionary Tables."); successMap.put("error", "DB UPDATE"); } @@ -208,50 +187,15 @@ public class CreateBrmsParamPolicy extends Policy { } private String getValueFromDictionary(String templateName){ - - Connection con = null; - Statement st = null; - ResultSet rs = null; - - /* - * Retrieve the property values for db access from the xacml.pap.properties - */ - papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); - papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); - papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); - papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); - - String ruleTemplate=null; - - try { - //Get DB Connection - Class.forName(papDbDriver); - con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword); - st = con.createStatement(); - - String queryString="select rule from BRMSParamTemplate where param_template_name=\""; - queryString=queryString+templateName+"\""; - - rs = st.executeQuery(queryString); - if(rs.next()){ - ruleTemplate=rs.getString("rule"); - } - rs.close(); - }catch (ClassNotFoundException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateBrmsParamPolicy", "Exception querying BRMSParamTemplate"); - } catch (SQLException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateBrmsParamPolicy", "Exception querying BRMSParamTemplate"); - } finally { - try{ - if (con!=null) con.close(); - if (rs!=null) rs.close(); - if (st!=null) st.close(); - } catch (Exception ex){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, ex, "CreateBrmsParamPolicy", "Exception querying BRMSParamTemplate"); - } + String ruleTemplate = null; + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + String queryString="from BRMSParamTemplate where param_template_name= '"+templateName+"'"; + List result = dbConnection.getDataByQuery(queryString); + if(!result.isEmpty()){ + BRMSParamTemplate template = (BRMSParamTemplate) result.get(0); + ruleTemplate = template.getRule(); } return ruleTemplate; - } protected Map findType(String rule) { diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java index 350bbc4ff..a0f13ec02 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java @@ -131,13 +131,9 @@ public class CreateBrmsRawPolicy extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - Boolean dbIsUpdated = true; - - successMap = new HashMap(); - if (dbIsUpdated) { - successMap = createPolicy(newPolicyPath, - getCorrectPolicyDataObject()); - } else { + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); + if (successMap == null) { + successMap = new HashMap<>(); PolicyLogger.error("Failed to Update the Database Dictionary Tables."); successMap.put("error", "DB UPDATE"); } diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroSerivceModel.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java similarity index 69% rename from ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroSerivceModel.java rename to ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java index 0e4e409d3..e801a459d 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroSerivceModel.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java @@ -25,11 +25,6 @@ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; @@ -46,38 +41,28 @@ import org.openecomp.policy.common.logging.eelf.PolicyLogger; import org.openecomp.policy.common.logging.flexlogger.FlexLogger; import org.openecomp.policy.common.logging.flexlogger.Logger; import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.openecomp.policy.rest.jpa.MicroServiceModels; import org.openecomp.policy.rest.jpa.UserInfo; import org.openecomp.policy.rest.util.MSAttributeObject; import org.openecomp.policy.rest.util.MSModelUtils; import org.openecomp.policy.rest.util.MSModelUtils.MODEL_TYPE; -import com.att.research.xacml.util.XACMLProperties; - -public class CreateNewMicroSerivceModel { - private static final Logger logger = FlexLogger.getLogger(CreateNewMicroSerivceModel.class); +public class CreateNewMicroServiceModel { + private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class); private MicroServiceModels newModel = null; private HashMap classMap = new HashMap<>(); - /* - * These are the parameters needed for DB access from the PAP - */ - private static String papDbDriver = null; - private static String papDbUrl = null; - private static String papDbUser = null; - private static String papDbPassword = null; MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsEcompName(), XACMLPapServlet.getMsPolicyName()); - public CreateNewMicroSerivceModel(String fileName, String serviceName, String string, String version) { + public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) { super(); } - public CreateNewMicroSerivceModel(String importFile, String modelName, String description, String version, String randomID) { + public CreateNewMicroServiceModel(String importFile, String modelName, String description, String version, String randomID) { this.newModel = new MicroServiceModels(); - this.newModel.setDescription(description); this.newModel.setVersion(version); this.newModel.setModelName(modelName); UserInfo userInfo = new UserInfo(); @@ -135,7 +120,7 @@ public class CreateNewMicroSerivceModel { int BUFFER = 2048; File file = new File(zipFile); - ZipFile zip; + ZipFile zip = null; try { zip = new ZipFile("ExtractDir" + File.separator +file); String newPath = zipFile.substring(0, zipFile.length() - 4); @@ -143,8 +128,7 @@ public class CreateNewMicroSerivceModel { 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(); @@ -153,8 +137,7 @@ public class CreateNewMicroSerivceModel { destinationParent.mkdirs(); - if (!entry.isDirectory()) - { + if (!entry.isDirectory()){ BufferedInputStream is = new BufferedInputStream(zip .getInputStream(entry)); int currentByte; @@ -173,13 +156,20 @@ public class CreateNewMicroSerivceModel { is.close(); } - if (currentEntry.endsWith(".zip")) - { + if (currentEntry.endsWith(".zip")){ extractFolder(destFile.getAbsolutePath()); } } } catch (IOException e) { - logger.error("Failed to unzip model file " + zipFile); + logger.error("Failed to unzip model file " + zipFile + e); + }finally{ + if(zip != null){ + try { + zip.close(); + } catch (Exception e) { + logger.error("Exception Occured while closing the zip file"+e); + } + } } } @@ -225,70 +215,34 @@ public class CreateNewMicroSerivceModel { } - @SuppressWarnings("resource") public Map saveImportService(){ - Map successMap = new HashMap<>(); - - Connection con = null; - Statement st = null; - ResultSet rs = null; String modelName = this.newModel.getModelName(); String imported_by = "API"; String version = this.newModel.getVersion(); - String insertQuery = null; - int ID = 0; - - /* - * Retrieve the property values for db access from the xacml.pap.properties - */ - papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); - papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); - papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); - papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); - - try { - //Get DB Connection - Class.forName(papDbDriver); - con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword); - st = con.createStatement(); - String queryString ="SELECT * FROM MicroServiceModels WHERE modelName='" + modelName + "' AND version='" + version+ "';"; - rs = st.executeQuery(queryString); - - if(rs.next()){ - successMap.put("DBError", "EXISTS"); - logger.error("Import new service failed. Service already exists"); - }else{ - rs = st.executeQuery("SELECT MAX(ID) AS ID FROM MicroServiceModels;"); - if(rs.next()){ - ID = rs.getInt("ID"); - ID++; - } - - String newDependency = "[" + this.newModel.getDependency() + "]"; - this.newModel.setDependency(newDependency); - insertQuery = "INSERT INTO MicroServiceModels (ID, modelName, Dependency, DESCRIPTION, attributes, ref_attributes, sub_attributes, version, imported_by, enumValues, annotation) " - + "VALUES("+ID+",'"+modelName+"','"+ this.newModel.getDependency()+"','"+this.newModel.getDescription()+"','"+this.newModel.getAttributes()+ - "','"+this.newModel.getRef_attributes()+"','"+this.newModel.getSub_attributes()+"','"+version+"','"+imported_by+"','"+this.newModel.getEnumValues()+"','"+this.newModel.getAnnotation()+"')"; - st.executeUpdate(insertQuery); - successMap.put("success", "success"); - } - rs.close(); - }catch (ClassNotFoundException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "saveImportService", "Exception querying MicroServiceModels"); - successMap.put("DBError", "Error Query"); - } catch (SQLException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "saveImportService", "Exception querying MicroServiceModels"); - successMap.put("DBError", "Error Query"); - } finally { - try{ - if (con!=null) con.close(); - if (rs!=null) rs.close(); - if (st!=null) st.close(); - } catch (Exception ex){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, ex, "saveImportService", "Exception querying MicroServiceModels"); - } - } - + Map successMap = new HashMap<>(); + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + List result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+version); + if(result.isEmpty()){ + MicroServiceModels model = new MicroServiceModels(); + model.setModelName(modelName); + model.setVersion(version); + model.setAttributes(this.newModel.getAttributes()); + model.setAnnotation(this.newModel.getAnnotation()); + model.setDependency(this.newModel.getDependency()); + model.setDescription(this.newModel.getDescription()); + model.setEnumValues(this.newModel.getEnumValues()); + model.setRef_attributes(this.newModel.getRef_attributes()); + model.setSub_attributes(this.newModel.getSub_attributes()); + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(imported_by); + userInfo.setUserName(imported_by); + model.setUserCreatedBy(userInfo); + dbConnection.save(model); + successMap.put("success", "success"); + }else{ + successMap.put("DBError", "EXISTS"); + logger.error("Import new service failed. Service already exists"); + } return successMap; } } diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java index 8d2617ce2..02ea630a6 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java @@ -21,6 +21,7 @@ package org.openecomp.policy.pap.xacml.rest.components; import java.io.ByteArrayInputStream; +import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; @@ -28,6 +29,8 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -85,7 +88,13 @@ public class DecisionPolicy extends Policy { public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not"; private static final String AAFProvider = "AAF"; public static final String GUARD_YAML = "GUARD_YAML"; - private static final String XACMLTEMPLATE = "Decision_GuardPolicyTemplate.xml"; + public static final String GUARD_BL_YAML = "GUARD_BL_YAML"; + private static final String XACML_GUARD_TEMPLATE = "Decision_GuardPolicyTemplate.xml"; + private static final String XACML_BLGUARD_TEMPLATE = "Decision_GuardBLPolicyTemplate.xml"; + + private static final String ECOMPNAME = "ECOMPName"; + private static final String POLICY_NAME = "PolicyName"; + private static final String DESCRIPTION = "description"; List dynamicLabelRuleAlgorithms = new LinkedList<>(); @@ -142,7 +151,7 @@ public class DecisionPolicy extends Policy { version = policyAdapter.getHighestVersion(); // Create the Instance for pojo, PolicyType object is used in marshalling. - if (policyAdapter.getPolicyType().equals("Decision")) { + if ("Decision".equals(policyAdapter.getPolicyType())) { PolicyType policyConfig = new PolicyType(); policyConfig.setVersion(Integer.toString(version)); @@ -152,20 +161,20 @@ public class DecisionPolicy extends Policy { } policyName = policyAdapter.getNewFileName(); - if(policyAdapter.getRuleProvider().equals(GUARD_YAML)){ + if(policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML)){ Map yamlParams = new HashMap<>(); - yamlParams.put("description", (policyAdapter.getPolicyDescription()!=null)? policyAdapter.getPolicyDescription(): "YAML Guard Policy"); + yamlParams.put(DESCRIPTION, (policyAdapter.getPolicyDescription()!=null)? policyAdapter.getPolicyDescription(): "YAML Guard Policy"); String fileName = policyAdapter.getNewFileName(); - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length()); + if ((name == null) || ("".equals(name))) { + name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); } - yamlParams.put("PolicyName", name); - yamlParams.put("ECOMPName", policyAdapter.getEcompName()); + yamlParams.put(POLICY_NAME, name); + yamlParams.put(ECOMPNAME, policyAdapter.getEcompName()); Map params = policyAdapter.getDynamicFieldConfigAttributes(); yamlParams.putAll(params); // Call YAML to XACML - PolicyType decisionPolicy = getGuardPolicy(yamlParams); + PolicyType decisionPolicy = getGuardPolicy(yamlParams, policyAdapter.getRuleProvider()); decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); decisionPolicy.setVersion(Integer.toString(version)); policyAdapter.setPolicyData(decisionPolicy); @@ -178,16 +187,16 @@ public class DecisionPolicy extends Policy { decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); AllOfType allOfOne = new AllOfType(); String fileName = policyAdapter.getNewFileName(); - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length()); + if ((name == null) || ("".equals(name))) { + name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); } - allOfOne.getMatch().add(createMatch("PolicyName", name)); + allOfOne.getMatch().add(createMatch(POLICY_NAME, name)); AllOfType allOf = new AllOfType(); // Match for Ecomp - allOf.getMatch().add(createMatch("ECOMPName", (policyAdapter.getEcompName()))); + allOf.getMatch().add(createMatch(ECOMPNAME, (policyAdapter.getEcompName()))); Map dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes(); if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFProvider)){ @@ -235,44 +244,73 @@ public class DecisionPolicy extends Policy { return true; } - public PolicyType getGuardPolicy(Map yamlParams) { + public PolicyType getGuardPolicy(Map yamlParams, String ruleProvider) { try { ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard()); - GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get("PolicyName"), yamlParams.get("description"), yamlParams.get("actor"), yamlParams.get("recipe")); + GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), yamlParams.get("actor"), yamlParams.get("recipe")); builder = builder.addGuardPolicy(policy1); Map time_in_range = new HashMap<>(); time_in_range.put("arg2", yamlParams.get("guardActiveStart")); time_in_range.put("arg3", yamlParams.get("guardActiveEnd")); - Constraint cons = new Constraint(Integer.parseInt(yamlParams.get("limit")), yamlParams.get("timeWindow")); - cons.setTime_in_range(time_in_range); + String blackListString = yamlParams.get("blackList"); + List blackList = null; + if(blackListString!=null){ + if (blackListString.contains(",")){ + blackList = Arrays.asList(blackListString.split(",")); + } + else{ + blackList = new ArrayList<>(); + blackList.add(blackListString); + } + } + File templateFile; + Path xacmlTemplatePath; + Constraint cons; + ClassLoader classLoader = getClass().getClassLoader(); + switch (ruleProvider){ + case GUARD_BL_YAML: + templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile()); + xacmlTemplatePath = templateFile.toPath(); + cons = new Constraint(time_in_range,blackList); + break; + default: + templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile()); + xacmlTemplatePath = templateFile.toPath(); + cons = new Constraint(Integer.parseInt(yamlParams.get("limit")), yamlParams.get("timeWindow"), time_in_range); + break; + } builder = builder.addLimitConstraint(policy1.getId(), cons); // Build the specification Results results = builder.buildSpecification(); // YAML TO XACML ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification()); - Path xacmlTemplatePath = Paths.get(XACMLTEMPLATE); + String xacmlTemplateContent; try { xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); - HashMap yamlSpecs = new HashMap(); - yamlSpecs.put("PolicyName", yamlParams.get("PolicyName")); - yamlSpecs.put("description", yamlParams.get("description")); - yamlSpecs.put("ECOMPName", yamlParams.get("ECOMPName")); - yamlSpecs.put("actor", ((LinkedList)yamlGuardObject.getGuards()).getFirst().getActor()); - yamlSpecs.put("recipe", ((LinkedList)yamlGuardObject.getGuards()).getFirst().getRecipe()); - yamlSpecs.put("limit", ((LinkedList)((LinkedList)yamlGuardObject.getGuards()).getFirst().getLimit_constraints()).getFirst().getNum().toString()); - yamlSpecs.put("timeWindow", ((LinkedList)((LinkedList)yamlGuardObject.getGuards()).getFirst().getLimit_constraints()).getFirst().getDuration()); - yamlSpecs.put("guardActiveStart", ((LinkedList)((LinkedList)yamlGuardObject.getGuards()).getFirst().getLimit_constraints()).getFirst().getTime_in_range().get("arg2")); - yamlSpecs.put("guardActiveEnd", ((LinkedList)((LinkedList)yamlGuardObject.getGuards()).getFirst().getLimit_constraints()).getFirst().getTime_in_range().get("arg3")); - String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs); - // Convert the Policy into Stream input to Policy Adapter. + HashMap yamlSpecs = new HashMap<>(); + yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME)); + yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION)); + yamlSpecs.put(ECOMPNAME, yamlParams.get(ECOMPNAME)); + yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getActor()); + yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getRecipe()); + if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getNum()!=null){ + yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getNum().toString()); + } + if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getDuration()!=null){ + yamlSpecs.put("timeWindow", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getDuration()); + } + yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_in_range().get("arg2")); + yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_in_range().get("arg3")); + String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist()); + // Convert the Policy into Stream input to Policy Adapter. Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8))); return (PolicyType) policy; } catch (IOException e) { - PolicyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage()); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() + e); } } catch (BuilderException e) { - PolicyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage()); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() +e); } return null; } @@ -394,19 +432,19 @@ public class DecisionPolicy extends Policy { decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); policyAdapter.setPolicyData(decisionPolicy); - }else if (dynamicLabelRuleAlgorithms != null && dynamicLabelRuleAlgorithms.size() > 0) { + }else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) { boolean isCompound = false; ConditionType condition = new ConditionType(); int index = dynamicFieldOneRuleAlgorithms.size() - 1; for (String labelAttr : dynamicLabelRuleAlgorithms) { // if the rule algorithm as a label means it is a compound - if (dynamicFieldOneRuleAlgorithms.get(index).toString().equals(labelAttr)) { + if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) { ApplyType decisionApply = new ApplyType(); - String selectedFunction = (String) dynamicFieldComboRuleAlgorithms.get(index).toString(); - String value1 = (String) dynamicFieldOneRuleAlgorithms.get(index).toString(); - String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString(); + String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index); + String value1 = dynamicFieldOneRuleAlgorithms.get(index); + String value2 = dynamicFieldTwoRuleAlgorithms.get(index); decisionApply.setFunctionId(dropDownMap.get(selectedFunction)); decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1))); decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2))); @@ -416,7 +454,7 @@ public class DecisionPolicy extends Policy { // if rule algorithm not a compound if (!isCompound) { - condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index).toString()))); + condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index)))); } } if (!permitRule) { @@ -452,7 +490,7 @@ public class DecisionPolicy extends Policy { // check the index for the label. for (String labelAttr : dynamicLabelRuleAlgorithms) { if (labelAttr.equals(value1Label)) { - String value1 = (String) dynamicFieldOneRuleAlgorithms.get(index).toString(); + String value1 = dynamicFieldOneRuleAlgorithms.get(index); populateDataTypeList(value1); // check if the row contains label again @@ -463,8 +501,8 @@ public class DecisionPolicy extends Policy { } // Getting the values from the form. - String functionKey = (String) dynamicFieldComboRuleAlgorithms.get(index).toString(); - String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString(); + String functionKey = dynamicFieldComboRuleAlgorithms.get(index); + String value2 = dynamicFieldTwoRuleAlgorithms.get(index); decisionApply.setFunctionId(dropDownMap.get(functionKey)); // if two text field are rule attributes. if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) { @@ -550,9 +588,9 @@ public class DecisionPolicy extends Policy { // if the rule algorithm is multiple compound one setting the apply protected ApplyType getCompoundDecisionApply(int index) { ApplyType decisionApply = new ApplyType(); - String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index).toString(); - String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString(); - String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString(); + String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index); + String value1 = dynamicFieldOneRuleAlgorithms.get(index); + String value2 = dynamicFieldTwoRuleAlgorithms.get(index); decisionApply.setFunctionId(dropDownMap.get(selectedFunction)); decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1))); decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2))); @@ -574,16 +612,14 @@ public class DecisionPolicy extends Policy { } private void populateDataTypeList(String value1) { - - ///String value1 = dynamicFieldDecisionOneRuleAlgorithms.get(index).getValue().toString(); String dataType = null; if(value1.contains("S_")) { value1 = value1.substring(2, value1.length()); - DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1); - if (decisionSettings != null && decisionSettings.getDatatypeBean().getShortName().equals("string")) { + DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length())); + if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) { dataType = STRING_DATATYPE; - } else if (decisionSettings != null && decisionSettings.getDatatypeBean().getShortName().equals("boolean")) { + } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) { dataType = BOOLEAN_DATATYPE; } else { dataType = INTEGER_DATATYPE; @@ -602,13 +638,13 @@ public class DecisionPolicy extends Policy { } catch (Exception e) { LOGGER.error("Exception Occured"+e); } - Map> functionMap = jpaUtils.getFunctionDatatypeMap(); - Map dropDownMap = new HashMap(); - for (Datatype id : functionMap.keySet()) { - List functionDefinitions = (List) functionMap - .get(id); - for (FunctionDefinition functionDef : functionDefinitions) { - dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid()); + Map dropDownMap = new HashMap<>(); + if(jpaUtils!=null){ + Map> functionMap = jpaUtils.getFunctionDatatypeMap(); + for (Map.Entry> map: functionMap.entrySet()) { + for (FunctionDefinition functionDef : map.getValue()) { + dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid()); + } } } @@ -620,9 +656,9 @@ public class DecisionPolicy extends Policy { DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key); String dataType = null; - if (decisionSettings != null && decisionSettings.getDatatypeBean().getShortName().equals("string")) { + if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) { dataType = STRING_DATATYPE; - } else if (decisionSettings != null && decisionSettings.getDatatypeBean().getShortName().equals("boolean")) { + } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) { dataType = BOOLEAN_DATATYPE; } else { dataType = INTEGER_DATATYPE; diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java index 48431fe93..536f8e6b3 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java @@ -210,13 +210,17 @@ public abstract class Policy { // Validation for json. protected static boolean isJSONValid(String data) { + JsonReader jsonReader = null; try { new JSONObject(data); InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); - JsonReader jsonReader = Json.createReader(stream); + jsonReader = Json.createReader(stream); System.out.println("Json Value is: " + jsonReader.read().toString() ); } catch (Exception e) { + LOGGER.error("Exception Occured while reading json"+e); return false; + }finally{ + jsonReader.close(); } return true; } @@ -308,6 +312,12 @@ public abstract class Policy { } } catch (Exception e) { success.put("error", "Validation Failed"); + }finally{ + try { + inputStream.close(); + } catch (IOException e) { + LOGGER.error("Exception Occured while closing the input stream"+e); + } } } else { PolicyLogger.error("Unknown data type sent back."); diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java index 51fcb3d09..b65557e05 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java @@ -35,7 +35,6 @@ import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; @@ -69,8 +68,6 @@ 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.PolicyType; - import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; @@ -105,6 +102,8 @@ import com.att.research.xacml.api.pap.PDP; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + public class PolicyDBDao { private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class); private List otherServers; @@ -871,6 +870,7 @@ public class PolicyDBDao { try { policyStream.close(); } catch (IOException e) { + didUpdate = false; PolicyLogger.error(e.getMessage()); } } @@ -1031,7 +1031,7 @@ public class PolicyDBDao { String action = "unknown action"; try { - if(policy.isDeleted()){ + if(policy != null && policy.isDeleted()){ logger.debug("Deleting Policy: " + policy.getPolicyName()); action = "delete"; Path newPath = Paths.get(policyPath.toString(), policy.getPolicyName()); @@ -1098,7 +1098,7 @@ public class PolicyDBDao { } } catch (IOException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Error occurred while performing [" + action + "] of Policy File: " + policy.getPolicyName()); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Error occurred while performing [" + action + "] of Policy File: " + policy != null ? policy.getPolicyName() : "null"); } } @@ -1315,11 +1315,12 @@ public class PolicyDBDao { String repo = buildPolicyDirectory(); String policyScope = policy.getScope(); + if(policyScope == null){ policyScope = ""; PolicyLogger.error("buildPolicyScopeDirectory("+policy+") computed null policyScope. Using blank."); } else { - policyScope = policyScope.replace(".", FileSystems.getDefault().getSeparator()); + policyScope = policyScope.replace(".", File.separator); } if(policyScope == null){ policyScope = ""; @@ -1329,7 +1330,7 @@ public class PolicyDBDao { PolicyLogger.error("buildPolicyScopeDirectory("+policy+") received null repo. Using blank."); repo = ""; } - Path returnPath = Paths.get(repo + FileSystems.getDefault().getSeparator() + policyScope); + Path returnPath = Paths.get(repo + File.separator + policyScope); if(returnPath != null){ return returnPath.toString(); } else { @@ -1341,9 +1342,7 @@ public class PolicyDBDao { } private String buildPolicyScopeDirectory(String policyScope){ String repo = buildPolicyDirectory(); - policyScope = policyScope.replace(".", FileSystems.getDefault().getSeparator()); - return repo + FileSystems.getDefault().getSeparator() + policyScope; - + return repo + File.separator + policyScope.replace(".", File.separator); } private static String buildPolicyDirectory(){ @@ -1628,7 +1627,13 @@ public class PolicyDBDao { } catch(Exception e){ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "auditLocalDatabase() error"); logger.error("Exception Occured"+e); - } + }finally{ + try { + Files.walk(webappsPath).close(); + } catch (IOException e) { + logger.error("Exception Occured while closing File Stream"+e); + } + } } /** @@ -1980,7 +1985,7 @@ public class PolicyDBDao { for(int j=i;j= path.length()){ + if(path != null && (gitPath.length() >= path.length())){ logger.debug("gitPath length(): " + gitPath.length() + ">= path.length(): " + path.length() + ". Returning null"); return null; } @@ -2996,6 +3001,13 @@ public class PolicyDBDao { } } } + if(policyXmlStream != null){ + try { + policyXmlStream.close(); + } catch (IOException e) { + logger.error("Exception Occured while closing input stream"+e); + } + } createPolicy(policy.policyAdapter, username, policyScope,finalName,policyDataString); } diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java index 7637719b1..c4f53582b 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java @@ -19,6 +19,7 @@ */ package org.openecomp.policy.pap.xacml.rest.components; +import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -30,6 +31,10 @@ import org.yaml.snakeyaml.constructor.Constructor; public class SafePolicyBuilder { + private SafePolicyBuilder(){ + //Private Constructor. + } + public static ControlLoopGuard loadYamlGuard(String specification) { // // Read the yaml into our Java Object @@ -40,18 +45,29 @@ public class SafePolicyBuilder { return (ControlLoopGuard) obj; } - public static String generateXacmlGuard(String xacmlFileContent,Map generateMap) { - for(String key: generateMap.keySet()){ - Pattern p = Pattern.compile("\\$\\{" +key +"\\}"); + public static String generateXacmlGuard(String xacmlFileContent,Map generateMap, List blacklist) { + for(Map.Entry map: generateMap.entrySet()){ + Pattern p = Pattern.compile("\\$\\{" +map.getKey() +"\\}"); Matcher m = p.matcher(xacmlFileContent); - String finalInput = generateMap.get(key); + String finalInput = map.getValue(); if(finalInput.contains("$")){ finalInput = finalInput.replace("$", "\\$"); } xacmlFileContent=m.replaceAll(finalInput); } + if(blacklist!=null && !blacklist.isEmpty()){ + StringBuilder rule = new StringBuilder(); + for(String blackListName : blacklist){ + if(blackListName.contains("$")){ + blackListName = blackListName.replace("$", "\\$"); + } + rule.append(""+blackListName+""); + } + Pattern p = Pattern.compile("\\$\\{blackListElement\\}"); + Matcher m = p.matcher(xacmlFileContent); + xacmlFileContent=m.replaceAll(rule.toString()); + } PolicyLogger.info("Generated XACML from the YAML Spec: \n" + xacmlFileContent); - return xacmlFileContent; } } diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java index 8d253d385..108d33c25 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java @@ -1010,7 +1010,7 @@ public class MicroServiceDictionaryController { this.newModel.setDependency(""); } - if (mainClass.getDependency()==null){ + if (mainClass != null && mainClass.getDependency()==null){ mainClass.setDependency(""); } diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java index f468b374d..3f86378ab 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java @@ -109,30 +109,6 @@ public class PushPolicyController { } } - /*private void safetyChecker(String policyName) { - if (XACMLProperties.getProperty("xacml.rest.pap.safetychecker").equals("on")) { - if (policyName.contains("Config_MS_") || policyName.contains("BRMS_Param")) { - SafetyCheckerService service = new SafetyCheckerService(); - PolicySafetyChecker safetyChecker = new PolicySafetyChecker(); - boolean isEntered = false; - try { - JSONObject policyDataObj = service.getConfigByPolicyName(policyName, XACMLPapServlet.getConfigHome()); - isEntered = safetyChecker.addItem(policyDataObj); - } catch (Exception e) { - PolicyLogger.warn(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", e, "Error while adding ClosedLoop in the database: " - + "This is a PolicySafetyChecker warning, the push execution may proceed normally."); - } - if (isEntered) { - LOGGER.info("SafetyChecker successfully added the closedLoop to the DB table."); - } else { - LOGGER.info("SafetyChecker failed to add the closedLoop to the DB table."); - } - } - } else { - LOGGER.info("PolicySafetyChecker is turned off."); - } - }*/ - private void addPolicyToGroup(String policyScope, String policyID, String policyName, String pdpGroup, HttpServletResponse response) { StdPDPGroup selectedPDPGroup = null; StdPDPPolicy selectedPolicy = null; diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java index 75bd725f0..4dd48adfd 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java @@ -194,7 +194,7 @@ public class ElkConnectorImpl implements ElkConnector{ LOGGER.trace("ENTER: " + text); } - if (filter_s == null || filter_s.size() <= 0) { + if (filter_s == null || filter_s.size() == 0) { return search(type, text); } diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java index ff454ade9..88548ffa4 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java @@ -308,7 +308,9 @@ public class DeleteHandler { return true; } }finally{ - st.close(); + if(st != null){ + st.close(); + } } } return false; diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java index dde2a0d3b..3437dab03 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java @@ -29,6 +29,7 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.lang.StringUtils; import org.openecomp.policy.common.logging.eelf.PolicyLogger; import org.openecomp.policy.common.logging.flexlogger.FlexLogger; import org.openecomp.policy.common.logging.flexlogger.Logger; @@ -363,13 +364,17 @@ public class PolicyCreation extends AbstractPolicyCreation{ } } } - if(policyData.getRuleProvider()!=null && policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML) && policyData.getYamlparams()!=null){ - attributeMap.put("actor", policyData.getYamlparams().getActor()); + if(policyData.getRuleProvider()!=null && (policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML)|| policyData.getRuleProvider().equals(DecisionPolicy.GUARD_BL_YAML)) + && policyData.getYamlparams()!=null){ attributeMap.put("actor", policyData.getYamlparams().getActor()); attributeMap.put("recipe", policyData.getYamlparams().getRecipe()); attributeMap.put("limit", policyData.getYamlparams().getLimit()); attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow()); attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart()); attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd()); + if(policyData.getYamlparams().getBlackList()!=null){ + String blackList = StringUtils.join(policyData.getYamlparams().getBlackList(), ","); + attributeMap.put("blackList", blackList); + } } policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java index 3ff279d8d..d70332edf 100644 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java +++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java @@ -35,7 +35,7 @@ import javax.servlet.http.HttpServletResponse; import org.openecomp.policy.common.logging.eelf.PolicyLogger; import org.openecomp.policy.pap.xacml.rest.components.CreateBRMSRuleTemplate; -import org.openecomp.policy.pap.xacml.rest.components.CreateNewMicroSerivceModel; +import org.openecomp.policy.pap.xacml.rest.components.CreateNewMicroServiceModel; public class ImportService { @@ -65,7 +65,7 @@ public class ImportService { successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); break; case "MICROSERVICE": - CreateNewMicroSerivceModel newMS = null; + CreateNewMicroServiceModel newMS = null; String randomID = UUID.randomUUID().toString(); if ( fileName != null) { File extracDir = new File("ExtractDir"); @@ -105,7 +105,7 @@ public class ImportService { outputStream.write(buffer, 0, bytesRead) ; } } catch (IOException e) { - PolicyLogger.error("Error in reading in Zip File from API call"); + PolicyLogger.error("Error in reading in Zip File from API call"+e); return; }finally{ try { @@ -120,7 +120,7 @@ public class ImportService { } } } - newMS = new CreateNewMicroSerivceModel(fileName, serviceName, "API", version, randomID); + newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID); successMap = newMS.addValuesToNewModel(); if (successMap.containsKey("success")) { successMap.clear(); diff --git a/packages/base/src/files/install/servers/pap/bin/Decision_GuardPolicyTemplate.xml b/ECOMP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml similarity index 67% rename from packages/base/src/files/install/servers/pap/bin/Decision_GuardPolicyTemplate.xml rename to ECOMP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml index 6701a0848..1e428ff34 100644 --- a/packages/base/src/files/install/servers/pap/bin/Decision_GuardPolicyTemplate.xml +++ b/ECOMP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml @@ -1,5 +1,5 @@ - + ${description} @@ -37,8 +37,8 @@ - - + + @@ -46,12 +46,16 @@ ${guardActiveStart} ${guardActiveEnd} - - - - - - ${limit} + + + + + + + + ${blackListElement} + + @@ -69,27 +73,31 @@ - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - - - - - - ${limit} - - + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + + + + + + + + ${blackListElement} + + + + - + Denied! diff --git a/ECOMP-PAP-REST/Decision_GuardPolicyTemplate.xml b/ECOMP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml similarity index 100% rename from ECOMP-PAP-REST/Decision_GuardPolicyTemplate.xml rename to ECOMP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java index 9d7ebbe6e..924c2b5ff 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java @@ -24,7 +24,6 @@ import java.net.URI; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.Arrays; import java.util.Date; import java.util.NoSuchElementException; import java.util.Properties; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java index b4433036b..0766ac469 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java @@ -559,7 +559,7 @@ public class XACMLPdpLoader { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while retrieving policy " + policy + " from URL " - + url.toString() + ", e=" + e); + + url + ", e=" + e); } } papUrls.getNext(); diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java index fe8c79409..4a705f5c4 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java @@ -490,9 +490,16 @@ public class PAPServices { + connection.getHeaderField("message"); } else if ("addGroupError".equals(connection.getHeaderField("error"))) { response = connection.getHeaderField("message"); + } else if ("validation".equals(connection.getHeaderField("error"))){ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Validation errors during policy engine " + connection.getHeaderField("operation") + + " for " + connection.getHeaderField("service"); } else if ("error".equals(connection.getHeaderField("error"))) { response = XACMLErrorConstants.ERROR_UNKNOWN + "Could not create or update the policy for and unknown reason"; + }else{ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "BAD REQUEST: Error occured while attempting perform this operation.. the request may be incorrect."; } LOGGER.error(response); } else { diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java index 38a0da32e..2a526f751 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java @@ -80,10 +80,10 @@ public class PolicyEngineImportService { } private void specialCheck() { - if(importResponse.contains("BAD REQUEST") || importResponse.contains("PE300")){ - status = HttpStatus.BAD_REQUEST; - }else if(importResponse.contains("PE200")){ + if(importResponse==null || importResponse.contains("PE200")){ status = HttpStatus.INTERNAL_SERVER_ERROR; + }else if(importResponse.contains("BAD REQUEST") || importResponse.contains("PE300")){ + status = HttpStatus.BAD_REQUEST; } } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java index a5d3adb7a..c4573cc0d 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java @@ -51,6 +51,10 @@ public class PDPApiAuth { private static Long oldModified = null; private static AAFPolicyClient aafClient = null; + private PDPApiAuth(){ + // Private Constructor + } + /* * Set Property by reading the properties File. */ @@ -84,7 +88,7 @@ public class PDPApiAuth { String resource) { try{ String[] userNamePass = PolicyUtils.decodeBasicEncoding(clientEncoding); - if(userNamePass==null){ + if(userNamePass==null || userNamePass.length==0){ String usernameAndPassword = null; byte[] decodedBytes = Base64.getDecoder().decode(clientEncoding); usernameAndPassword = new String(decodedBytes, "UTF-8"); diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java index adcce2633..71a99d2fb 100644 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java +++ b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java @@ -20,6 +20,8 @@ package org.openecomp.policy.rest.adapter; +import java.util.List; + public class YAMLParams { private String actor; private String recipe; @@ -27,6 +29,7 @@ public class YAMLParams { private String timeWindow; private String guardActiveStart; private String guardActiveEnd; + private List blackList; public String getActor() { return actor; @@ -64,4 +67,10 @@ public class YAMLParams { public void setGuardActiveEnd(String guardActiveEnd) { this.guardActiveEnd = guardActiveEnd; } + public List getBlackList() { + return blackList; + } + public void setBlackList(List blackList) { + this.blackList = blackList; + } } diff --git a/ECOMP-SDK-APP/xacml.admin.properties b/ECOMP-SDK-APP/xacml.admin.properties index ded60a5b9..b3550dfc1 100644 --- a/ECOMP-SDK-APP/xacml.admin.properties +++ b/ECOMP-SDK-APP/xacml.admin.properties @@ -149,7 +149,7 @@ xacml.rest.pap.password=alpha123 # new Property Please mention your PAP-REST webapps Location here. -xacml.rest.config.webapps=C:\\Second Tomcat\\apache-tomcat-8.0.23\\webapps\\ConfigPAP\\ +xacml.rest.config.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ # pdps file - Needs to have the location of the PDPs File of the PAP-REST xacml.rest.pdp.idfile=test.properties diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java index fdf43264f..639e29e3d 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java @@ -353,6 +353,16 @@ public class PolicyManagerServlet extends HttpServlet { if(scopes.isEmpty()){ return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); } + Set tempScopes = scopes; + for(String scope : tempScopes){ + List scopesList = queryPolicyEditorScopes(scope); + if(!scopesList.isEmpty()){ + for(int i = 0; i < scopesList.size(); i++){ + PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i); + scopes.add(tempScope.getScopeName()); + } + } + } } if(policyList!= null){ for(int i = 0; i < policyList.length(); i++){ @@ -384,9 +394,13 @@ public class PolicyManagerServlet extends HttpServlet { List filterdatas = controller.getData(PolicyVersion.class); for(Object filter : filterdatas){ PolicyVersion filterdata = (PolicyVersion) filter; - String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator)); - if(scopes.contains(scopeName)){ - policyData.add(filterdata); + try{ + String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator)); + if(scopes.contains(scopeName)){ + policyData.add(filterdata); + } + }catch(Exception e){ + LOGGER.error("Exception occured while filtering policyversion data"+e); } } } @@ -567,11 +581,6 @@ public class PolicyManagerServlet extends HttpServlet { } } } - if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { - if(scopes.isEmpty()){ - return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); - } - } List resultList = new ArrayList<>(); boolean onlyFolders = params.getBoolean("onlyFolders"); @@ -580,7 +589,18 @@ public class PolicyManagerServlet extends HttpServlet { path = path.replaceAll("..xml", "").trim(); } - + if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { + if(scopes.isEmpty()){ + return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); + }else{ + if(!"/".equals(path)){ + String tempScope = path.substring(1, path.length()); + tempScope = tempScope.replace("/", File.separator); + scopes.add(tempScope); + } + } + } + if("/".equals(path)){ if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ List scopesList = queryPolicyEditorScopes(null); @@ -601,14 +621,16 @@ public class PolicyManagerServlet extends HttpServlet { for(Object scope : scopes){ JSONObject el = new JSONObject(); List scopesList = queryPolicyEditorScopes(scope.toString()); - PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0); - el.put("name", scopeById.getScopeName()); - el.put("date", scopeById.getCreatedDate()); - el.put("size", ""); - el.put("type", "dir"); - el.put("createdBy", scopeById.getUserCreatedBy().getUserName()); - el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName()); - resultList.add(el); + if(!scopesList.isEmpty()){ + PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0); + el.put("name", scopeById.getScopeName()); + el.put("date", scopeById.getCreatedDate()); + el.put("size", ""); + el.put("type", "dir"); + el.put("createdBy", scopeById.getUserCreatedBy().getUserName()); + el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName()); + resultList.add(el); + } } } }else{ @@ -632,7 +654,7 @@ public class PolicyManagerServlet extends HttpServlet { if(scopeName == null){ scopeNamequery = "from PolicyEditorScopes"; }else{ - scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"'"; + scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'"; } PolicyController controller = getPolicyControllerInstance(); List scopesList = controller.getDataByQuery(scopeNamequery); @@ -945,6 +967,7 @@ public class PolicyManagerServlet extends HttpServlet { } private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{ + FileWriter fw = null; String queryEntityName = null; PolicyController controller = getPolicyControllerInstance(); PolicyEntity cloneEntity = new PolicyEntity(); @@ -967,6 +990,15 @@ public class PolicyManagerServlet extends HttpServlet { controller.saveData(configurationDataEntity); ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName); cloneEntity.setConfigurationData(configEntiy); + String newConfigurationName = configEntiy.getConfigurationName(); + try { + fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName); + BufferedWriter bw = new BufferedWriter(fw); + bw.write(configEntiy.getConfigBody()); + bw.close(); + } catch (IOException e) { + LOGGER.error("Exception Occured While cloning the configuration file"+e); + } }else if(newpolicyName.contains("Action_")){ ActionBodyEntity actionBodyEntity = new ActionBodyEntity(); actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension)); @@ -978,6 +1010,22 @@ public class PolicyManagerServlet extends HttpServlet { controller.saveData(actionBodyEntity); ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName); cloneEntity.setActionBodyEntity(actionEntiy); + String newConfigurationName = actionEntiy.getActionBodyName(); + try { + fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName); + BufferedWriter bw = new BufferedWriter(fw); + bw.write(actionEntiy.getActionBody()); + bw.close(); + } catch (IOException e) { + LOGGER.error("Exception Occured While cloning the configuration file"+e); + } + } + if(fw != null){ + try { + fw.close(); + } catch (IOException e) { + LOGGER.error("Exception Occured While closing the File input stream"+e); + } } cloneEntity.setDeleted(entity.isDeleted()); cloneEntity.setCreatedBy(userId); @@ -1032,46 +1080,21 @@ public class PolicyManagerServlet extends HttpServlet { //Check PolicyEntity table with newPolicy Name String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'"; List queryData = controller.getDataByQuery(policyEntityquery); + if(!queryData.isEmpty()){ + return error("Policy already exists with same name"); + } + + //Query the Policy Entity with oldPolicy Name + policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'"; + queryData = controller.getDataByQuery(policyEntityquery); if(!queryData.isEmpty()){ entity = (PolicyEntity) queryData.get(0); } if(entity != null){ - //if a policy exists with new name check if it is deleted or not - if(entity.isDeleted()){ - //Check Policy Group Entity table if policy has been pushed or not - String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'"; - List object = controller.getDataByQuery(query); - if(object == null){ - //if PolicyGroupEntity data is empty delete the entry from database - controller.deleteData(entity); - //Query the Policy Entity with oldPolicy Name - policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'"; - queryData = controller.getDataByQuery(policyEntityquery); - if(!queryData.isEmpty()){ - entity = (PolicyEntity) queryData.get(0); - } - if(entity != null){ - cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId); - success = true; - } - }else{ - return error("Policy Clone failed due to policy with new name existing in PDP Group."); - } - }else{ - return error("Policy Clone failed due to same name existing."); - } - }else{ - //Query the Policy Entity with oldPolicy Name - policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'"; - queryData = controller.getDataByQuery(policyEntityquery); - if(!queryData.isEmpty()){ - entity = (PolicyEntity) queryData.get(0); - } - if(entity != null){ - cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId); - success = true; - } + cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId); + success = true; } + if(success){ PolicyVersion entityItem = new PolicyVersion(); entityItem.setActiveVersion(Integer.parseInt(version)); @@ -1394,18 +1417,15 @@ public class PolicyManagerServlet extends HttpServlet { } LOGGER.debug("addFolder path: {} name: {}" + path +name); if(!name.equals("")){ + if(name.startsWith(File.separator)){ + name = name.substring(1); + } PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name); if(entity == null){ UserInfo userInfo = new UserInfo(); userInfo.setUserLoginId(userId); PolicyEditorScopes newScope = new PolicyEditorScopes(); - String scopeName = null; - if(name.startsWith(File.separator)){ - scopeName = name.substring(1); - }else{ - scopeName = name; - } - newScope.setScopeName(scopeName); + newScope.setScopeName(name); newScope.setUserCreatedBy(userInfo); newScope.setUserModifiedBy(userInfo); controller.saveData(newScope); diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java index 582dd6c68..2c04bc66d 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java @@ -380,14 +380,21 @@ public class PolicyRestController extends RestrictedBaseController{ public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ Object resultList = null; String uri = request.getRequestURI(); - String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); - if(body.contains("CouldNotConnectException")){ + try{ + String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); + if(body.contains("CouldNotConnectException")){ + List data = new ArrayList<>(); + data.add("Elastic Search Server is down"); + resultList = data; + }else{ + JSONObject json = new JSONObject(body); + resultList = json.get("policyresult"); + } + }catch(Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e); List data = new ArrayList<>(); data.add("Elastic Search Server is down"); resultList = data; - }else{ - JSONObject json = new JSONObject(body); - resultList = json.get("policyresult"); } response.setCharacterEncoding(PolicyController.getCharacterencoding()); diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java index 68dff19bd..8258b8bed 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java @@ -20,7 +20,12 @@ package org.openecomp.policy.controller; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -355,11 +360,25 @@ public class CreateBRMSParamController extends RestrictedBaseController { private void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) { String data = entity.getConfigurationData().getConfigBody(); if(data != null){ + File file = new File(PolicyController.getConfigHome() +File.separator+ entity.getConfigurationData().getConfigurationName()); + if(file.exists()){ + try (BufferedReader br = new BufferedReader(new FileReader(file))) { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + }catch(Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage() + e); + } + } try { StringBuilder params = new StringBuilder(""); Boolean flag = false; Boolean comment = false; - for (String line : data.split("\n")) { + for (String line : Files.readAllLines(Paths.get(file.toString()))) { if (line.isEmpty() || line.startsWith("//")) { continue; } diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java index 2fecd7eea..28278062d 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java @@ -157,6 +157,8 @@ public class DecisionPolicyController extends RestrictedBaseController { break; }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_YAML")){ policyAdapter.setRuleProvider("GUARD_YAML"); + }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_BL_YAML")){ + policyAdapter.setRuleProvider("GUARD_BL_YAML"); } }else{ policyAdapter.setRuleProvider("Custom"); @@ -166,7 +168,7 @@ public class DecisionPolicyController extends RestrictedBaseController { ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue(); ruleAlgoirthmTracker = new LinkedList<>(); - if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals("GUARD_YAML")){ + if(policyAdapter.getRuleProvider()!=null && (policyAdapter.getRuleProvider().equals("GUARD_YAML")||(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")))){ YAMLParams yamlParams = new YAMLParams(); for(int i=0; i map = (Map)attributeList.get(i); @@ -179,9 +181,19 @@ public class DecisionPolicyController extends RestrictedBaseController { ApplyType apply = ((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue()); yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString()); yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString()); - yamlParams.setLimit(((AttributeValueType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(1).getValue()).getContent().get(0).toString()); - String timeWindow = ((AttributeDesignatorType)((ApplyType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer(); - yamlParams.setTimeWindow(timeWindow.substring(timeWindow.lastIndexOf(":")+1)); + if(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")){ + apply = (ApplyType)((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue()).getExpression().get(2).getValue(); + Iterator> attributes = apply.getExpression().iterator(); + List blackList = new ArrayList<>(); + while(attributes.hasNext()){ + blackList.add(((AttributeValueType)attributes.next().getValue()).getContent().get(0).toString()); + } + yamlParams.setBlackList(blackList); + }else{ + yamlParams.setLimit(((AttributeValueType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(1).getValue()).getContent().get(0).toString()); + String timeWindow = ((AttributeDesignatorType)((ApplyType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer(); + yamlParams.setTimeWindow(timeWindow.substring(timeWindow.lastIndexOf(":")+1)); + } policyAdapter.setYamlparams(yamlParams); policyAdapter.setAttributes(new ArrayList()); policyAdapter.setRuleAlgorithmschoices(new ArrayList()); diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java index ff91e9381..bb138d415 100644 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java @@ -30,6 +30,7 @@ import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -89,8 +90,6 @@ public class PolicyValidationController extends RestrictedBaseController { public static final String MICROSERVICES="Micro Service"; private Pattern pattern; private Matcher matcher; - - private static Map rangeMap = new HashMap<>(); private static Map mapAttribute = new HashMap<>(); private static final String EMAIL_PATTERN = @@ -104,7 +103,7 @@ public class PolicyValidationController extends RestrictedBaseController { public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ try{ boolean valid = true; - String responseString = ""; + StringBuilder responseString = new StringBuilder(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); @@ -112,17 +111,17 @@ public class PolicyValidationController extends RestrictedBaseController { if(policyData.getPolicyName() != null){ String policyNameValidate = emptyValidator(policyData.getPolicyName()); if(!policyNameValidate.contains("success")){ - responseString = responseString + "PolicyName:" + policyNameValidate + "
"; + responseString.append("PolicyName:" + policyNameValidate + "
"); valid = false; }; }else{ - responseString = responseString + "PolicyName: PolicyName Should not be empty" + "
"; + responseString.append( "PolicyName: PolicyName Should not be empty" + "
"); valid = false; } if(policyData.getPolicyDescription() != null){ String descriptionValidate = descriptionValidator(policyData.getPolicyDescription()); if(!descriptionValidate.contains("success")){ - responseString = responseString + "Description:" + descriptionValidate + "
"; + responseString.append("Description:" + descriptionValidate + "
"); valid = false; } } @@ -133,11 +132,11 @@ public class PolicyValidationController extends RestrictedBaseController { if(policyData.getEcompName() != null){ String ecompNameValidate = emptyValidator(policyData.getEcompName()); if(!ecompNameValidate.contains("success")){ - responseString = responseString + "EcompName:" + ecompNameValidate + "
"; + responseString.append("EcompName:" + ecompNameValidate + "
"); valid = false; } }else{ - responseString = responseString + "Ecomp Name: Ecomp Name Should not be empty" + "
"; + responseString.append("Ecomp Name: Ecomp Name Should not be empty" + "
"); valid = false; } } @@ -145,33 +144,33 @@ public class PolicyValidationController extends RestrictedBaseController { if(policyData.getRiskType() != null){ String riskTypeValidate = emptyValidator(policyData.getRiskType()); if(!riskTypeValidate.contains("success")){ - responseString = responseString + "RiskType:" + riskTypeValidate + "
"; + responseString.append("RiskType:" + riskTypeValidate + "
"); valid = false; } }else { - responseString = responseString + "Risk Type: Risk Type Should not be Empty" + "
"; + responseString.append("Risk Type: Risk Type Should not be Empty" + "
"); valid = false; } if(policyData.getRiskLevel() != null){ String validateRiskLevel = emptyValidator(policyData.getRiskLevel()); if(!validateRiskLevel.contains("success")){ - responseString = responseString + "RiskLevel:" + validateRiskLevel + "
"; + responseString.append("RiskLevel:" + validateRiskLevel + "
"); valid = false; } }else { - responseString = responseString + "Risk Level: Risk Level Should not be Empty" + "
"; + responseString.append("Risk Level: Risk Level Should not be Empty" + "
"); valid = false; } if(policyData.getGuard() != null){ String validateGuard = emptyValidator(policyData.getGuard()); if(!validateGuard.contains("success")){ - responseString = responseString + "Guard:" + validateGuard + "
"; + responseString.append("Guard:" + validateGuard + "
"); valid = false; } }else { - responseString = responseString + "Guard: Guard Value Should not be Empty" + "
"; + responseString.append("Guard: Guard Value Should not be Empty" + "
"); valid = false; } @@ -179,21 +178,21 @@ public class PolicyValidationController extends RestrictedBaseController { if(policyData.getConfigName() != null){ String configNameValidate = emptyValidator(policyData.getConfigName()); if(!configNameValidate.contains("success")){ - responseString = responseString + "ConfigName:" + configNameValidate + "
"; + responseString.append("ConfigName:" + configNameValidate + "
"); valid = false; } }else{ - responseString = responseString + "Config Name: Config Name Should not be Empty" + "
"; + responseString.append("Config Name: Config Name Should not be Empty" + "
"); valid = false; } if(policyData.getConfigType() != null){ String configTypeValidate = emptyValidator(policyData.getConfigType()); if(!configTypeValidate.contains("success")){ - responseString = responseString + "ConfigType:" + configTypeValidate + "
"; + responseString.append("ConfigType:" + configTypeValidate + "
"); valid = false; } }else{ - responseString = responseString + "Config Type: Config Type Should not be Empty" + "
"; + responseString.append("Config Type: Config Type Should not be Empty" + "
"); valid = false; } if(policyData.getConfigBodyData() != null){ @@ -202,28 +201,28 @@ public class PolicyValidationController extends RestrictedBaseController { if (policyType != null) { if (policyType.equals("JSON")) { if (!isJSONValid(configBodyData)) { - responseString = responseString + "Config Body: JSON Content is not valid" + "
"; + responseString.append("Config Body: JSON Content is not valid" + "
"); valid = false; } } else if (policyType.equals("XML")) { if (!isXMLValid(configBodyData)) { - responseString = responseString + "Config Body: XML Content data is not valid" + "
"; + responseString.append("Config Body: XML Content data is not valid" + "
"); valid = false; } } else if (policyType.equals("PROPERTIES")) { if (!isPropValid(configBodyData)||configBodyData.equals("")) { - responseString = responseString + "Config Body: Property data is not valid" + "
"; + responseString.append("Config Body: Property data is not valid" + "
"); valid = false; } } else if (policyType.equals("OTHER")) { if (configBodyData.equals("")) { - responseString = responseString + "Config Body: Config Body Should not be Empty" + "
"; + responseString.append("Config Body: Config Body Should not be Empty" + "
"); valid = false; } } } }else{ - responseString = responseString + "Config Body: Config Body Should not be Empty" + "
"; + responseString.append("Config Body: Config Body Should not be Empty" + "
"); valid = false; } } @@ -232,21 +231,21 @@ public class PolicyValidationController extends RestrictedBaseController { if(policyData.getConfigName() != null){ String configNameValidate = PolicyUtils.emptyPolicyValidator(policyData.getConfigName()); if(!configNameValidate.contains("success")){ - responseString = responseString + "ConfigName:" + configNameValidate + "
"; + responseString.append("ConfigName:" + configNameValidate + "
"); valid = false; } }else{ - responseString = responseString + "Config Name: Config Name is required" + "
"; + responseString.append("Config Name: Config Name is required" + "
"); valid = false; } if(policyData.getSecurityZone() == null){ - responseString = responseString + "Security Zone: Security Zone is required" + "
"; + responseString.append("Security Zone: Security Zone is required" + "
"); valid = false; } } if(policyData.getConfigPolicyType().equals("BRMS_Param")){ if(policyData.getRuleName() == null){ - responseString = responseString + "BRMS Template:BRMS Template is required
"; + responseString.append("BRMS Template:BRMS Template is required
"); valid = false; } } @@ -255,38 +254,38 @@ public class PolicyValidationController extends RestrictedBaseController { String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData()); // If there are any error other than Annotations then this is not Valid if(message.contains("[ERR")){ - responseString = responseString + "Raw Rule Validate:Raw Rule has error"+ message +"
"; + responseString.append("Raw Rule Validate:Raw Rule has error"+ message +"
"); valid = false; } }else{ - responseString = responseString + "Raw Rule:Raw Rule is required
"; + responseString.append("Raw Rule:Raw Rule is required
"); valid = false; } } if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){ try{ if(root.get("policyData").get("verticaMetrics").get("serviceTypePolicyName") == null && policyData.getServiceTypePolicyName().isEmpty()){ - responseString = responseString + "ServiceType PolicyName:ServiceType PolicyName is required
"; + responseString.append("ServiceType PolicyName:ServiceType PolicyName is required
"); valid = false; } }catch(Exception e){ - responseString = responseString + "ServiceType PolicyName:ServiceType PolicyName is required
"; + responseString.append("ServiceType PolicyName:ServiceType PolicyName is required
"); valid = false; } if(root.get("policyData").get("jsonBodyData") != null){ ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class); if(pmBody.getEmailAddress() != null){ - String result = emailValidation(pmBody.getEmailAddress(), responseString); + String result = emailValidation(pmBody.getEmailAddress(), responseString.toString()); if(result != "success"){ - responseString = result + "
"; + responseString.append(result + "
"); valid = false; } } if(pmBody.getGeoLink() != null){ String result = PolicyUtils.emptyPolicyValidator(pmBody.getGeoLink()); if(!result.contains("success")){ - responseString = responseString + "GeoLink:" + result + "
"; + responseString.append("GeoLink:" + result + "
"); valid = false; }; } @@ -297,14 +296,14 @@ public class PolicyValidationController extends RestrictedBaseController { if(!key.contains("Message")){ String attributeValidate = PolicyUtils.emptyPolicyValidator(value); if(!attributeValidate.contains("success")){ - responseString = responseString + "Attributes:" + key + " : value has spaces
"; + responseString.append("Attributes:" + key + " : value has spaces
"); valid = false; }; } } } }else{ - responseString = responseString + "D2/Virtualized Services:Select atleast one D2/Virtualized Services
"; + responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
"); valid = false; } } @@ -312,73 +311,69 @@ public class PolicyValidationController extends RestrictedBaseController { if(root.get("policyData").get("jsonBodyData") != null){ ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); if(faultBody.getEmailAddress() != null){ - String result = emailValidation(faultBody.getEmailAddress(), responseString); + String result = emailValidation(faultBody.getEmailAddress(), responseString.toString()); if(result != "success"){ - responseString = result+ "
"; + responseString.append(result+ "
"); valid = false; } } if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){ - responseString = responseString + "D2/Virtualized Services:Select atleast one D2/Virtualized Services
"; + responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
"); valid = false; } if(faultBody.getActions() == null){ - responseString = responseString + "vPRO Actions:vPRO Actions is required
"; - valid = false; - } - if(faultBody.getAgingWindow() == 0){ - responseString = responseString + "Aging Window:Aging Window is required
"; + responseString.append("vPRO Actions:vPRO Actions is required
"); valid = false; } if(faultBody.getClosedLoopPolicyStatus() == null){ - responseString = responseString + "Policy Status:Policy Status is required
"; + responseString.append("Policy Status:Policy Status is required
"); valid = false; } if(faultBody.getConditions() == null){ - responseString = responseString + "Conditions:Select Atleast one Condition
"; + responseString.append("Conditions:Select Atleast one Condition
"); valid = false; } if(faultBody.getGeoLink() != null){ - String result = PolicyUtils.emptyPolicyValidator(faultBody.getGeoLink()); + String result = PolicyUtils.emptyPolicyValidatorWithSpaceAllowed(faultBody.getGeoLink()); if(!result.contains("success")){ - responseString = responseString + "GeoLink:" + result + "
"; + responseString.append("GeoLink:" + result + "
"); valid = false; }; } if(faultBody.getTimeInterval() == 0){ - responseString = responseString + "Time Interval:Time Interval is required
"; + responseString.append("Time Interval:Time Interval is required
"); valid = false; } if(faultBody.getRetrys() == 0){ - responseString = responseString + "Number of Retries:Number of Retries is required
"; + responseString.append("Number of Retries:Number of Retries is required
"); valid = false; } if(faultBody.getTimeOutvPRO() == 0){ - responseString = responseString + "APP-C Timeout:APP-C Timeout is required
"; + responseString.append("APP-C Timeout:APP-C Timeout is required
"); valid = false; } if(faultBody.getTimeOutRuby() == 0){ - responseString = responseString + "TimeOutRuby:TimeOutRuby is required
"; + responseString.append("TimeOutRuby:TimeOutRuby is required
"); valid = false; } if(faultBody.getVnfType() == null){ - responseString = responseString + "Vnf Type:Vnf Type is required
"; + responseString.append("Vnf Type:Vnf Type is required
"); valid = false; } }else{ - responseString = responseString + "D2/Virtualized Services:Select atleast one D2/Virtualized Services
"; - responseString = responseString + "vPRO Actions:vPRO Actions is required
"; - responseString = responseString + "Aging Window:Aging Window is required
"; - responseString = responseString + "Policy Status:Policy Status is required
"; - responseString = responseString + "Conditions:Select Atleast one Condition
"; - responseString = responseString + "PEP Name:PEP Name is required
"; - responseString = responseString + "PEP Action:PEP Action is required
"; - responseString = responseString + "Time Interval:Time Interval is required
"; - responseString = responseString + "Number of Retries:Number of Retries is required
"; - responseString = responseString + "APP-C Timeout:APP-C Timeout is required
"; - responseString = responseString + "TimeOutRuby:TimeOutRuby is required
"; - responseString = responseString + "Vnf Type:Vnf Type is required
"; + responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
"); + responseString.append("vPRO Actions:vPRO Actions is required
"); + responseString.append("Aging Window:Aging Window is required
"); + responseString.append("Policy Status:Policy Status is required
"); + responseString.append("Conditions:Select Atleast one Condition
"); + responseString.append("PEP Name:PEP Name is required
"); + responseString.append("PEP Action:PEP Action is required
"); + responseString.append("Time Interval:Time Interval is required
"); + responseString.append("Number of Retries:Number of Retries is required
"); + responseString.append("APP-C Timeout:APP-C Timeout is required
"); + responseString.append("TimeOutRuby:TimeOutRuby is required
"); + responseString.append("Vnf Type:Vnf Type is required
"); valid = false; } } @@ -399,7 +394,7 @@ public class PolicyValidationController extends RestrictedBaseController { returnModel = getAttributeObject(service, version); String annoation = returnModel.getAnnotation(); if (!Strings.isNullOrEmpty(annoation)){ - rangeMap = new HashMap(); + Map rangeMap = new HashMap<>(); rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annoation); for (Entry rMap : rangeMap.entrySet()){ if (rMap.getValue().contains("range::")){ @@ -409,16 +404,16 @@ public class PolicyValidationController extends RestrictedBaseController { int endNum = Integer.parseInt(tempString[1]); String returnString = "Invalid Range:" + rMap.getKey() + " must be between " + startNum + " - " + endNum + ","; - if (isType(value.replace("\"", ""))){ + if (isInteger(value.replace("\"", ""))){ int result = Integer.parseInt(value.replace("\"", "")); if (result < startNum || result > endNum){ - responseString = responseString + returnString; + responseString.append(returnString); valid = false; } }else { - responseString = responseString + returnString; + responseString.append(returnString); valid = false; } } @@ -426,17 +421,17 @@ public class PolicyValidationController extends RestrictedBaseController { } //for continue testing for Dkat, just blocked this validation until fixing it. gw1218 on 3/30/17 //if (!checkAttributeValues()){ - //responseString = responseString + "Micro Service: Attribute Values Missing" + "
"; + //responseString.append("Micro Service: Attribute Values Missing" + "
"); //valid = false; //} }else{ - responseString = responseString + "Micro Service: Micro Service is required" + "
"; + responseString.append("Micro Service: Micro Service is required" + "
"); valid = false; } if(policyData.getPriority() == null){ - responseString = responseString + "Priority: Priority is required" + "
"; + responseString.append("Priority: Priority is required" + "
"); valid = false; } } @@ -445,49 +440,60 @@ public class PolicyValidationController extends RestrictedBaseController { if(policyData.getEcompName() != null){ String ecompNameValidate = emptyValidator(policyData.getEcompName()); if(!ecompNameValidate.contains("success")){ - responseString = responseString + "EcompName:" + ecompNameValidate + "
"; + responseString.append("EcompName:" + ecompNameValidate + "
"); valid = false; } }else{ - responseString = responseString + "Ecomp Name: Ecomp Name Should not be empty" + "
"; + responseString.append("Ecomp Name: Ecomp Name Should not be empty" + "
"); valid = false; } - if(policyData.getRuleProvider().equals("GUARD_YAML")){ + if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){ if(policyData.getYamlparams()==null){ - responseString = responseString + " Guard Params are Required " + "
"; + responseString.append(" Guard Params are Required " + "
"); valid = false; }else{ if(policyData.getYamlparams().getActor()==null){ - responseString = responseString + "Guard Params Actor is Required " + "
"; + responseString.append("Guard Params Actor is Required " + "
"); valid = false; } if(policyData.getYamlparams().getRecipe()==null){ - responseString = responseString + "Guard Params Recipe is Required " + "
"; - valid = false; - } - if(policyData.getYamlparams().getLimit()==null){ - responseString = responseString + " Guard Params Limit is Required " + "
"; - valid = false; - }else{ - try{ - Integer.parseInt(policyData.getYamlparams().getLimit()); - }catch(NumberFormatException e){ - responseString = responseString + " Guard Params Limit Should be Integer " + "
"; - valid = false; - } - } - if(policyData.getYamlparams().getTimeWindow()==null){ - responseString = responseString + "Guard Params Time Window is Required" + "
"; + responseString.append("Guard Params Recipe is Required " + "
"); valid = false; } if(policyData.getYamlparams().getGuardActiveStart()==null){ - responseString = responseString + "Guard Params Guard Active Start/b>is Required " + "
"; + responseString.append("Guard Params Guard Active Start/b>is Required " + "
"); valid = false; } if(policyData.getYamlparams().getGuardActiveEnd()==null){ - responseString = responseString + "Guard Params Guard Active Endis Required " + "
"; + responseString.append("Guard Params Guard Active Endis Required " + "
"); valid = false; } + if("GUARD_YAML".equals(policyData.getRuleProvider())){ + if(policyData.getYamlparams().getLimit()==null){ + responseString.append(" Guard Params Limit is Required " + "
"); + valid = false; + }else if(!isInteger(policyData.getYamlparams().getLimit())){ + responseString.append(" Guard Params Limit Should be Integer " + "
"); + valid = false; + } + if(policyData.getYamlparams().getTimeWindow()==null){ + responseString.append("Guard Params Time Window is Required" + "
"); + valid = false; + } + }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){ + if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){ + responseString.append(" Guard Params BlackList is Required " + "
"); + valid = false; + }else{ + for(String blackList: policyData.getYamlparams().getBlackList()){ + if(blackList==null || !("success".equals(emptyValidator(blackList)))){ + responseString.append(" Guard Params BlackList Should be valid String" + "
"); + valid = false; + break; + } + } + } + } } } } @@ -496,49 +502,99 @@ public class PolicyValidationController extends RestrictedBaseController { if(policyData.getActionPerformer() != null){ String actionPerformer = emptyValidator(policyData.getActionPerformer()); if(!actionPerformer.contains("success")){ - responseString = responseString + "ActionPerformer:" + actionPerformer + "
"; + responseString.append("ActionPerformer:" + actionPerformer + "
"); valid = false; }; }else{ - responseString = responseString + "ActionPerformer: ActionPerformer Should not be empty" + "
"; + responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "
"); + valid = false; + } + if(policyData.getAttributes() != null){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + try{ + //This is for validation check if the value exists or not + String key = ((LinkedHashMap) attribute).get("key").toString(); + String value = ((LinkedHashMap) attribute).get("value").toString(); + if("".equals(key) || "".equals(value)){ + responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
"); + valid = false; + break; + } + }catch(Exception e){ + LOGGER.error("This is a Policy Validation check" +e); + responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
"); + valid = false; + break; + } + } + } + }else{ + responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
"); valid = false; } if(policyData.getActionAttributeValue() != null){ String actionAttribute = emptyValidator(policyData.getActionAttributeValue()); if(!actionAttribute.contains("success")){ - responseString = responseString + "ActionAttribute:" + actionAttribute + "
"; + responseString.append("ActionAttribute:" + actionAttribute + "
"); valid = false; }; }else{ - responseString = responseString + "ActionAttribute: ActionAttribute Should not be empty" + "
"; + responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "
"); valid = false; } } + + if(policyData.getPolicyType().equals(ACTION_POLICY) || policyData.getPolicyType().equals(DECISION_POLICY)){ + if(!policyData.getRuleAlgorithmschoices().isEmpty()){ + for(Object attribute : policyData.getRuleAlgorithmschoices()){ + if(attribute instanceof LinkedHashMap){ + try{ + String label = ((LinkedHashMap) attribute).get("id").toString(); + String key = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField1").toString(); + String rule = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmCombo").toString(); + String value = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2").toString(); + if("".equals(label) || "".equals(key) || "".equals(rule) || "".equals(value)){ + responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "
"); + valid = false; + } + }catch(Exception e){ + LOGGER.error("This is a Policy Validation check" +e); + responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "
"); + valid = false; + break; + } + } + } + } + } if(policyData.getPolicyType().equals(CONFIG_POLICY)){ + String value = ""; if(valid){ List spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType()); if (!spData.isEmpty()){ SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0); safePolicyWarningData.getMessage(); - responseString = responseString + "Messaage:" + safePolicyWarningData.getMessage(); + value = "Messaage:" + safePolicyWarningData.getMessage(); } - responseString = "success" + "@#"+ responseString; + responseString.append("success" + "@#"+ value); } }else{ if(valid){ - responseString = "success"; + responseString.append("success"); } } PrintWriter out = response.getWriter(); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString())); JSONObject j = new JSONObject(msg); out.write(j.toString()); return null; } catch (Exception e){ + LOGGER.error("Exception Occured while Policy Validation" +e); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); @@ -547,9 +603,18 @@ public class PolicyValidationController extends RestrictedBaseController { return null; } + protected boolean isInteger(String number) { + try{ + Integer.parseInt(number); + }catch(NumberFormatException e){ + return false; + } + return true; + } + protected String emptyValidator(String field){ - String error = "success"; - if (field.equals("") || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) { + String error; + if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) { error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; return error; } else { @@ -564,7 +629,7 @@ public class PolicyValidationController extends RestrictedBaseController { } protected String descriptionValidator(String field) { - String error = "success"; + String error; if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) { error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:"; return error; @@ -590,16 +655,16 @@ public class PolicyValidationController extends RestrictedBaseController { return error; } - protected String emailValidation(String email, String responseString){ + protected String emailValidation(String email, String response){ if(email != null){ String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", "")); if(!validateEmail.contains("success")){ - responseString = responseString + "Email:" + validateEmail+ "
"; + response += "Email:" + validateEmail+ "
"; }else{ return "success"; } } - return responseString; + return response; } private MicroServiceModels getAttributeObject(String name, String version) { @@ -631,35 +696,16 @@ public class PolicyValidationController extends RestrictedBaseController { } } - private Boolean isType(String testStr) { - try { - Integer.parseInt(testStr); - return true; - } catch(Exception e) { - return false; - } - } - // Validation for json. protected static boolean isJSONValid(String data) { - InputStream stream = null; - JsonReader jsonReader = null; try { new JSONObject(data); - stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); - jsonReader = Json.createReader(stream); + InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + JsonReader jsonReader = Json.createReader(stream); + System.out.println("Json Value is: " + jsonReader.read().toString() ); } catch (Exception e) { - LOGGER.error("Exception Occured"+e); + e.printStackTrace(); return false; - }finally{ - try { - if(stream != null && jsonReader != null){ - jsonReader.close(); - stream.close(); - } - } catch (IOException e) { - LOGGER.error("Exception Occured while closing the input stream"+e); - } } return true; } @@ -689,7 +735,7 @@ public class PolicyValidationController extends RestrictedBaseController { Scanner scanner = new Scanner(prop); while (scanner.hasNextLine()) { String line = scanner.nextLine(); - line.replaceAll("\\s+", ""); + line = line.replaceAll("\\s+", ""); if (line.startsWith("#")) { continue; } else { @@ -709,4 +755,4 @@ public class PolicyValidationController extends RestrictedBaseController { return true; } -} +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PDPTabWindows/AddorEditPDPtoGroup.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PDPTabWindows/AddorEditPDPtoGroup.html index 19e11bfeb..3bfb50fd7 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PDPTabWindows/AddorEditPDPtoGroup.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PDPTabWindows/AddorEditPDPtoGroup.html @@ -19,7 +19,7 @@ */-->