diff options
Diffstat (limited to 'ECOMP-PDP-REST/src')
36 files changed, 3751 insertions, 205 deletions
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpServlet.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpServlet.java index a247fe65c..12dfbd23b 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpServlet.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpServlet.java @@ -270,13 +270,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { // CreateUpdatePolicy ResourceName createUpdateResourceName = properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE); - try{ - Class<?> createUpdateclass = Class.forName(createUpdateResourceName); - createUpdatePolicyConstructor = createUpdateclass.getConstructor(PolicyParameters.class, String.class, boolean.class); - }catch(Exception e){ - PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, "createUpdatePolicy.impl.className", "xacml.pdp.init"); - throw new ServletException("Could not find the Class name : " +createUpdateResourceName + "\n" +e.getMessage()); - } + setCreateUpdatePolicyConstructor(createUpdateResourceName); // Create an IntegrityMonitor try { @@ -1159,4 +1153,14 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { public static Constructor<?> getCreateUpdatePolicyConstructor(){ return createUpdatePolicyConstructor; } + + private static void setCreateUpdatePolicyConstructor(String createUpdateResourceName) throws ServletException{ + try{ + Class<?> createUpdateclass = Class.forName(createUpdateResourceName); + createUpdatePolicyConstructor = createUpdateclass.getConstructor(PolicyParameters.class, String.class, boolean.class); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, "createUpdatePolicy.impl.className", "xacml.pdp.init"); + throw new ServletException("Could not find the Class name : " +createUpdateResourceName + "\n" +e.getMessage()); + } + } } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java index a9d80fdc2..48539ad83 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java @@ -58,6 +58,8 @@ import org.openecomp.policy.pdp.rest.api.services.GetDecisionService; import org.openecomp.policy.pdp.rest.api.services.GetDictionaryService; import org.openecomp.policy.pdp.rest.api.services.GetMetricsService; import org.openecomp.policy.pdp.rest.api.services.ListConfigService; +import org.openecomp.policy.pdp.rest.api.services.NotificationService; +import org.openecomp.policy.pdp.rest.api.services.NotificationService.NotificationServiceType; import org.openecomp.policy.pdp.rest.api.services.PolicyEngineImportService; import org.openecomp.policy.pdp.rest.api.services.PushPolicyService; import org.openecomp.policy.pdp.rest.api.services.SendEventService; @@ -81,8 +83,9 @@ import springfox.documentation.annotations.ApiIgnore; @Api(value = "Policy Engine Services") @RequestMapping("/") public class PolicyEngineServices { - private static Logger logger = FlexLogger - .getLogger(PolicyEngineServices.class.getName()); + private static Logger logger = FlexLogger.getLogger(PolicyEngineServices.class.getName()); + private static final String NOTIFICATIONPERM = "notification"; + private final AtomicLong configCounter = new AtomicLong(); private final AtomicLong configNameCounter = new AtomicLong(); private final AtomicLong eventCounter = new AtomicLong(); @@ -97,6 +100,7 @@ public class PolicyEngineServices { private final AtomicLong policyEngineImportCounter = new AtomicLong(); private final AtomicLong deprecatedCounter = new AtomicLong(); private final AtomicLong metricCounter = new AtomicLong(); + private final AtomicLong notificationCounter = new AtomicLong(); @ApiImplicitParams({ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @@ -118,7 +122,7 @@ public class PolicyEngineServices { status = getConfigService.getResponseCode(); } configCounter.incrementAndGet(); - return new ResponseEntity<Collection<PolicyConfig>>(policyConfig, status); + return new ResponseEntity<>(policyConfig, status); } @ApiImplicitParams({ @@ -135,8 +139,7 @@ public class PolicyEngineServices { Collection<PolicyConfig> policyConfig = null; HttpStatus status = HttpStatus.UNAUTHORIZED; // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "getConfigByPolicyName")) { + if (PDPApiAuth.checkPermissions(clientEncoding, requestID,"getConfigByPolicyName")) { ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); configRequestParameters.setPolicyName(configNameRequest .getPolicyName()); @@ -194,6 +197,71 @@ public class PolicyEngineServices { metricCounter.incrementAndGet(); return new ResponseEntity<>(response, status); } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Registers DMaaP Topic to recieve notification from Policy Engine") + @RequestMapping(value = "/getNotification", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity<String> getNotification( + @RequestBody String notificationTopic, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String policyResponse = "Error Unauthorized to use Notification Service."; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, NOTIFICATIONPERM)) { + NotificationService notificationService = new NotificationService(notificationTopic, requestID, NotificationServiceType.ADD); + policyResponse = notificationService.getResult(); + status = notificationService.getResponseCode(); + } + notificationCounter.incrementAndGet(); + return new ResponseEntity<>(policyResponse, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "De-Registers DMaaP Topic to stop recieving notifications from Policy Engine") + @RequestMapping(value = "/stopNotification", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity<String> stopNotification( + @RequestBody String notificationTopic, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String policyResponse = "Error Unauthorized to use Notification Service."; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, NOTIFICATIONPERM)) { + NotificationService notificationService = new NotificationService(notificationTopic, requestID, NotificationServiceType.REMOVE); + policyResponse = notificationService.getResult(); + status = notificationService.getResponseCode(); + } + notificationCounter.incrementAndGet(); + return new ResponseEntity<>(policyResponse, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Sends Heartbeat to DMaaP Topic Registry to continue recieving notifications from Policy Engine") + @RequestMapping(value = "/sendHeartbeat", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity<String> sendHeartbeat( + @RequestBody String notificationTopic, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String policyResponse = "Error Unauthorized to use Heartbeat Service."; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, NOTIFICATIONPERM)) { + NotificationService notificationService = new NotificationService(notificationTopic, requestID, NotificationServiceType.HB); + policyResponse = notificationService.getResult(); + status = notificationService.getResponseCode(); + } + return new ResponseEntity<>(policyResponse, status); + } @ApiImplicitParams({ @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), @@ -314,7 +382,7 @@ public class PolicyEngineServices { status = createPolicyService.getResponseCode(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - logger.error(e.getMessage()); + logger.error(e.getMessage(), e); response = "Problem with CreateUpdate Policy Service. "; status = HttpStatus.INTERNAL_SERVER_ERROR; } @@ -346,7 +414,7 @@ public class PolicyEngineServices { status = updatePolicyService.getResponseCode(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - logger.error(e.getMessage()); + logger.error(e.getMessage(), e); response = "Problem with CreateUpdate Policy Service. "; status = HttpStatus.INTERNAL_SERVER_ERROR; } @@ -571,7 +639,8 @@ public class PolicyEngineServices { + "\nTotal PolicyEngine Import Calls: " + policyEngineImportCounter + "\nTotal Deprecated Policy Calls: " + deprecatedCounter - + "\nTotal Metrics Calls:" + metricCounter; + + "\nTotal Metrics Calls:" + metricCounter + + "\nTotal Notification Calls:" + notificationCounter; } @ExceptionHandler({ HttpMessageNotReadableException.class }) diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java index 14c536605..7640cad0e 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java @@ -35,8 +35,8 @@ import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; * @version 0.1 */ public class ActionPolicyService { - private static Logger LOGGER = FlexLogger.getLogger(ActionPolicyService.class.getName()); - private static PAPServices papServices = null; + private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyService.class.getName()); + private PAPServices papServices = null; private PolicyParameters policyParameters = null; private String message = null; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java index 971f2fd35..37d07660d 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java @@ -36,15 +36,14 @@ import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; * @version 0.1 */ public class BRMSParamPolicyService{ - private static Logger LOGGER = FlexLogger.getLogger(BRMSParamPolicyService.class.getName()); - private static PAPServices papServices = null; + private static final Logger LOGGER = FlexLogger.getLogger(BRMSParamPolicyService.class.getName()); + private PAPServices papServices = null; private PolicyParameters policyParameters = null; private String message = null; private String policyName = null; private String policyScope = null; - private String date = null; - private boolean levelCheck = false; + private String date = null; private Map<AttributeType, Map<String, String>> drlRuleAndUIParams = null; public BRMSParamPolicyService(String policyName, String policyScope, @@ -57,7 +56,7 @@ public class BRMSParamPolicyService{ } public Boolean getValidation() { - levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); if(!levelCheck){ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; return false; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java index a85533be8..b2ff00ed5 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java @@ -36,8 +36,8 @@ import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; * @version 0.1 */ public class ClosedLoopFaultPolicyService{ - private static Logger LOGGER = FlexLogger.getLogger(ClosedLoopFaultPolicyService.class.getName()); - private static PAPServices papServices = null; + private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopFaultPolicyService.class.getName()); + private PAPServices papServices = null; private PolicyParameters policyParameters = null; private String message = null; @@ -68,6 +68,7 @@ public class ClosedLoopFaultPolicyService{ configBody = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); } catch(JsonException| IllegalStateException e){ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + LOGGER.error("Json Parse Exception.", e); return false; } return true; @@ -89,20 +90,25 @@ public class ClosedLoopFaultPolicyService{ } else { operation = "create"; } - boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); // get values and attributes from the JsonObject - String ecompName = configBody.get("ecompname").toString().replace("\"", ""); - String jsonBody = configBody.toString(); - if (ecompName==null||ecompName.equals("")){ + if(!configBody.containsKey("ecompname")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; + LOGGER.error(message); + return message; + } + String ecompName = configBody.get("ecompname").toString().trim().replace("\"", ""); + if (ecompName==null||ecompName.trim().isEmpty()){ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; LOGGER.error(message); return message; } + boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); if (!levelCheck){ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; LOGGER.error(message); return message; } + String jsonBody = configBody.toString(); // Create Policy. StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_Fault", policyName, policyParameters.getPolicyDescription(), ecompName, jsonBody, false, oldPolicyName, null, updateFlag, policyScope, 0, policyParameters.getRiskLevel(), diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java index 15a2c3abc..3fb8f461c 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java @@ -36,9 +36,9 @@ import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; * @version 0.1 */ public class ClosedLoopPMPolicyService{ - private static Logger LOGGER = FlexLogger.getLogger(ClosedLoopPMPolicyService.class.getName()); - private static PAPServices papServices = null; + private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPMPolicyService.class.getName()); + private PAPServices papServices = null; private PolicyParameters policyParameters = null; private String message = null; private String policyName = null; @@ -68,6 +68,7 @@ public class ClosedLoopPMPolicyService{ configBody = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); } catch(JsonException| IllegalStateException e){ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + LOGGER.error("Error during parsing JSON config body for Closed loop PM policy " , e); return false; } return true; @@ -85,21 +86,31 @@ public class ClosedLoopPMPolicyService{ } else { operation = "create"; } - boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); // get values and attributes from the JsonObject - String ecompName = configBody.get("ecompname").toString().replace("\"", ""); - String serviceType = configBody.get("serviceTypePolicyName").toString().replace("\"", ""); - String jsonBody = configBody.toString(); - if (ecompName==null||ecompName.equals("")){ + if(!configBody.containsKey("ecompname")){ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; LOGGER.error(message); return message; } + if(!configBody.containsKey("serviceTypePolicyName")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Service Type Policy Name given."; + LOGGER.error(message); + return message; + } + String ecompName = configBody.get("ecompname").toString().trim().replace("\"", ""); + if (ecompName==null||ecompName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; + LOGGER.error(message); + return message; + } + boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); if (!levelCheck){ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; LOGGER.error(message); return message; } + String jsonBody = configBody.toString(); + String serviceType = configBody.get("serviceTypePolicyName").toString().replace("\"", ""); // Create Policy. StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_PM", policyName, policyParameters.getPolicyDescription(), ecompName, jsonBody, false, null, serviceType, updateFlag, policyScope, 0, policyParameters.getRiskLevel(), diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java index 8edd1ac61..3401d55b9 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java @@ -37,15 +37,14 @@ import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; * @version 0.1 */ public class ConfigPolicyService { - private static Logger LOGGER = FlexLogger.getLogger(ConfigPolicyService.class.getName()); - private static PAPServices papServices = null; + private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicyService.class.getName()); + private PAPServices papServices = null; private PolicyParameters policyParameters = null; private String message = null; private String policyName = null; private String policyScope = null; private String date = null; - private boolean levelCheck = false; private String ecompName = null; private String configName = null; @@ -67,6 +66,7 @@ public class ConfigPolicyService { message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body Type given."; return false; } + boolean levelCheck = false; levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); if (!levelCheck){ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; @@ -111,7 +111,7 @@ public class ConfigPolicyService { String body = policyParameters.getConfigBody(); String configBody = null; //check body for JSON form and remove single quotes if present - if (configType.equalsIgnoreCase("JSON")) { + if ("JSON".equalsIgnoreCase(configType)) { if (body.contains("'")) { configBody = body.replace("'", "\""); } else { diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java index 850115f22..6dde8a276 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java @@ -37,7 +37,7 @@ import org.openecomp.policy.xacml.api.XACMLErrorConstants; import org.springframework.http.HttpStatus; public class CreateUpdateConfigPolicyService { - private static Logger LOGGER = FlexLogger.getLogger(CreateUpdateConfigPolicyService.class.getName()); + private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdateConfigPolicyService.class.getName()); private String response = null; private HttpStatus status = HttpStatus.BAD_REQUEST; @@ -75,16 +75,32 @@ public class CreateUpdateConfigPolicyService { Map<AttributeType, Map<String, String>> attributes = new HashMap<>(); attributes.put(AttributeType.MATCHING, configPolicyAPIRequest.getConfigAttributes()); policyParameters.setAttributes(attributes); - policyParameters.setConfigBodyType(PolicyType.valueOf(configPolicyAPIRequest.getConfigType())); + if(configPolicyAPIRequest.getConfigType()==null){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy ConfigType given."; + LOGGER.error(message); + throw new PolicyException(message); + } + try{ + policyParameters.setConfigBodyType(PolicyType.valueOf(configPolicyAPIRequest.getConfigType())); + }catch(IllegalArgumentException e){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Improper ConfigType given."; + LOGGER.error(message, e); + throw new PolicyException(message); + } policyParameters.setConfigBody(configPolicyAPIRequest.getBody()); policyParameters.setRiskLevel(configPolicyAPIRequest.getRiskLevel()); policyParameters.setRiskType(configPolicyAPIRequest.getRiskType()); policyParameters.setGuard(Boolean.parseBoolean(configPolicyAPIRequest.getGuard())); - try { - policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(configPolicyAPIRequest.getTtlDate())); - } catch (ParseException e) { - LOGGER.warn("Error Parsing date given " + configPolicyAPIRequest.getTtlDate()); + if(configPolicyAPIRequest.getTtlDate()==null){ + LOGGER.warn("No TTL date given "); policyParameters.setTtlDate(null); + }else{ + try { + policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(configPolicyAPIRequest.getTtlDate())); + } catch (ParseException e) { + LOGGER.warn("Error Parsing date given " + configPolicyAPIRequest.getTtlDate(), e); + policyParameters.setTtlDate(null); + } } CreateUpdatePolicyService createUpdatePolicyService = new CreateUpdatePolicyServiceImpl(policyParameters, requestID, updateFlag); status = createUpdatePolicyService.getResponseCode(); diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java index 1c3049da3..3c102fa68 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java @@ -34,7 +34,7 @@ import org.openecomp.policy.xacml.api.XACMLErrorConstants; import org.springframework.http.HttpStatus; public class CreateUpdateDictionaryService { - private static Logger LOGGER = FlexLogger.getLogger(CreateUpdateDictionaryService.class.getName()); + private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdateDictionaryService.class.getName()); private String dictionaryResult = null; private HttpStatus status = HttpStatus.BAD_REQUEST; @@ -54,7 +54,7 @@ public class CreateUpdateDictionaryService { requestUUID = UUID.fromString(requestID); } catch (IllegalArgumentException e) { requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(),e); } }else{ requestUUID = UUID.randomUUID(); @@ -110,13 +110,12 @@ public class CreateUpdateDictionaryService { json = PolicyApiUtils.stringToJsonObject(dictionaryParameters.getDictionaryJson()); } catch(JsonException| IllegalStateException e){ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper Dictionary JSON object : " + dictionaryParameters.getDictionaryJson(); - LOGGER.error(message); + LOGGER.error(message, e); return message; } String dictionaryFields = json.toString(); PAPServices papServices = new PAPServices(); - String result = (String) papServices.callPAP(new ByteArrayInputStream(dictionaryFields.getBytes()), new String[] {"operation="+operation, "apiflag=api", "dictionaryType="+dictionaryParameters.getDictionary()}, dictionaryParameters.getRequestID(), "dictionaryItem"); - return result; + return (String) papServices.callPAP(new ByteArrayInputStream(dictionaryFields.getBytes()), new String[] {"operation="+operation, "apiflag=api", "dictionaryType="+dictionaryParameters.getDictionary()}, dictionaryParameters.getRequestID(), "dictionaryItem"); } private boolean getValidation() { @@ -136,11 +135,9 @@ public class CreateUpdateDictionaryService { message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary JSON given."; return false; } - if (updateFlag && dictionaryParameters.getDictionary().equalsIgnoreCase("MicroServiceDictionary")){ - if (!dictionaryParameters.getDictionaryJson().contains("initialFields")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Mising the required field initialFields."; - return false; - } + if (updateFlag && "MicroServiceDictionary".equalsIgnoreCase(dictionaryParameters.getDictionary())&& !dictionaryParameters.getDictionaryJson().contains("initialFields")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Mising the required field initialFields."; + return false; } return true; } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java index b547f8dfe..3e5dce15b 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java @@ -33,7 +33,7 @@ import org.openecomp.policy.xacml.api.XACMLErrorConstants; import org.springframework.http.HttpStatus; public class CreateUpdateFirewallPolicyService { - private static Logger LOGGER = FlexLogger.getLogger(CreateUpdateFirewallPolicyService.class.getName()); + private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdateFirewallPolicyService.class.getName()); private String response = null; private HttpStatus status = HttpStatus.BAD_REQUEST; @@ -73,7 +73,7 @@ public class CreateUpdateFirewallPolicyService { try { policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(configFirewallPolicyAPIRequest.getTtlDate())); } catch (NullPointerException | ParseException e) { - LOGGER.warn("Error Parsing date given " + configFirewallPolicyAPIRequest.getTtlDate()); + LOGGER.warn("Error Parsing date given " + configFirewallPolicyAPIRequest.getTtlDate(), e); policyParameters.setTtlDate(null); } CreateUpdatePolicyService createUpdatePolicyService = new CreateUpdatePolicyServiceImpl(policyParameters, requestID, updateFlag); diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java index 4032a8a7f..6112c42ce 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java @@ -33,7 +33,7 @@ import org.openecomp.policy.xacml.api.XACMLErrorConstants; import org.springframework.http.HttpStatus; public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService { - private static Logger LOGGER = FlexLogger.getLogger(CreateUpdatePolicyService.class.getName()); + private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdatePolicyServiceImpl.class.getName()); private String policyResult = null; private HttpStatus status = HttpStatus.BAD_REQUEST; @@ -55,7 +55,7 @@ public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService requestUUID = UUID.fromString(requestID); } catch (IllegalArgumentException e) { requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); } }else{ requestUUID = UUID.randomUUID(); @@ -233,7 +233,6 @@ public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService if (policyName==null||policyName.trim().isEmpty()){ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; return false; - } message = PolicyUtils.emptyPolicyValidator(policyScope); if(!message.contains("success")){ diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java index d0978fc5b..3b1ea23fb 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java @@ -31,7 +31,7 @@ import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; import org.springframework.http.HttpStatus; public class DeletePolicyService { - private static Logger LOGGER = FlexLogger.getLogger(DeletePolicyService.class.getName()); + private static final Logger LOGGER = FlexLogger.getLogger(DeletePolicyService.class.getName()); private String deleteResult = null; private HttpStatus status = HttpStatus.BAD_REQUEST; @@ -53,7 +53,7 @@ public class DeletePolicyService { requestUUID = UUID.fromString(requestID); } catch (IllegalArgumentException e) { requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); } }else{ requestUUID = UUID.randomUUID(); @@ -74,7 +74,7 @@ public class DeletePolicyService { if(deleteResult==null){ return; } - if (deleteResult.contains("BAD REQUEST")||deleteResult.contains("PE300")||deleteResult.contains("not exist")||deleteResult.contains("Invalid policyName")) { + if (deleteResult.contains("BAD REQUEST")||deleteResult.contains("PE300")||deleteResult.contains("PE200")||deleteResult.contains("not exist")||deleteResult.contains("Invalid policyName")) { status = HttpStatus.BAD_REQUEST; } else if (deleteResult.contains("locked down")){ status = HttpStatus.ACCEPTED; @@ -174,6 +174,10 @@ public class DeletePolicyService { private boolean getValidation() { // While Validating, extract the required values. + if (deletePolicyParameters.getPolicyName()==null||deletePolicyParameters.getPolicyName().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + return false; + } if (!deletePolicyParameters.getPolicyName().contains("xml")) { if (deletePolicyParameters.getPolicyName() != null && deletePolicyParameters.getPolicyName().contains(".")) { @@ -188,10 +192,6 @@ public class DeletePolicyService { } else { policyName = deletePolicyParameters.getPolicyName(); } - if (deletePolicyParameters.getPolicyName()==null||deletePolicyParameters.getPolicyName().trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - return false; - } policyType = deletePolicyParameters.getPolicyType(); if(policyType== null || policyType.trim().isEmpty()){ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given."; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java index 1d4305a3b..f301bf05d 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java @@ -36,15 +36,14 @@ import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; * @version 0.1 */ public class FirewallPolicyService { - private static Logger LOGGER = FlexLogger.getLogger(FirewallPolicyService.class.getName()); - private static PAPServices papServices = null; + private static final Logger LOGGER = FlexLogger.getLogger(FirewallPolicyService.class.getName()); + private PAPServices papServices = null; private PolicyParameters policyParameters = null; private String message = null; private String policyName = null; private String policyScope = null; private String date = null; - private boolean levelCheck = false; private JsonObject firewallJson = null; public FirewallPolicyService(String policyName, String policyScope, @@ -65,12 +64,14 @@ public class FirewallPolicyService { firewallJson = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); } catch(JsonException| IllegalStateException e){ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + LOGGER.error("Error while parsing JSON body for creating Firewall Policy " , e); return false; } - if(firewallJson==null){ + if(firewallJson==null|| firewallJson.isEmpty()){ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config-Body given."; return false; } + boolean levelCheck = false; levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); if (!levelCheck){ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; @@ -92,6 +93,11 @@ public class FirewallPolicyService { operation = "create"; } //set values for basic policy information + if(!firewallJson.containsKey("configName")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No configName given in firwall JSON."; + LOGGER.error(message); + return message; + } String configName = firewallJson.get("configName").toString(); String configDescription = ""; String json = firewallJson.toString(); diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java index b501a5c6a..2363877b2 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java @@ -20,6 +20,7 @@ package org.openecomp.policy.pdp.rest.api.services; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -43,7 +44,7 @@ import org.openecomp.policy.xacml.api.XACMLErrorConstants; import org.springframework.http.HttpStatus; public class GetConfigService { - private static Logger LOGGER = FlexLogger.getLogger(GetConfigService.class.getName()); + private static final Logger LOGGER = FlexLogger.getLogger(GetConfigService.class.getName()); private ConfigRequestParameters configRequestParameters = null; private String message = null; @@ -61,7 +62,7 @@ public class GetConfigService { requestUUID = UUID.fromString(requestID); } catch (IllegalArgumentException e) { requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(),e); } }else{ requestUUID = UUID.randomUUID(); @@ -69,11 +70,12 @@ public class GetConfigService { } this.configRequestParameters.setRequestID(requestUUID); } - policyConfigs = new ArrayList<PolicyConfig>(); + policyConfigs = new ArrayList<>(); try{ run(); specialCheck(); }catch(PolicyConfigException e){ + LOGGER.error(e); PolicyConfig policyConfig = new PolicyConfig(); policyConfig.setPolicyConfigMessage(e.getMessage()); policyConfig.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); @@ -83,7 +85,7 @@ public class GetConfigService { } private void specialCheck() { - if(policyConfigs==null || policyConfigs.size()==0){ + if(policyConfigs==null || policyConfigs.isEmpty()){ responseCode = HttpStatus.BAD_REQUEST; }else if(policyConfigs.size()==1){ for(PolicyConfig policyConfig: policyConfigs){ @@ -125,7 +127,7 @@ public class GetConfigService { private Collection<PolicyConfig> configResult( Collection<PDPResponse> generateRequest) { - Collection<PolicyConfig> result = new HashSet<PolicyConfig>(); + Collection<PolicyConfig> result = new HashSet<>(); if (generateRequest == null) { return null; } @@ -151,7 +153,7 @@ public class GetConfigService { private Collection<PolicyConfig> filterResults( Collection<PolicyConfig> policyConfigs, ConfigRequestParameters configRequestParameters) { - List<PolicyConfig> policyConfig = new ArrayList<PolicyConfig>(); + List<PolicyConfig> policyConfig = new ArrayList<>(); for(PolicyConfig config: policyConfigs){ if(config.getPolicyName()!=null && configRequestParameters.getPolicyName()!=null && configRequestParameters.getPolicyName().trim().length()>0){ if(!config.getPolicyName().matches(configRequestParameters.getPolicyName())){ @@ -172,9 +174,23 @@ public class GetConfigService { if(configRequestParameters.getConfigAttributes()!=null && configRequestParameters.getConfigAttributes().size()>0){ boolean flag = false; for(String key: configRequestParameters.getConfigAttributes().keySet()){ - if(!config.getMatchingConditions().containsKey(key) || !config.getMatchingConditions().get(key).matches(configRequestParameters.getConfigAttributes().get(key))){ - flag = true; - break; + if(key.equals("RiskType")||key.equals("RiskLevel")||key.equals("guard")||key.equals("TTLDate")){ + continue; + } + if(config.getMatchingConditions().containsKey(key)){ + if(config.getMatchingConditions().get(key).contains(",")){ + List<String> elements = Arrays.asList(config.getMatchingConditions().get(key).split(",")); + if(!elements.contains(configRequestParameters.getConfigAttributes().get(key))){ + flag=true; + } + }else if(!config.getMatchingConditions().get(key).matches(configRequestParameters.getConfigAttributes().get(key))){ + flag = true; + } + }else{ + flag = true; + } + if(flag){ + break; } } if(flag){ @@ -184,7 +200,7 @@ public class GetConfigService { } policyConfig.add(config); } - if(policyConfig.size()==0){ + if(policyConfig.isEmpty()){ PolicyConfig pConfig = new PolicyConfig(); pConfig.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); pConfig.setPolicyConfigMessage(XACMLErrorConstants.ERROR_DATA_ISSUE+"No Match Found, for the parameters sent."); @@ -226,7 +242,7 @@ public class GetConfigService { }else{ LOGGER.info("Ecomp Name is not given. "); } - JsonObject model = Json.createObjectBuilder() + return Json.createObjectBuilder() .add("Request",Json.createObjectBuilder() .add("AccessSubject",Json.createObjectBuilder() .add("Attribute",subjectArray)) @@ -240,7 +256,6 @@ public class GetConfigService { .add("Value","Config") .add("AttributeId","urn:oasis:names:tc:xacml:1.0:resource:resource-id"))))) .build(); - return model; } private JsonArrayBuilder getResourceArray(Map<String, String> configAttributes) throws PolicyConfigException{ @@ -261,7 +276,7 @@ public class GetConfigService { } }else{ // ConfigAttributes is Null. So add basic values. - configAttributes = new HashMap<String,String>(); + configAttributes = new HashMap<>(); configAttributes.put("RiskType", ".*"); configAttributes.put("RiskLevel", ".*"); configAttributes.put("guard", ".*"); diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java index f70c3fb97..1ef5e53cf 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java @@ -21,6 +21,7 @@ package org.openecomp.policy.pdp.rest.api.services; import java.util.Collection; import java.util.Map; +import java.util.Map.Entry; import java.util.UUID; import javax.json.Json; @@ -40,7 +41,7 @@ import org.openecomp.policy.xacml.api.XACMLErrorConstants; import org.springframework.http.HttpStatus; public class GetDecisionService { - private static Logger LOGGER = FlexLogger.getLogger(GetDecisionService.class.getName()); + private static final Logger LOGGER = FlexLogger.getLogger(GetDecisionService.class.getName()); private DecisionResponse decisionResponse = null; private HttpStatus status = HttpStatus.BAD_REQUEST; @@ -60,7 +61,7 @@ public class GetDecisionService { requestUUID = UUID.fromString(requestID); } catch (IllegalArgumentException e) { requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(),e); } }else{ requestUUID = UUID.randomUUID(); @@ -117,24 +118,33 @@ public class GetDecisionService { private JsonObject getModel() throws PolicyDecisionException{ JsonArrayBuilder resourceArray = Json.createArrayBuilder(); - for (String key : decisionAttributes.keySet()) { - if (key.isEmpty()) { + for (Entry<String,String> key : decisionAttributes.entrySet()) { + if (key.getKey().isEmpty()) { String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; LOGGER.error(message); throw new PolicyDecisionException(message); } JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); - if (decisionAttributes.get(key).matches("[0-9]+")) { - int val = Integer.parseInt(decisionAttributes.get(key)); - resourceBuilder.add("Value", val); + if (key.getValue().matches("[0-9]+")) { + + if ((key.getKey().equals("ErrorCode")) || (key.getKey().equals("WorkStep"))) { + + resourceBuilder.add("Value", key.getValue()); + + } else { + + int val = Integer.parseInt(key.getValue()); + resourceBuilder.add("Value", val); + + } + } else { - resourceBuilder.add("Value", decisionAttributes.get(key)); + resourceBuilder.add("Value", key.getValue()); } - resourceBuilder.add("AttributeId", key); + resourceBuilder.add("AttributeId", key.getKey()); resourceArray.add(resourceBuilder); } - JsonObject model = Json - .createObjectBuilder() + return Json.createObjectBuilder() .add("Request", Json.createObjectBuilder() .add("AccessSubject", Json.createObjectBuilder() .add("Attribute", Json.createObjectBuilder() @@ -147,7 +157,6 @@ public class GetDecisionService { .add("Value", "DECIDE") .add("AttributeId", "urn:oasis:names:tc:xacml:1.0:action:action-id")))) .build(); - return model; } private boolean getValidation() { diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java index 2305ecbec..04567e2e1 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java @@ -35,7 +35,7 @@ import org.openecomp.policy.xacml.api.XACMLErrorConstants; import org.springframework.http.HttpStatus; public class GetDictionaryService { - private static Logger LOGGER = FlexLogger.getLogger(GetDictionaryService.class.getName()); + private static final Logger LOGGER = FlexLogger.getLogger(GetDictionaryService.class.getName()); private DictionaryResponse dictionaryResponse = null; private HttpStatus status = HttpStatus.BAD_REQUEST; @@ -52,7 +52,7 @@ public class GetDictionaryService { requestUUID = UUID.fromString(requestID); } catch (IllegalArgumentException e) { requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); } }else{ requestUUID = UUID.randomUUID(); @@ -72,10 +72,8 @@ public class GetDictionaryService { } private void specialCheck() { - if(dictionaryResponse!=null){ - if(dictionaryResponse.getResponseMessage()!=null && dictionaryResponse.getResponseMessage().contains("PE300")){ - status = HttpStatus.BAD_REQUEST; - } + if(dictionaryResponse!=null && (dictionaryResponse.getResponseMessage()!=null && dictionaryResponse.getResponseMessage().contains("PE300"))){ + status = HttpStatus.BAD_REQUEST; } } @@ -115,7 +113,7 @@ public class GetDictionaryService { json = PolicyApiUtils.stringToJsonObject(datas); } catch(JsonException| IllegalStateException e){ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper Dictionary JSON object : " + dictionaryParameters.getDictionaryJson(); - LOGGER.error(message); + LOGGER.error(message, e); response.setResponseMessage(message); response.setResponseCode(400); return response; @@ -126,6 +124,11 @@ public class GetDictionaryService { } else { response.setResponseCode(400); response.setResponseMessage(result); + if(result!=null && result.contains("PE200")){ + status=HttpStatus.INTERNAL_SERVER_ERROR; + }else{ + status=HttpStatus.BAD_REQUEST; + } } return response; } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java index dc431b0d5..5a90bfac9 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java @@ -34,12 +34,11 @@ import org.openecomp.policy.xacml.api.XACMLErrorConstants; import org.springframework.http.HttpStatus; public class GetMetricsService { - private static Logger LOGGER = FlexLogger - .getLogger(GetDictionaryService.class.getName()); + private static final Logger LOGGER = FlexLogger + .getLogger(GetMetricsService.class.getName()); private MetricsResponse response = null; private HttpStatus status = HttpStatus.BAD_REQUEST; - private String message = null; private MetricsRequestParameters metricsParameters = null; public GetMetricsService(String requestID) { @@ -49,7 +48,7 @@ public class GetMetricsService { requestUUID = UUID.fromString(requestID); } catch (IllegalArgumentException e) { requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); } } else { requestUUID = UUID.randomUUID(); @@ -72,11 +71,9 @@ public class GetMetricsService { } private void specialCheck() { - if (response != null) { - if (response.getResponseMessage() != null - && response.getResponseMessage().contains("PE300")) { + if (response != null && (response.getResponseMessage() != null + && response.getResponseMessage().contains("PE300"))) { status = HttpStatus.BAD_REQUEST; - } } } @@ -100,11 +97,12 @@ public class GetMetricsService { metricsParameters.getRequestID(), "metrics"); JSONObject json = null; + String message = null; if (result != null) { if (result.length() > 81 && result.contains("{")) { try { String responseMessage = result.substring(0, 82); - String jsonString = result.substring(result.indexOf("{"), + String jsonString = result.substring(result.indexOf('{'), result.length()); json = new JSONObject(jsonString); diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java index 636b7fbf8..3188292d7 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java @@ -36,9 +36,9 @@ import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; * @version 0.1 */ public class MicroServicesPolicyService{ - private static Logger LOGGER = FlexLogger.getLogger(MicroServicesPolicyService.class.getName()); - private static PAPServices papServices = null; + private static final Logger LOGGER = FlexLogger.getLogger(MicroServicesPolicyService.class.getName()); + private PAPServices papServices = null; private PolicyParameters policyParameters = null; private String message = null; private String policyName = null; @@ -46,7 +46,6 @@ public class MicroServicesPolicyService{ private String date = null; private String ecompName = null; private JsonObject microServiceAttributes = null; - private boolean levelCheck = false; public MicroServicesPolicyService(String policyName, String policyScope, PolicyParameters policyParameters, String date) { this.policyParameters = policyParameters; @@ -65,6 +64,7 @@ public class MicroServicesPolicyService{ microServiceAttributes = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); } catch(JsonException| IllegalStateException e){ message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + LOGGER.error("Error while parsing JSON body for MicroService Policy creation. ", e); return false; } ecompName = policyParameters.getEcompName(); @@ -72,6 +72,7 @@ public class MicroServicesPolicyService{ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; return false; } + boolean levelCheck = false; levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); if (!levelCheck){ message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; @@ -96,7 +97,13 @@ public class MicroServicesPolicyService{ String uuid = null; String msLocation = null; String configName = null; - String microService = microServiceAttributes.get("service").toString().replace("\"", ""); + String microService = null; + String policyDescription=null; + String priority=null; + String version=null; + if (microServiceAttributes.get("service")!=null){ + microService = microServiceAttributes.get("service").toString().replace("\"", ""); + } if (microServiceAttributes.get("uuid")!=null){ uuid = microServiceAttributes.get("uuid").toString().replace("\"", ""); } @@ -106,10 +113,15 @@ public class MicroServicesPolicyService{ if (microServiceAttributes.get("configName")!=null){ configName = microServiceAttributes.get("configName").toString().replace("\"", ""); } - String policyDescription = microServiceAttributes.get("description").toString().replace("\"", ""); - String priority = microServiceAttributes.get("priority").toString().replace("\"", ""); - String version = microServiceAttributes.get("version").toString().replace("\"", ""); - + if(microServiceAttributes.containsKey("description")){ + policyDescription = microServiceAttributes.get("description").toString().replace("\"", ""); + } + if(microServiceAttributes.containsKey("priority")){ + priority = microServiceAttributes.get("priority").toString().replace("\"", ""); + } + if(microServiceAttributes.containsKey("version")){ + version = microServiceAttributes.get("version").toString().replace("\"", ""); + } // Create Policy. StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Micro Service", policyName, policyDescription, ecompName, configName, microService, uuid, msLocation, microServiceAttributes.toString(), priority, diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/NotificationService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/NotificationService.java new file mode 100644 index 000000000..4b453fa87 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/NotificationService.java @@ -0,0 +1,314 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.utils.BusPublisher; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +import com.att.research.xacml.util.XACMLProperties; + +public class NotificationService { + public static final String BACKUPFILE = "topicBackup.txt"; + private static Logger logger = FlexLogger.getLogger(GetDictionaryService.class.getName()); + private static ConcurrentHashMap<String, Date> topicQueue = new ConcurrentHashMap<>(); + private static int interval = 15000; + private static Thread backUpthread = null; + private static Object resourceLock = new Object(); + private static List<String> dmaapList = null; + private static String dmaapServers = null; + private static String aafLogin = null; + private static String aafPassword = null; + + private String notificationResponse = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + + /** + * NotificationService Constructor. + * + * @param notificationTopic Topic Name in String format. + * @param requestID Request ID in String format. + * @param serviceType Needs to be NotificationServiceType based enumeration value. + */ + public NotificationService(String notificationTopic, String requestID, NotificationServiceType serviceType) { + init(); + if(dmaapServers==null || aafLogin==null || aafPassword==null){ + notificationResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file"; + return; + } + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + logger.info("Generated Random UUID: " + requestUUID.toString(), e); + } + }else{ + requestUUID = UUID.randomUUID(); + logger.info("Generated Random UUID: " + requestUUID.toString()); + } + try{ + run(notificationTopic, serviceType); + }catch(PolicyException e){ + notificationResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private static void init() { + if(dmaapServers==null || aafLogin==null || aafPassword==null){ + dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); + aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN"); + aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD"); + interval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY, Integer.toString(interval))); + if(dmaapServers==null || aafLogin==null || aafPassword==null){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + return; + } + // Cleanup Values. + dmaapServers= dmaapServers.trim(); + aafLogin = aafLogin.trim(); + aafPassword = aafPassword.trim(); + // Get servers to List. + if(dmaapServers.contains(",")) { + dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*"))); + } else { + dmaapList = new ArrayList<>(); + dmaapList.add(dmaapServers); + } + callThread(); + } + } + + private void run(String notificationTopic, NotificationServiceType serviceType) throws PolicyException{ + // Check Validation + if(notificationTopic==null){ + String message = "Notification Topic is null"; + logger.error(message); + throw new PolicyException(message); + } + notificationTopic = notificationTopic.trim(); + if(notificationTopic.isEmpty()){ + String message = "Notification Topic is not valid. "; + logger.error(message); + throw new PolicyException(message); + } + // if already exists give error.Saying already registered. + // Get Result. + try{ + status = HttpStatus.OK; + switch (serviceType) { + case ADD: + addTopic(notificationTopic); + notificationResponse = "Success!! Please give permissions to " + aafLogin + " that PDP will use to publish on given topic :" + notificationTopic + + "\n Start calling /sendHeartbeat API at an interval less than " + Integer.toString(interval) + "ms"; + break; + case REMOVE: + removeTopic(notificationTopic); + notificationResponse = "Notification Topic :" + notificationTopic + " has been removed and PDP will not publish notifications to this Topic."; + break; + case HB: + heartBeat(notificationTopic); + notificationResponse = "Success!! HeartBeat registered."; + break; + } + }catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + // Used to register Heart beat. + private void heartBeat(String notificationTopic) throws PolicyException{ + if(!topicQueue.isEmpty()&& topicQueue.containsKey(notificationTopic)){ + topicQueue.put(notificationTopic, new Date()); + }else{ + logger.info("Failed HeartBeat, Topic " + notificationTopic + "is not registered."); + throw new PolicyException("Failed HeartBeat, Topic " + notificationTopic + "is not registered."); + } + } + + // Used to remove Topic. + private static void removeTopic(String notificationTopic) throws PolicyException{ + if(topicQueue.containsKey(notificationTopic)){ + topicQueue.remove(notificationTopic); + removeTopicFromBackup(notificationTopic); + }else{ + logger.info("Failed Removal, Topic " + notificationTopic + " is not registered."); + throw new PolicyException("Failed Removal, Topic " + notificationTopic + " is not registered."); + } + } + + private static void removeTopicFromBackup(String notificationTopic) { + synchronized (resourceLock) { + try (Stream<String> lines = Files.lines(Paths.get(BACKUPFILE))) { + List<String> replaced = lines.map(line-> (line.split("=")[0].equals(notificationTopic)?"":line)).collect(Collectors.toList()); + try (PrintWriter pw = new PrintWriter( BACKUPFILE, "UTF-8")) { + replaced.forEach(line-> { + if(line.trim().isEmpty()){ + return; + } + pw.println(line); + }); + } + lines.close(); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + " Could not remove/recreate the backup. ", e); + } + } + } + + // Used to add Topic. + private void addTopic(String notificationTopic) throws PolicyException{ + // validate if topic exists. + if(!topicQueue.isEmpty()&& topicQueue.containsKey(notificationTopic)){ + topicQueue.put(notificationTopic, new Date()); + logger.info("Topic " + notificationTopic + " is already registered."); + throw new PolicyException("Topic " + notificationTopic + " is already registered."); + } + topicQueue.put(notificationTopic, new Date()); + addTopictoBackUp(notificationTopic); + } + + private void addTopictoBackUp(String notificationTopic) { + synchronized (resourceLock) { + try { + Files.write(Paths.get(BACKUPFILE),( notificationTopic+"="+new Date().toString()+"\n").getBytes() , StandardOpenOption.APPEND); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + " Could not add to the backup. ", e); + } + } + } + + // Maintains BackUp and Queue Topic. + private static void callThread() { + // Create the backup file if it not exists. + backup(); + if(backUpthread==null){ + Runnable task = () -> { + logger.info("BackUpThread not set. Starting now !"); + threadTask(); + }; + backUpthread = new Thread(task); + backUpthread.start(); + } + } + + private static void backup(){ + synchronized (resourceLock) { + try{ + File backUpFile = new File(BACKUPFILE); + if(!backUpFile.exists() && backUpFile.createNewFile()){ + logger.info(" BackUp File for topic's has been created !"); + }else{ + // File Already exists. Process file and load the Memory. + Stream<String> stream = Files.lines(Paths.get(BACKUPFILE)); + Map<String,Date> data = stream.map(line -> line.split(",")).collect(Collectors.toMap(e->e[0],e-> new Date())); + stream.close(); + data.forEach((key, value)->logger.debug("Topic retrieved from backUp : " + key + " with Time : " + value)); + topicQueue.putAll(data); + } + }catch(IOException e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + " Could not process the backup. ", e); + } + } + } + + private static void threadTask() { + while(true){ + try { + TimeUnit.MILLISECONDS.sleep(interval); + for(Map.Entry<String, Date> map : topicQueue.entrySet()){ + Date currentTime = new Date(); + long timeDiff = 0; + timeDiff = currentTime.getTime()-map.getValue().getTime(); + if(timeDiff < (interval+1500)){ + removeTopic(map.getKey()); + } + } + } catch (InterruptedException | PolicyException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error during thread execution ", e); + } + } + } + + public String getResult() { + return notificationResponse; + } + + public HttpStatus getResponseCode() { + return status; + } + + /** + * Entry point for sending Notifications from Notification Server. + * @param notification String JSON format of notification message which needs to be sent. + */ + public static void sendNotification(String notification) { + init(); + for (String topic: topicQueue.keySet()){ + sendDmaapMessage(topic, notification); + } + } + + private static void sendDmaapMessage(String topic, String notification) { + BusPublisher publisher = new BusPublisher.DmaapPublisherWrapper(dmaapList, + topic, + aafLogin, + aafPassword); + // Sending notification through DMaaP Message Router + publisher.send( "MyPartitionKey", notification); + logger.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + topic); + publisher.close(); + } + + /** + * Notification service Type Enumeration + */ + public enum NotificationServiceType{ + ADD, + REMOVE, + HB + } + +}
\ No newline at end of file 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 4a705f5c4..66a557056 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 @@ -459,6 +459,11 @@ public class PAPServices { + "Group Policy Scope List Exist Error: The Group Policy Scope List for this Dictionary Item already exist in the database. " + "Duplicate Group Policy Scope Lists for multiple groupNames is not allowed. " + "Please review the request and verify that the groupPolicyScopeListData1 is unique compared to existing groups."; + } else if("PolicyInPDP".equals(connection.getHeaderField("error"))){ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Policy Exist Error: The Policy trying to be deleted is active in PDP. " + + "Active PDP Polcies are not allowed to be deleted from PAP. " + + "Please First remove the policy from PDP in order to successfully delete the Policy from PAP."; } LOGGER.error(response); } else if (connection.getResponseCode() == 500 && connection.getHeaderField("error") != null) { @@ -499,7 +504,7 @@ public class PAPServices { + "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."; + + "BAD REQUEST: Error occured while attempting perform this operation.. the request may be incorrect. " + connection.getHeaderField("error"); } LOGGER.error(response); } else { diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java index a25c322a0..fb7b8e270 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java @@ -70,12 +70,12 @@ import com.att.research.xacml.std.json.JSONResponse; import com.att.research.xacml.util.XACMLProperties; public class PDPServices { - private static Logger LOGGER = FlexLogger.getLogger(PDPServices.class.getName()); + private static final Logger LOGGER = FlexLogger.getLogger(PDPServices.class.getName()); // Change the default Priority value here. private static final int DEFAULT_PRIORITY = 9999; private boolean unique = false; private Boolean decide = false; - private Matches match = null; + private Request rainydayRequest = null; public Collection<PDPResponse> generateRequest(String jsonString, UUID requestID, boolean unique, boolean decide) throws PolicyException{ this.unique = unique; @@ -85,13 +85,17 @@ public class PDPServices { // Create Request. We need XACML API here. try { Request request = JSONRequest.load(jsonString); + // Assign a rainy day treatment request to parse the decided treatment + if (jsonString.contains("BB_ID")) { + rainydayRequest = request; + } // Call the PDP - LOGGER.debug("--- Generating Request: ---\n" + JSONRequest.toString(request)); + LOGGER.info("--- Generating Request: ---\n" + JSONRequest.toString(request)); response = callPDP(request, requestID); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e); PDPResponse pdpResponse = new PDPResponse(); - results = new HashSet<PDPResponse>(); + results = new HashSet<>(); pdpResponse.setPolicyConfigMessage("Unable to Call PDP. Error with the URL"); pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED); @@ -101,9 +105,9 @@ public class PDPServices { if (response != null) { results = checkResponse(response); } else { - LOGGER.debug("No Response Received from PDP"); + LOGGER.info("No Response Received from PDP"); PDPResponse pdpResponse = new PDPResponse(); - results = new HashSet<PDPResponse>(); + results = new HashSet<>(); pdpResponse.setPolicyConfigMessage("No Response Received"); pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED); @@ -119,10 +123,19 @@ public class PDPServices { Map<Integer, PDPResponse> uniqueResult = new HashMap<>(); for (Result result : response.getResults()) { if (!result.getDecision().equals(Decision.PERMIT)) { - LOGGER.debug("Decision not a Permit. " + result.getDecision().toString()); + LOGGER.info("Decision not a Permit. " + result.getDecision().toString()); PDPResponse pdpResponse = new PDPResponse(); if (decide) { - pdpResponse.setDecision(PolicyDecision.DENY); + String indeterminatePropValue = XACMLProperties.getProperty("decision.inStringdeterminate.response"); + if(result.getDecision().equals(Decision.INDETERMINATE)&& indeterminatePropValue != null){ + if("PERMIT".equalsIgnoreCase(indeterminatePropValue)){ + pdpResponse.setDecision(PolicyDecision.PERMIT); + }else{ + pdpResponse.setDecision(PolicyDecision.DENY); + } + }else{ + pdpResponse.setDecision(PolicyDecision.DENY); + } for(Advice advice: result.getAssociatedAdvice()){ for(AttributeAssignment attribute: advice.getAttributeAssignments()){ pdpResponse.setDetails(attribute.getAttributeValue().getValue().toString()); @@ -140,7 +153,13 @@ public class PDPServices { // check for Decision for decision based calls. PDPResponse pdpResponse = new PDPResponse(); pdpResponse.setDecision(PolicyDecision.PERMIT); - pdpResponse.setDetails("Decision Permit. OK!"); + + //if this is a Rainy Day treatment decision we need to get the selected treatment + if(rainydayRequest!=null){ + pdpResponse.setDetails(getRainyDayTreatment(result)); + } else { + pdpResponse.setDetails("Decision Permit. OK!"); + } combinedResult.add(pdpResponse); return combinedResult; } @@ -152,7 +171,7 @@ public class PDPServices { String configURL = null; String policyName = null; String policyVersion = null; - match = new Matches(); + Matches match = new Matches(); Map<String, String> matchingConditions = new HashMap<>(); Map<String, String> configAttributes = new HashMap<>(); Map<String, String> responseAttributes = new HashMap<>(); @@ -161,7 +180,7 @@ public class PDPServices { Map<String, String> adviseAttributes = new HashMap<>(); for (AttributeAssignment attribute : advice.getAttributeAssignments()) { adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); - if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("CONFIGURATION")) { + if ("CONFIGURATION".equalsIgnoreCase(attribute.getAttributeValue().getValue().toString())) { config++; } else if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) { uri++; @@ -169,29 +188,29 @@ public class PDPServices { configURL = attribute.getAttributeValue().getValue().toString(); pdpConfigLocation = configURL.replace("$URL", XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)); } else { - if (!(attribute.getIssuer().equalsIgnoreCase("PDP"))) { + if (!("PDP".equalsIgnoreCase(attribute.getIssuer()))) { throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error having multiple URI in the Policy"); } } - } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("PolicyName")) { + } else if ("PolicyName".equalsIgnoreCase(attribute.getAttributeId().stringValue())) { policyName = attribute.getAttributeValue().getValue().toString(); - } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("VersionNumber")) { + } else if ("VersionNumber".equalsIgnoreCase(attribute.getAttributeId().stringValue())) { policyVersion = attribute.getAttributeValue().getValue().toString(); - } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("Priority")){ + } else if ("Priority".equalsIgnoreCase(attribute.getAttributeId().stringValue())){ try{ priority = Integer.parseInt(attribute.getAttributeValue().getValue().toString()); } catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Unable to Parse Integer for Priority. Setting to default value"); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Unable to Parse Integer for Priority. Setting to default value",e); priority = DEFAULT_PRIORITY; } } else if (attribute.getAttributeId().stringValue().startsWith("matching")) { matchingConditions.put(attribute.getAttributeId().stringValue() .replaceFirst("(matching).", ""),attribute.getAttributeValue().getValue().toString()); - if (attribute.getAttributeId().stringValue() - .replaceFirst("(matching).", "").equals("ECOMPName")) { + if ("ECOMPName".equals(attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", ""))) { match.setEcompName(attribute.getAttributeValue().getValue().toString()); - } else if (attribute.getAttributeId().stringValue() - .replaceFirst("(matching).", "").equals("ConfigName")) { + } else if ("ConfigName".equals(attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", ""))) { match.setConfigName(attribute.getAttributeValue().getValue().toString()); } else { configAttributes.put(attribute.getAttributeId().stringValue() @@ -296,6 +315,23 @@ public class PDPServices { return combinedResult; } + + private String getRainyDayTreatment(Result result) { + String treatment = null; + if (rainydayRequest!=null&& !result.getAssociatedAdvice().isEmpty()) { + // Get the desired treatment for requested errorCode from the Advice + for (Advice advice : result.getAssociatedAdvice()) { + Map<String, String> adviseAttributes = new HashMap<>(); + for (AttributeAssignment attribute : advice.getAttributeAssignments()) { + adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); + if ("treatment".equalsIgnoreCase(attribute.getAttributeId().stringValue())){ + treatment = attribute.getAttributeValue().getValue().toString(); + } + } + } + } + return treatment; + } private PDPResponse configCall(String pdpConfigLocation) throws Exception{ PDPResponse pdpResponse = new PDPResponse(); @@ -392,7 +428,7 @@ public class PDPServices { // call the PDPEngine to decide and give the response on the Request. try { response = pdpEngine.decide(request); - LOGGER.debug("Response from the PDP is: \n" + JSONResponse.toString(response)); + LOGGER.info("Response from the PDP is: \n" + JSONResponse.toString(response)); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); return null; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java index ee8683f1f..a703c50d6 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java @@ -34,7 +34,7 @@ import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; public class PushPolicyService { - private static Logger LOGGER = FlexLogger.getLogger(PushPolicyService.class.getName()); + private static final Logger LOGGER = FlexLogger.getLogger(PushPolicyService.class.getName()); private String pushResult = null; private HttpStatus status = HttpStatus.BAD_REQUEST; @@ -57,7 +57,7 @@ public class PushPolicyService { requestUUID = UUID.fromString(requestID); } catch (IllegalArgumentException e) { requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); } }else{ requestUUID = UUID.randomUUID(); @@ -107,31 +107,6 @@ public class PushPolicyService { LOGGER.error(response); return response; } - /* //String activeVersion = papServices.getActiveVersion(policyScope, filePrefix, policyName, clientScope, pushPolicyParameters.getRequestID()); - LOGGER.debug("The active version of " + policyScope + File.separator + filePrefix + policyName + " is " + activeVersion); - String id = null; - if ("pe100".equalsIgnoreCase(activeVersion)) { - response = XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is 403. PEP is not Authorized for making this Request!! " - + "Contact Administrator for this Scope. "; - LOGGER.error(response); - return response; - } else if ("pe300".equalsIgnoreCase(activeVersion)) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. " - + "This indicates a problem with getting the version from the PAP or the policy does not exist."; - LOGGER.error(response); - return response; - } - if (!activeVersion.equalsIgnoreCase("0")) { - id = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml"; - LOGGER.debug("The policyId is " + id); - } else { - response = XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy. " - + "This indicates the policy does not exist, please verify the policy exists."; - LOGGER.error(response); - return response; - } - StdPDPPolicy selectedPolicy = papServices.getGitPath(policyScope, filePrefix, policyName, activeVersion, clientScope, pushPolicyParameters.getRequestID(), id); - */ try { LOGGER.debug("StdPDPPolicy object contains: " + selectedPolicy.getId() + ", " + selectedPolicy.getName() + ", " + selectedPolicy.getLocation().toString()); response = copyPolicy(selectedPolicy, pdpGroup, clientScope, pushPolicyParameters.getRequestID()); @@ -181,9 +156,9 @@ public class PushPolicyService { // While Validating, extract the required values. if (pushPolicyParameters.getPolicyName() != null && pushPolicyParameters.getPolicyName().contains(".")) { - policyName = pushPolicyParameters.getPolicyName().substring(pushPolicyParameters.getPolicyName().lastIndexOf(".") + 1, + policyName = pushPolicyParameters.getPolicyName().substring(pushPolicyParameters.getPolicyName().lastIndexOf('.') + 1, pushPolicyParameters.getPolicyName().length()); - policyScope = pushPolicyParameters.getPolicyName().substring(0,pushPolicyParameters.getPolicyName().lastIndexOf(".")); + policyScope = pushPolicyParameters.getPolicyName().substring(0,pushPolicyParameters.getPolicyName().lastIndexOf('.')); LOGGER.info("Name is " + policyName + " scope is " + policyScope); } else { message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java index 412adfa86..c16872ebc 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java @@ -23,6 +23,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Map; +import java.util.Map.Entry; import java.util.UUID; import javax.json.Json; @@ -42,7 +43,7 @@ import org.openecomp.policy.xacml.api.XACMLErrorConstants; import org.springframework.http.HttpStatus; public class SendEventService { - private static Logger LOGGER = FlexLogger.getLogger(SendEventService.class.getName()); + private static final Logger LOGGER = FlexLogger.getLogger(SendEventService.class.getName()); private Collection<PolicyResponse> policyResponses = null; private HttpStatus status = HttpStatus.BAD_REQUEST; @@ -59,7 +60,7 @@ public class SendEventService { requestUUID = UUID.fromString(requestID); } catch (IllegalArgumentException e) { requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); } }else{ requestUUID = UUID.randomUUID(); @@ -67,7 +68,7 @@ public class SendEventService { } this.eventRequestParameters.setRequestID(requestUUID); } - policyResponses = new ArrayList<PolicyResponse>(); + policyResponses = new ArrayList<>(); try{ run(); }catch(PolicyEventException e){ @@ -104,7 +105,7 @@ public class SendEventService { Collection<PDPResponse> generateRequest) { Collection<PolicyResponse> result = new HashSet<>(); if (generateRequest == null) { - return null; + return result; } if (!generateRequest.isEmpty()) { for (PDPResponse stdStatus : generateRequest) { @@ -123,29 +124,27 @@ public class SendEventService { private JsonObject getModel() throws PolicyEventException{ JsonArrayBuilder resourceArray = Json.createArrayBuilder(); Map<String,String> eventAttributes = eventRequestParameters.getEventAttributes(); - for (String key : eventAttributes.keySet()) { - if (key.isEmpty()) { + for (Entry<String,String> key : eventAttributes.entrySet()) { + if (key.getKey().isEmpty()) { String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; LOGGER.error(message); throw new PolicyEventException(message); } JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); - if (eventAttributes.get(key).matches("[0-9]+")) { - int val = Integer.parseInt(eventAttributes.get(key)); + if (key.getValue().matches("[0-9]+")) { + int val = Integer.parseInt(key.getValue()); resourceBuilder.add("Value", val); } else { - resourceBuilder.add("Value", eventAttributes.get(key)); + resourceBuilder.add("Value", key.getValue()); } - resourceBuilder.add("AttributeId", key); + resourceBuilder.add("AttributeId", key.getKey()); resourceArray.add(resourceBuilder); } - JsonObject model = Json - .createObjectBuilder() + return Json.createObjectBuilder() .add("Request", Json.createObjectBuilder() .add("Resource",Json.createObjectBuilder() .add("Attribute",resourceArray))) .build(); - return model; } private boolean getValidation() { diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationController.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationController.java index a226a3afe..214151d16 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationController.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationController.java @@ -36,6 +36,7 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; +import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; @@ -81,7 +82,7 @@ public class NotificationController { private static String pdpURL = null; private static Boolean notificationFlag = false; - public void check(PDPStatus newStatus,HashMap<String, PolicyDef> policyContainer) { + public void check(PDPStatus newStatus,Map<String, PolicyDef> policyContainer) { boolean updated = false; boolean removed = false; Notification notification = new Notification(); @@ -167,15 +168,11 @@ public class NotificationController { notificationJSON= record(notification); }catch(Exception e){ LOGGER.error(e); - // TODO:EELF Cleanup - Remove LOGGER - //PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, ""); } NotificationServer.setUpdate(notificationJSON); ManualNotificationUpdateThread.setUpdate(notificationJSON); } catch (JsonProcessingException e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); - // TODO:EELF Cleanup - Remove LOGGER - //PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, ""); } } } @@ -194,15 +191,13 @@ public class NotificationController { private void sendremove(PDPPolicy oldPolicy) { removed = new Removed(); // Want to know what is removed ? - // LOGGER.info("The Policy removed is: " + oldPolicy.getId()); - // LOGGER.info("The version no. is: " + oldPolicy.getVersion()); LOGGER.info("Policy removed: " + oldPolicy.getId()+ " with version number: " + oldPolicy.getVersion()); removed.setPolicyName(oldPolicy.getId()); removed.setVersionNo(oldPolicy.getVersion()); removeFile(oldPolicy); } - private void sendUpdate(PDPPolicy newPolicy,HashMap<String, PolicyDef> policyContainer) { + private void sendUpdate(PDPPolicy newPolicy,Map<String, PolicyDef> policyContainer) { updated = new Updated(); // Want to know what is new ? LOGGER.info("The new Policy is: " + newPolicy.getId()); @@ -327,8 +322,6 @@ public class NotificationController { json = om.writeValueAsString(record); } catch (JsonProcessingException e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); - // TODO:EELF Cleanup - Remove LOGGER - //PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, ""); } LOGGER.info(json); return json; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java index 21fb8f3c9..55ab760af 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java @@ -42,6 +42,7 @@ import org.openecomp.policy.common.logging.eelf.MessageCodes; 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.pdp.rest.api.services.NotificationService; import org.openecomp.policy.rest.XACMLRestProperties; import org.openecomp.policy.utils.BusPublisher; import org.openecomp.policy.xacml.api.XACMLErrorConstants; @@ -63,7 +64,7 @@ import com.att.research.xacml.util.XACMLProperties; @ServerEndpoint(value = "/notifications") public class NotificationServer { private static final Logger LOGGER = FlexLogger.getLogger(NotificationServer.class); - private static Queue<Session> queue = new ConcurrentLinkedQueue<Session>(); + private static Queue<Session> queue = new ConcurrentLinkedQueue<>(); private static String update = null; private static String hosts = null; private static URL aURL = null; @@ -104,7 +105,7 @@ public class NotificationServer { LOGGER.debug("Notification set to " + propNotificationType); if (propNotificationType.equals("ueb")){ - + String topic = null; try { aURL = new URL(pdpURL); @@ -118,7 +119,7 @@ public class NotificationServer { hosts = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); String apiKey = XACMLProperties.getProperty(XACMLRestProperties.PROP_UEB_API_KEY); String apiSecret = XACMLProperties.getProperty(XACMLRestProperties.PROP_UEB_API_SECRET); - + LOGGER.debug("Creating Publisher for host: " + hosts + " with topic: " + topic); CambriaBatchingPublisher pub = null; try { @@ -126,7 +127,7 @@ public class NotificationServer { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); } - + hosts.trim(); topic.trim(); apiKey.trim(); @@ -136,8 +137,8 @@ public class NotificationServer { .onTopic ( topic ) .authenticatedBy ( apiKey, apiSecret ) .build () - ; - + ; + } catch (MalformedURLException e1) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error creating the UEB publisher" + e1.getMessage()); } catch (GeneralSecurityException e1) { @@ -147,7 +148,7 @@ public class NotificationServer { try { pub.send( "MyPartitionKey", notification ); } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update" + e.getMessage() + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update" + e.getMessage()); } // close the publisher. The batching publisher does not send events // immediately, so you MUST use close to send any remaining messages. @@ -156,7 +157,7 @@ public class NotificationServer { // they're returned to your app. You could, for example, persist to disk // and try again later. final List<?> stuck = pub.close ( 20, TimeUnit.SECONDS ); - + if (!stuck.isEmpty()){ LOGGER.error( stuck.size() + " messages unsent" ); }else{ @@ -184,7 +185,7 @@ public class NotificationServer { List<String> dmaapList = null; if(dmaapServers.contains(",")) { - dmaapList = new ArrayList<String>(Arrays.asList(dmaapServers.split("\\s*,\\s*"))); + dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*"))); } else { dmaapList = new ArrayList<>(); dmaapList.add(dmaapServers); @@ -213,9 +214,11 @@ public class NotificationServer { LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage()); } } + NotificationService.sendNotification(notification); } - + public static void setUpdate(String update) { NotificationServer.update = update; } + } diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/XACMLPdpServletTest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/XACMLPdpServletTest.java index 581abbe08..e0d2f18c1 100644 --- a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/XACMLPdpServletTest.java +++ b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/XACMLPdpServletTest.java @@ -95,7 +95,6 @@ public class XACMLPdpServletTest extends TestCase{ System.setProperty("xacml.properties", "xacml.pdp.properties"); System.setProperty("xacml.rest.pdp.config", "config_testing"); - System.setProperty("xacml.rest.pep.idfile", "testclient.properties"); System.setProperty("xacml.rest.pdp.webapps", "/webapps"); System.setProperty("xacml.rootPolicies", "test_PolicyEngine.xml"); System.setProperty("xacml.referencedPolicies", "test_PolicyEngine.xml"); diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/services/PDPServicesTest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/services/PDPServicesTest.java new file mode 100644 index 000000000..fd20e3162 --- /dev/null +++ b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/services/PDPServicesTest.java @@ -0,0 +1,194 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.Map.Entry; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import org.junit.*; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +import org.openecomp.policy.api.DecisionRequestParameters; +import org.openecomp.policy.api.PolicyDecisionException; +import org.openecomp.policy.pdp.rest.api.models.PDPResponse; +import org.openecomp.policy.pdp.rest.config.PDPRestConfig; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PDPRestConfig.class}) +@WebAppConfiguration +public class PDPServicesTest { + /** + * Run the PDPServices() constructor test. + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @Test + public void testPDPServices_1() + throws Exception { + PDPServices result = new PDPServices(); + assertNotNull(result); + // add additional test code here + } + + /** + * Run the Collection<PDPResponse> generateRequest(String,UUID,boolean,boolean) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @Test + public void testGenerateRequest_1() + throws Exception { + DecisionRequestParameters pep = new DecisionRequestParameters(); + Map<String,String> eventAttributes = new HashMap<>(); + eventAttributes.put("TEST", "test"); + pep.setECOMPComponentName("te123"); + pep.setDecisionAttributes(eventAttributes); + PDPServices fixture = new PDPServices(); + + //Failure Tests. + String jsonString = getModel(pep).toString(); + UUID requestID = UUID.randomUUID(); + + Collection<PDPResponse> result = fixture.generateRequest(jsonString, requestID, false, true); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.pdp.rest.api.services.PDPServices + assertNotNull(result); + + } + + private JsonObject getModel(DecisionRequestParameters pep) throws PolicyDecisionException{ + JsonArrayBuilder resourceArray = Json.createArrayBuilder(); + + Map<String, String> decisionAttributes = pep.getDecisionAttributes(); + for (Entry<String,String> key : decisionAttributes.entrySet()) { + JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); + if (key.getValue().matches("[0-9]+")) { + + if ((key.getKey().equals("ErrorCode")) || (key.getKey().equals("WorkStep"))) { + + resourceBuilder.add("Value", key.getValue()); + + } else { + + int val = Integer.parseInt(key.getValue()); + resourceBuilder.add("Value", val); + + } + + } else { + resourceBuilder.add("Value", key.getValue()); + } + resourceBuilder.add("AttributeId", key.getKey()); + resourceArray.add(resourceBuilder); + } + return Json.createObjectBuilder() + .add("Request", Json.createObjectBuilder() + .add("AccessSubject", Json.createObjectBuilder() + .add("Attribute", Json.createObjectBuilder() + .add("Value", pep.getECOMPComponentName()) + .add("AttributeId", "ECOMPName"))) + .add("Resource", Json.createObjectBuilder() + .add("Attribute", resourceArray)) + .add("Action", Json.createObjectBuilder() + .add("Attribute", Json.createObjectBuilder() + .add("Value", "DECIDE") + .add("AttributeId", "urn:oasis:names:tc:xacml:1.0:action:action-id")))) + .build(); + } + + /** + * Run the Collection<PDPResponse> generateRequest(String,UUID,boolean,boolean) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @Test(expected = org.openecomp.policy.api.PolicyException.class) + public void testGenerateRequest_2() + throws Exception { + PDPServices fixture = new PDPServices(); + fixture.generateRequest("", UUID.randomUUID(), true, true); + String jsonString = ""; + UUID requestID = UUID.randomUUID(); + boolean unique = true; + boolean decide = true; + + Collection<PDPResponse> result = fixture.generateRequest(jsonString, requestID, unique, decide); + + // add additional test code here + assertNotNull(result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PDPServicesTest.class); + } +}
\ No newline at end of file diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/NotificationAPITest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/NotificationAPITest.java new file mode 100644 index 000000000..8d6cf8945 --- /dev/null +++ b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/NotificationAPITest.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.test; + +import static org.awaitility.Awaitility.await; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.policy.pdp.rest.api.services.NotificationService; +import org.openecomp.policy.pdp.rest.api.services.NotificationService.NotificationServiceType; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +import com.att.research.xacml.util.XACMLProperties; + +public class NotificationAPITest { + + @Before + public void setup() throws IOException{ + // Fix properties for next test cases. + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/pass.xacml.pdp.properties"); + XACMLProperties.getProperties(); + } + + @Test + public void testPropertyFailure() throws IOException{ + // Change properties and fail. + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/fail.xacml.pdp.properties"); + XACMLProperties.getProperties(); + NotificationService notificationService = new NotificationService(null,null,null); + assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); + setup(); + } + + @Test + public void testFailureTopicName(){ + NotificationService notificationService = new NotificationService(null,null,null); + assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); + assertEquals(XACMLErrorConstants.ERROR_DATA_ISSUE + "org.openecomp.policy.api.PolicyException: Notification Topic is null", notificationService.getResult()); + notificationService = new NotificationService(" ",null,null); + assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); + assertEquals(XACMLErrorConstants.ERROR_DATA_ISSUE + "org.openecomp.policy.api.PolicyException: Notification Topic is not valid. ", notificationService.getResult()); + } + + @Test + public void testFailureServiceType(){ + NotificationService notificationService = new NotificationService("test",null,null); + assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); + } + + @Test + public void threadTest() throws InterruptedException{ + NotificationService notificationSerivce = new NotificationService("test",null,NotificationServiceType.ADD); + assertEquals(HttpStatus.OK, notificationSerivce.getResponseCode()); + // Wait for thread to remove the Topic Entry. + await().atMost(Integer.toUnsignedLong(2500),TimeUnit.MILLISECONDS).until(()-> { + // Trying to remove again should fail + NotificationService nService = new NotificationService("test",null,NotificationServiceType.REMOVE); + return HttpStatus.BAD_REQUEST.equals(nService.getResponseCode()); + }); + // Coverage Tests, Call Notification Service. + NotificationService.sendNotification("test"); + } +} diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/PolicyEngineServicesTest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/PolicyEngineServicesTest.java new file mode 100644 index 000000000..eb514a8f5 --- /dev/null +++ b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/PolicyEngineServicesTest.java @@ -0,0 +1,832 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.test; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.policy.api.AttributeType; +import org.openecomp.policy.api.ConfigRequestParameters; +import org.openecomp.policy.api.DecisionRequestParameters; +import org.openecomp.policy.api.DeletePolicyCondition; +import org.openecomp.policy.api.DeletePolicyParameters; +import org.openecomp.policy.api.DictionaryParameters; +import org.openecomp.policy.api.DictionaryType; +import org.openecomp.policy.api.EventRequestParameters; +import org.openecomp.policy.api.PolicyClass; +import org.openecomp.policy.api.PolicyConfigType; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.api.PolicyType; +import org.openecomp.policy.api.PushPolicyParameters; +import org.openecomp.policy.pdp.rest.XACMLPdpServlet; +import org.openecomp.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest; +import org.openecomp.policy.pdp.rest.api.models.ConfigNameRequest; +import org.openecomp.policy.pdp.rest.api.models.ConfigPolicyAPIRequest; +import org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl; +import org.openecomp.policy.pdp.rest.config.PDPRestConfig; +import org.openecomp.policy.utils.PolicyUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.context.WebApplicationContext; + +import com.att.research.xacml.util.XACMLProperties; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PDPRestConfig.class}) +@WebAppConfiguration +public class PolicyEngineServicesTest { + private static final String CLIENTAUTHHEADER = "ClientAuth"; + private static final String UUIDHEADER = "X-ECOMP-RequestID"; + // This value is as per test resource code. Don't change this. + private static final String CLIENTAUTHVALUE = "Basic cHl0aG9uOnRlc3Q="; + private static final String ERRORCLIENTVALUE = "Basic dGVzdDp0ZXN0MTIz"; + + private MockMvc mockMvc; + private HttpHeaders headers; + + @Autowired + private WebApplicationContext webApplicationContext; + + @Before() + public void setup() throws IOException{ + headers = new HttpHeaders(); + headers.add(CLIENTAUTHHEADER, CLIENTAUTHVALUE); + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/pass.xacml.pdp.properties"); + XACMLProperties.getProperties(); + this.mockMvc = webAppContextSetup(webApplicationContext).build(); + } + + @Test + public void getConfigAPIFailureTest() throws Exception{ + ConfigRequestParameters pep = new ConfigRequestParameters(); + pep.setPolicyName(".*"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(400)); + // Authorization tests. + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, ERRORCLIENTVALUE)) + .andExpect(status().isUnauthorized()); + // Set wrong request. + pep.setPolicyName(null); + pep.setConfigName("test"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, "123").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + + @Test + public void getConfigServiceTest() throws Exception{ + ConfigRequestParameters pep = new ConfigRequestParameters(); + pep.setPolicyName(".*"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, UUID.randomUUID()).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + // Without policyName and using ecompName and other fields. + pep.setPolicyName(null); + pep.setEcompName("test"); + pep.setConfigName("test"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + // with config attributes. + Map<String, String> configAttributes = new HashMap<>(); + configAttributes.put("test", "test"); + pep.setConfigAttributes(configAttributes); + pep.makeUnique(true); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void getConfigByPolicyNameTest() throws Exception{ + ConfigNameRequest pep = new ConfigNameRequest(); + pep.setPolicyName(".*"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(400)); + // Authorization tests. + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getConfigByPolicyName").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, UUID.randomUUID()).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void listConfigTest() throws Exception{ + ConfigRequestParameters pep = new ConfigRequestParameters(); + pep.setPolicyName(".*"); + mockMvc.perform(post("/listConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(400)); + // Authorization tests. + mockMvc.perform(post("/listConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/listConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, UUID.randomUUID()).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void getMetricsTest() throws Exception{ + //Failure Tests. + mockMvc.perform(get("/getMetrics")).andExpect(status().isBadRequest()); + mockMvc.perform(get("/getMetrics").header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(get("/getMetrics").headers(headers).header(UUIDHEADER, "123")).andExpect(status().isOk()); + mockMvc.perform(get("/getMetrics").headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isOk()); + mockMvc.perform(get("/getMetrics").headers(headers)).andExpect(status().isOk()); + } + + @Test + public void getNotificationAuthFailureTest() throws Exception{ + mockMvc.perform(post("/getNotification").header(CLIENTAUTHHEADER, "").content("test")).andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getNotification").header(CLIENTAUTHHEADER, "Basic test123").content("test")).andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getNotification").header(CLIENTAUTHHEADER, ERRORCLIENTVALUE).content(" ")).andExpect(status().isUnauthorized()); + } + + @Test + public void getNotificationTopicFailureTest() throws Exception{ + mockMvc.perform(post("/getNotification")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/getNotification").headers(headers).content("")).andExpect(status().isBadRequest()); + } + + @Test + public void getNotificationTopicValidFailTest() throws Exception{ + // Check failures. + mockMvc.perform(post("/getNotification").headers(headers).content(" ")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/stopNotification").headers(headers).content(" ")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/sendHeartbeat").headers(headers).content(" ")).andExpect(status().isBadRequest()); + } + + @Test + public void getNotificationTopicValidPassTest() throws Exception{ + // Add a Topic. + mockMvc.perform(post("/getNotification").headers(headers).header(UUIDHEADER, "123").content("test")).andExpect(status().isOk()); + // Try to add same topic should fail. + mockMvc.perform(post("/getNotification").headers(headers).header(UUIDHEADER, UUID.randomUUID()).content("test")).andExpect(status().isBadRequest()); + // do a heart beat. + mockMvc.perform(post("/sendHeartbeat").headers(headers).content("test")).andExpect(status().isOk()); + // remove the added Topic. + mockMvc.perform(post("/stopNotification").headers(headers).content("test")).andExpect(status().isOk()); + // try to remove again should fail. + mockMvc.perform(post("/sendHeartbeat").headers(headers).content("test")).andExpect(status().isBadRequest()); + } + + @Test + public void sendEventTest() throws Exception{ + EventRequestParameters pep = new EventRequestParameters(); + Map<String,String> eventAttributes = new HashMap<>(); + eventAttributes.put("TEST", "test"); + pep.setEventAttributes(eventAttributes); + //Failure Tests. + mockMvc.perform(post("/sendEvent")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isOk()); + pep.setEventAttributes(null); + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setEventAttributes(eventAttributes); + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isOk()); + pep.setEventAttributes(eventAttributes); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isOk()); + } + + @Test + public void getDecisionTest() throws Exception{ + DecisionRequestParameters pep = new DecisionRequestParameters(); + Map<String,String> eventAttributes = new HashMap<>(); + eventAttributes.put("TEST", "test"); + pep.setECOMPComponentName("te123"); + pep.setDecisionAttributes(eventAttributes); + //Failure Tests. + mockMvc.perform(post("/getDecision")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isOk()); + pep.setDecisionAttributes(null); + pep.setECOMPComponentName(null); + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setECOMPComponentName("testing"); + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setDecisionAttributes(eventAttributes); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isOk()); + } + + @Test + public void pushPolicyTest() throws Exception{ + PushPolicyParameters pep = new PushPolicyParameters(); + //Failure Tests. + mockMvc.perform(put("/pushPolicy")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("scopeless"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyName("testing.test"); + pep.setPolicyType("wrong"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("BRMS_PARAM"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("BRMS_RAW"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("MicroService"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("ClosedLoop_PM"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("ClosedLoop_Fault"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("Base"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("Decision"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("Action"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("Firewall"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPdpGroup("default"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isBadRequest()); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + } + + @Test + public void deletePolicyTest() throws Exception{ + DeletePolicyParameters pep = new DeletePolicyParameters(); + //Failure Tests. + mockMvc.perform(delete("/deletePolicy")).andExpect(status().isBadRequest()); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("testing"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "test123")).andExpect(status().isBadRequest()); + pep.setPolicyName("testscope.name"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyName("testscope.name"); + pep.setPolicyType("wrong"); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("BRMS_PARAM"); + pep.setPolicyComponent("wrong"); + pep.setRequestID(null); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("BRMS_RAW"); + pep.setPolicyComponent("PDP"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("MicroService"); + pep.setPolicyComponent("PAP"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("ClosedLoop_PM"); + pep.setPolicyComponent("PDP"); + pep.setDeleteCondition(DeletePolicyCondition.ALL); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("ClosedLoop_Fault"); + pep.setDeleteCondition(DeletePolicyCondition.ONE); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("Base"); + pep.setPolicyComponent("PAP"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("Decision"); + pep.setPolicyComponent("PDP"); + pep.setPolicyName("test.xml"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("Action"); + pep.setPolicyName("scope.Config_test.xml"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPdpGroup("default"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent("PAP"); + pep.setPolicyType("Firewall"); + pep.setDeleteCondition(null); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent("PAP"); + pep.setDeleteCondition(DeletePolicyCondition.ONE); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent("fail"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent("PDP"); + pep.setPolicyName("testscope.policyName"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent(null); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + } + + @Test + public void createUpdatePolicyTest() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + //Failure Tests. + mockMvc.perform(put("/createPolicy")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + setCreateUpdateImpl(); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("failName"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "test 123")).andExpect(status().isBadRequest()); + pep.setPolicyName("test. name"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyName(" "); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("test. "); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("te st.name"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("testá"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + } + + @Test + public void brmsPolicyCreationTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for BRMS Param Policy. + pep.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + Map<AttributeType, Map<String,String>> attributes = new HashMap<>(); + Map<String,String> matching = new HashMap<>(); + matching.put("key", "value"); + attributes.put(AttributeType.MATCHING, matching); + pep.setAttributes(attributes); + pep.setRiskLevel("5"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + // Checks for BRMS Raw Policy + pep.setPolicyConfigType(PolicyConfigType.BRMS_RAW); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel(null); + pep.setConfigBody("package droolsexample\n\n import com.sample.ItemCity;\nimport java.math.BigDecimal;\nrule \"Nagpur Medicine Item\"\n\n when\n item : ItemCity(purchaseCity == ItemCity.City.NAGPUR,\n typeofItem == ItemCity.Type.MEDICINES)\n then\n BigDecimal tax = new BigDecimal(0.0);\n item.setLocalTax(tax.multiply(item.getSellPrice()));\nend"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("5"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void baseConfigTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Base config Policy. + pep.setPolicyConfigType(PolicyConfigType.Base); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("testbody"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBodyType(PolicyType.OTHER); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setEcompName("ec nam-e"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setEcompName("ecompName"); + pep.setConfigName("tes config"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigName("configName"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setConfigBody("{'test':'test}"); + pep.setConfigBodyType(PolicyType.JSON); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + Map<AttributeType, Map<String,String>> attributes = new HashMap<>(); + Map<String,String> matching = new HashMap<>(); + matching.put("key", "value"); + attributes.put(AttributeType.MATCHING, matching); + pep.setAttributes(attributes); + pep.setConfigBody("testBody"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void closedLoopPolicyTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Closed loop Policy. + pep.setPolicyConfigType(PolicyConfigType.ClosedLoop_Fault); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("te stá"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("testBody"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"key\":\"value\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"ecompname\":\"\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"ecompname\":\"test\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void closedLoopPMTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Closed loop Policy. + pep.setPolicyConfigType(PolicyConfigType.ClosedLoop_PM); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("te stá"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("testBody"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"key\":\"value\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"ecompname\":\"\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"ecompname\":\"test\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"ecompname\":\"test\", \"serviceTypePolicyName\":\"value\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void firewallPolicyTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Closed loop Policy. + pep.setPolicyConfigType(PolicyConfigType.Firewall); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("te st"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"test\":\"test\"}"); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"configName\":\"test\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void microServicePolicyTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Closed loop Policy. + pep.setPolicyConfigType(PolicyConfigType.MicroService); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("te st"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"test\":\"test\"}"); + pep.setEcompName(" "); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setEcompName("testecomp"); + pep.setRiskLevel("fail"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setConfigBody("{\"service\":\"test\",\"uuid\":\"test\",\"location\":\"test\",\"configName\":\"test\",\"description\":\"test\",\"priority\":\"test\",\"version\":\"test\"}"); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void actionDecisionPolicyCreationTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for action Policy. + pep.setPolicyClass(PolicyClass.Action); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + Map<AttributeType, Map<String,String>> attributes = new HashMap<>(); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + attributes.put(AttributeType.MATCHING, new HashMap<>()); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + Map<String,String> matching = new HashMap<>(); + matching.put("key", "value"); + attributes.put(AttributeType.MATCHING, matching); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setActionAttribute("A1"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setActionPerformer("PEX"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setActionPerformer("PEP"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + // Checks for Decision Policy. + pep.setPolicyClass(PolicyClass.Decision); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setEcompName("xyz"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + attributes.remove(AttributeType.MATCHING); + attributes.put(AttributeType.SETTINGS, matching); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + attributes.put(AttributeType.MATCHING, matching); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void createUpdateDictionaryTests() throws Exception{ + DictionaryParameters pep = new DictionaryParameters(); + //Failure Tests. + mockMvc.perform(put("/createDictionaryItem")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + mockMvc.perform(put("/updateDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setDictionaryType(DictionaryType.MicroService); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setDictionary("test dict"); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setDictionaryJson("{\"test\":\"value\"}"); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isInternalServerError()); + pep.setDictionaryJson("test123"); + mockMvc.perform(put("/updateDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isBadRequest()); + pep.setDictionary("MicroServiceDictionary"); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + } + + @Test + public void getDictionaryTests() throws Exception{ + DictionaryParameters pep = new DictionaryParameters(); + //Failure Tests. + mockMvc.perform(post("/getDictionaryItems")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setDictionaryType(DictionaryType.Common); + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID().toString())).andExpect(status().isBadRequest()); + pep.setDictionary("EcompName"); + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void policyEngineImportTests() throws Exception{ + //Failure Tests. + mockMvc.perform(post("/policyEngineImport")).andExpect(status().isBadRequest()); + } + + @Test + public void oldConfigAPITests() throws Exception{ + ConfigPolicyAPIRequest pep = new ConfigPolicyAPIRequest(); + //Failure Tests. + mockMvc.perform(put("/createConfig")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + mockMvc.perform(put("/updateConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setPolicyScope("test"); + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setPolicyName("name"); + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setConfigType("OTHER"); + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setTtlDate(new Date().toString()); + mockMvc.perform(put("/updateConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + } + + @Test + public void oldFirewallAPITests() throws Exception{ + ConfigFirewallPolicyAPIRequest pep = new ConfigFirewallPolicyAPIRequest(); + //Failure Tests. + mockMvc.perform(put("/createFirewallConfig")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + mockMvc.perform(put("/updateFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setPolicyScope("test"); + mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setPolicyName("name"); + mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setTtlDate(new Date().toString()); + mockMvc.perform(put("/updateFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + } + + private void setCreateUpdateImpl() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method setter = XACMLPdpServlet.class.getDeclaredMethod("setCreateUpdatePolicyConstructor", String.class); + setter.setAccessible(true); + setter.invoke(new XACMLPdpServlet(), CreateUpdatePolicyServiceImpl.class.getName()); + } + + //Health Check Tests + @Test + public void getCountTest() throws Exception { + mockMvc.perform(get("/count")) + .andExpect(status().isOk()); + } +} diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getConfigTest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getConfigTest.java new file mode 100644 index 000000000..ebe86b0d8 --- /dev/null +++ b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getConfigTest.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.test; + +import static org.junit.Assert.assertEquals; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.openecomp.policy.api.ConfigRequestParameters; +import org.openecomp.policy.api.PolicyConfigStatus; +import org.openecomp.policy.pdp.rest.api.models.PolicyConfig; +import org.openecomp.policy.pdp.rest.api.services.GetConfigService; + +public class getConfigTest { + private static final String TEST = "test"; + + @SuppressWarnings("unchecked") + @Test + public void filterMethodTest() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ + ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); + GetConfigService getConfigService= new GetConfigService(configRequestParameters, null); + Method filter = GetConfigService.class.getDeclaredMethod("filterResults", Collection.class,ConfigRequestParameters.class); + filter.setAccessible(true); + List<PolicyConfig> policyConfigs = new LinkedList<>(); + + List<PolicyConfig> filterResults = (List<PolicyConfig>) filter.invoke(getConfigService, policyConfigs,configRequestParameters); + assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND, filterResults.get(0).getPolicyConfigStatus()); + // Check again with some values + configRequestParameters.setPolicyName(TEST); + configRequestParameters.setEcompName(TEST); + configRequestParameters.setConfigName(TEST); + Map<String,String> configAttributes = new HashMap<>(); + configAttributes.put(TEST, TEST); + configRequestParameters.setConfigAttributes(configAttributes); + PolicyConfig pConfig = new PolicyConfig(); + pConfig.setPolicyName(TEST); + Map<String,String> matching = new HashMap<>(); + matching.put("ECOMPName", TEST); + matching.put("ConfigName", TEST); + matching.put("TEST", TEST); + pConfig.setMatchingConditions(matching); + policyConfigs.add(pConfig); + filterResults = (List<PolicyConfig>) filter.invoke(getConfigService, policyConfigs,configRequestParameters); + assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND, filterResults.get(0).getPolicyConfigStatus()); + } +} diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getDictionaryTest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getDictionaryTest.java new file mode 100644 index 000000000..3ade07ccb --- /dev/null +++ b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getDictionaryTest.java @@ -0,0 +1,231 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.lang.reflect.Method; + +import org.junit.Test; +import org.openecomp.policy.api.DictionaryParameters; +import org.openecomp.policy.pdp.rest.api.services.GetDictionaryService; + +public class getDictionaryTest { + + @Test + public void dictionaryJsonTest() throws Exception{ + Method formatDictionary = GetDictionaryService.class.getDeclaredMethod("formatDictionaryJson", String.class); + formatDictionary.setAccessible(true); + String input="{\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"," + + "\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"," + + "\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"}"; + DictionaryParameters dp = new DictionaryParameters(); + dp.setDictionary("test"); + GetDictionaryService gds = new GetDictionaryService(dp, null); + String result = (String) formatDictionary.invoke(gds, input); + assertNull(result); + // + dp.setDictionary("EcompName"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Attribute"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Action"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("BRMSParamTemplate"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("VSCLAction"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("VNFType"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PEPOptions"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Varbind"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Service"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Site"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Settings"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("DescriptiveScope"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Enforcer"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("ActionList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("ProtocolList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Zone"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("SecurityZone"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PrefixList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("AddressGroup"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("ServiceGroup"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("ServiceList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("TermList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("RuleList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("FirewallRuleList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Term"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("MicroServiceLocation"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("MicroServiceConfigName"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("DCAEUUID"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("MicroServiceModels"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PolicyScopeService"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PolicyScopeResource"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PolicyScopeType"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PolicyScopeClosedLoop"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("GroupPolicyScopeList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("RiskType"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("SafePolicyWarning"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("MicroServiceDictionary"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + } +} diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/auth/test/FilterTests.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/auth/test/FilterTests.java new file mode 100644 index 000000000..944dd90a9 --- /dev/null +++ b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/auth/test/FilterTests.java @@ -0,0 +1,199 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pdp.rest.auth.test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.policy.pdp.rest.restAuth.PDPAuthenticationFilter; + +import com.att.research.xacml.util.XACMLProperties; +import com.mockrunner.mock.web.MockRequestDispatcher; + +public class FilterTests { + + private PDPAuthenticationFilter authenticationFilter = new PDPAuthenticationFilter(); + private final String VALIDHEADERVALUE = "Basic dGVzdHBkcDphbHBoYTQ1Ng=="; + + @Before + public void setUp() throws Exception{ + authenticationFilter.init(null); + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/pass.xacml.pdp.properties"); + XACMLProperties.getProperties(); + } + + @Test + public void testDoFilterError() throws IOException, ServletException { + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("error"); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if unauthorized + verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + public void testDoFilterNotification() throws IOException, ServletException { + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("notifications"); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + verify(filterChain).doFilter(httpServletRequest,httpServletResponse); + } + + @Test + public void testDoFilterSwagger() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/swagger"); + when(httpServletRequest.getRequestDispatcher("/api/swagger")).thenReturn(new MockRequestDispatcher()); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + verify(httpServletRequest).getRequestDispatcher("/api/swagger"); + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api-docs/"); + when(httpServletRequest.getRequestDispatcher("/api/api-docs/")).thenReturn(new MockRequestDispatcher()); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + verify(httpServletRequest).getRequestDispatcher("/api/api-docs/"); + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/configuration"); + when(httpServletRequest.getRequestDispatcher("/api/configuration")).thenReturn(new MockRequestDispatcher()); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + verify(httpServletRequest).getRequestDispatcher("/api/configuration"); + } + + @Test + public void newRequestAuthFailTest() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("error"); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if unauthorized + verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + public void tokenFailureTest() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic test123"); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if unauthorized + verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + public void oldRequestAuthPassTest() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // New request no environment header check + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api/getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if authorized + verify(httpServletRequest).getRequestDispatcher("/api/getConfig"); + // + // Old Requests Checks + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api//getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if authorized + verify(httpServletRequest).getRequestDispatcher("/api//getConfig"); + } + + @Test + public void newRequestAuthPassTest() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + // Requests with Valid Environment Header values. + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api//getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("DEVL"); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if authorized + verify(httpServletRequest).getRequestDispatcher("/api//getConfig"); + // New request no environment header check + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api/getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if authorized + verify(httpServletRequest).getRequestDispatcher("/api/getConfig"); + // + // + // Requests with InValid Environment Header + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api//getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("TEST"); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if unauthorized + verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } +} diff --git a/ECOMP-PDP-REST/src/test/resources/client.properties b/ECOMP-PDP-REST/src/test/resources/client.properties new file mode 100644 index 000000000..13aa106cd --- /dev/null +++ b/ECOMP-PDP-REST/src/test/resources/client.properties @@ -0,0 +1,2 @@ +#Don't Change this +python=test,MASTER
\ No newline at end of file diff --git a/ECOMP-PDP-REST/src/test/resources/fail.xacml.pdp.properties b/ECOMP-PDP-REST/src/test/resources/fail.xacml.pdp.properties new file mode 100644 index 000000000..52ca6ab92 --- /dev/null +++ b/ECOMP-PDP-REST/src/test/resources/fail.xacml.pdp.properties @@ -0,0 +1,171 @@ +### +# ============LICENSE_START======================================================= +# ECOMP-PDP-REST +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +# Default XACML Properties File for PDP RESTful servlet +# +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +# NOT USED SEE BELOW xacml.pipFinderFactory=org.openecomp.policy.xacml.std.pip.StdPIPFinderFactory +xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory +# +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=org.openecomp.policy.xacml.custom.EcompFunctionDefinitionFactory +# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.openecomp.policy.pdp.std.StdPolicyFinderFactory +# creteUpdate Policy Implementation Class details. +createUpdatePolicy.impl.className=org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl +# AAF Implementation class details +aafClient.impl.className=org.openecomp.policy.utils.AAFPolicyClientImpl +# +# AT&T RESTful PDP Implementation Factories +# +xacml.pipFinderFactory=org.openecomp.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory +xacml.att.policyFinderFactory=org.openecomp.policy.pdp.rest.XACMLPdpPolicyFinderFactory +# +# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into +# into one PolicySet and use the given Policy Algorithm. +# +xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides +# +# PDP RESTful API properties +# +# Set this to the address where the XACML-PAP-REST servlet is running +xacml.rest.pap.url=http://localhost:8070/pap/ + +#if multiple paps exist, the xacml.rest.pap.url can be removed and they can be defined like this: +#xacml.rest.pap.urls=http://localhost:9090/pap/,http://localhost:9091/pap/ + +# +# Give the running PDP an ID for the PAP. The url that its running as is a good choice. +# The PAP identifies PDP's using the URL of the PDP. +# +xacml.rest.pdp.id=http://localhost:8082/pdp/ + +# Give the port number used for the PDP + +xacml.jmx.port=0 + + +# Notification Properties +# Notifcation type: websocket, ueb or dmaap... if left blank websocket is the default +NOTIFICATION_TYPE=websocket +NOTIFICATION_SERVERS= +NOTIFICATION_TOPIC= +NOTIFICATION_DELAY=500 +UEB_API_KEY= +UEB_API_SECRET= +DMAAP_AAF_LOGIN=test +DMAAP_AAF_PASSWORD=test + +# +# Set the directory where the PDP holds its Policy Cache and PIP Configuration +# +xacml.rest.pdp.config=config + +xacml.rest.pdp.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ +# +# Initialize register with PAP servlet +# +xacml.rest.pdp.register=true +# +# Sleep period in seconds between register attempts +# +xacml.rest.pdp.register.sleep=15 +# +# number of attempts to register. -1 means keep trying forever. +# +xacml.rest.pdp.register.retries=-1 +# +# max number of bytes in a POST of a XML/JSON request +# old value #32767 +xacml.rest.pdp.maxcontent=99999999 +# +# Set UserID here +xacml.rest.pdp.userid=testpdp +# Set Password here +xacml.rest.pdp.password=alpha456 + +# id PAP +xacml.rest.pap.userid=testpap +#if multiple paps have different logins, they can be defined like this: +#http\://localhost\:9090/pap/.xacml.rest.pap.userid=testpap + +# pass PAP +xacml.rest.pap.password=alpha123 +#http\://localhost\:9090/pap/.xacml.rest.pap.password=alpha123 + +# Delay for Notifications Don't change this. Value in milliSec. +xacml.rest.notification.delay=30 +# Buffer Size. +REQUEST_BUFFER_SIZE=15 + +#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs +javax.persistence.jdbc.driver=com.mysql.jdbc.Driver +javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/xacml +javax.persistence.jdbc.user=policy_user +javax.persistence.jdbc.password=policy_user + + +#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** + +#The name of the PDP. Must be unique across the system +xacml.rest.pdp.resource.name=site_1.pdp_1 + +#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** + +#Interval between forward progress counter updates in seconds +fp_monitor_interval=30 + +#Number of forward progress counter failures before failover +failed_counter_threshold=3 + +#Interval in seconds between test transactions if there is no other traffic +test_trans_interval=10 + +#Interval in seconds between updates of the forward progress counter in the DB +write_fpc_interval=5 + +#Name of the site +site_name=site_1 + +#Node type +node_type=pdp_xacml + +#Dependency groups are groups of resources upon which a node operational state is dependent upon). +#Each group is a comma-separated list of resource names and groups are separated by a semicolon. +#A group may contain one or more members. Resource names must match the resource names defined +#in the respective servers' properties files +dependency_groups=site_1.pdplp_1;site_1.astragw_1;site_1.brmsgw_1 + +# this can be DEVL, TEST, PROD +ENVIRONMENT=DEVL +xacml.rest.pep.idfile = src/test/resources/client.properties + +#AAF Policy Name space +#Not Mandatory for Open Ecomp +policy.aaf.namespace = +policy.aaf.resource = +# +DMAAP_AAF_LOGIN = diff --git a/ECOMP-PDP-REST/src/test/resources/pass.xacml.pdp.properties b/ECOMP-PDP-REST/src/test/resources/pass.xacml.pdp.properties new file mode 100644 index 000000000..0fe3e2aee --- /dev/null +++ b/ECOMP-PDP-REST/src/test/resources/pass.xacml.pdp.properties @@ -0,0 +1,171 @@ +### +# ============LICENSE_START======================================================= +# ECOMP-PDP-REST +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +# Default XACML Properties File for PDP RESTful servlet +# +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +# NOT USED SEE BELOW xacml.pipFinderFactory=org.openecomp.policy.xacml.std.pip.StdPIPFinderFactory +xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory +# +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=org.openecomp.policy.xacml.custom.EcompFunctionDefinitionFactory +# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.openecomp.policy.pdp.std.StdPolicyFinderFactory +# creteUpdate Policy Implementation Class details. +createUpdatePolicy.impl.className=org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl +# AAF Implementation class details +aafClient.impl.className=org.openecomp.policy.utils.AAFPolicyClientImpl +# +# AT&T RESTful PDP Implementation Factories +# +xacml.pipFinderFactory=org.openecomp.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory +xacml.att.policyFinderFactory=org.openecomp.policy.pdp.rest.XACMLPdpPolicyFinderFactory +# +# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into +# into one PolicySet and use the given Policy Algorithm. +# +xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides +# +# PDP RESTful API properties +# +# Set this to the address where the XACML-PAP-REST servlet is running +xacml.rest.pap.url=http://localhost:8070/pap/ + +#if multiple paps exist, the xacml.rest.pap.url can be removed and they can be defined like this: +#xacml.rest.pap.urls=http://localhost:9090/pap/,http://localhost:9091/pap/ + +# +# Give the running PDP an ID for the PAP. The url that its running as is a good choice. +# The PAP identifies PDP's using the URL of the PDP. +# +xacml.rest.pdp.id=http://localhost:8082/pdp/ + +# Give the port number used for the PDP + +xacml.jmx.port=0 + + +# Notification Properties +# Notifcation type: websocket, ueb or dmaap... if left blank websocket is the default +NOTIFICATION_TYPE=websocket +NOTIFICATION_SERVERS=test +NOTIFICATION_TOPIC=test +NOTIFICATION_DELAY=500 +UEB_API_KEY= +UEB_API_SECRET= +DMAAP_AAF_LOGIN=test +DMAAP_AAF_PASSWORD=test + +# +# Set the directory where the PDP holds its Policy Cache and PIP Configuration +# +xacml.rest.pdp.config=config + +xacml.rest.pdp.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ +# +# Initialize register with PAP servlet +# +xacml.rest.pdp.register=true +# +# Sleep period in seconds between register attempts +# +xacml.rest.pdp.register.sleep=15 +# +# number of attempts to register. -1 means keep trying forever. +# +xacml.rest.pdp.register.retries=-1 +# +# max number of bytes in a POST of a XML/JSON request +# old value #32767 +xacml.rest.pdp.maxcontent=99999999 +# +# Set UserID here +xacml.rest.pdp.userid=testpdp +# Set Password here +xacml.rest.pdp.password=alpha456 + +# id PAP +xacml.rest.pap.userid=testpap +#if multiple paps have different logins, they can be defined like this: +#http\://localhost\:9090/pap/.xacml.rest.pap.userid=testpap + +# pass PAP +xacml.rest.pap.password=alpha123 +#http\://localhost\:9090/pap/.xacml.rest.pap.password=alpha123 + +# Delay for Notifications Don't change this. Value in milliSec. +xacml.rest.notification.delay=30 +# Buffer Size. +REQUEST_BUFFER_SIZE=15 + +#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs +javax.persistence.jdbc.driver=com.mysql.jdbc.Driver +javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/xacml +javax.persistence.jdbc.user=policy_user +javax.persistence.jdbc.password=policy_user + + +#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** + +#The name of the PDP. Must be unique across the system +xacml.rest.pdp.resource.name=site_1.pdp_1 + +#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** + +#Interval between forward progress counter updates in seconds +fp_monitor_interval=30 + +#Number of forward progress counter failures before failover +failed_counter_threshold=3 + +#Interval in seconds between test transactions if there is no other traffic +test_trans_interval=10 + +#Interval in seconds between updates of the forward progress counter in the DB +write_fpc_interval=5 + +#Name of the site +site_name=site_1 + +#Node type +node_type=pdp_xacml + +#Dependency groups are groups of resources upon which a node operational state is dependent upon). +#Each group is a comma-separated list of resource names and groups are separated by a semicolon. +#A group may contain one or more members. Resource names must match the resource names defined +#in the respective servers' properties files +dependency_groups=site_1.pdplp_1;site_1.astragw_1;site_1.brmsgw_1 + +# this can be DEVL, TEST, PROD +ENVIRONMENT=DEVL +xacml.rest.pep.idfile = src/test/resources/client.properties + +#AAF Policy Name space +#Not Mandatory for Open Ecomp +policy.aaf.namespace = +policy.aaf.resource = +# +DMAAP_AAF_LOGIN = diff --git a/ECOMP-PDP-REST/src/test/resources/test.drl b/ECOMP-PDP-REST/src/test/resources/test.drl new file mode 100644 index 000000000..2a58f5439 --- /dev/null +++ b/ECOMP-PDP-REST/src/test/resources/test.drl @@ -0,0 +1,1121 @@ +/*- + * ============LICENSE_START======================================================= + * archetype-closed-loop-demo-rules + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop; + +import java.util.List; +import java.util.LinkedList; +import java.util.Map; +import java.util.HashMap; +import java.util.UUID; + +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.ControlLoopOperation; +import org.onap.policy.controlloop.ControlLoopOperationWrapper; +import org.onap.policy.template.demo.ControlLoopException; + +import org.onap.policy.aai.AAINQF199.AAINQF199CloudRegion; +import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperties; +import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperty; +import org.onap.policy.aai.AAINQF199.AAINQF199GenericVNF; +import org.onap.policy.aai.AAINQF199.AAINQF199InstanceFilters; +import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItem; +import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItems; +import org.onap.policy.aai.AAINQF199.AAINQF199Manager; +import org.onap.policy.aai.AAINQF199.AAINQF199NamedQuery; +import org.onap.policy.aai.AAINQF199.AAINQF199QueryParameters; +import org.onap.policy.aai.AAINQF199.AAINQF199Request; +import org.onap.policy.aai.AAINQF199.AAINQF199RequestWrapper; +import org.onap.policy.aai.AAINQF199.AAINQF199Response; +import org.onap.policy.aai.AAINQF199.AAINQF199ResponseWrapper; +import org.onap.policy.aai.AAINQF199.AAINQF199ServiceInstance; +import org.onap.policy.aai.AAINQF199.AAINQF199Tenant; +import org.onap.policy.aai.AAINQF199.AAINQF199VfModule; +import org.onap.policy.aai.AAINQF199.AAINQF199VServer; +import org.onap.policy.aai.util.Serialization; + +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.appc.Request; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseCode; +import org.onap.policy.appc.ResponseStatus; +import org.onap.policy.appc.ResponseValue; + +import org.onap.policy.template.demo.EventManager; +import org.onap.policy.vnf.trafficgenerator.PGRequest; +import org.onap.policy.vnf.trafficgenerator.PGStream; +import org.onap.policy.vnf.trafficgenerator.PGStreams; + +import org.onap.policy.mso.MSOManager; +import org.onap.policy.mso.MSORequest; +import org.onap.policy.mso.MSORequestStatus; +import org.onap.policy.mso.MSORequestDetails; +import org.onap.policy.mso.MSOModelInfo; +import org.onap.policy.mso.MSOCloudConfiguration; +import org.onap.policy.mso.MSORequestInfo; +import org.onap.policy.mso.MSORequestParameters; +import org.onap.policy.mso.MSORelatedInstanceListElement; +import org.onap.policy.mso.MSORelatedInstance; +import org.onap.policy.mso.MSOResponse; + +import org.openecomp.policy.drools.system.PolicyEngine; + +// +// These parameters are required to build the runtime policy +// +declare Params + closedLoopControlName : String + actor : String + aaiURL : String + aaiUsername : String + aaiPassword : String + msoURL : String + msoUsername : String + msoPassword : String + aaiNamedQueryUUID : String + aaiPatternMatch : int + notificationTopic : String + appcTopic : String +end + +/* +* +* Called once and only once to insert the parameters into working memory for this Closed Loop policy. +* (Comment SETUP rule out for the first ECOMP opensource release since policy BRMS_GW already puts a Params fact in there) +* +* +*rule "${policyName}.SETUP" +* when +* then +* System.out.println("rule SETUP is triggered."); +* Params params = new Params(); +* params.setClosedLoopControlName("${closedLoopControlName}"); +* params.setActor("${actor}"); +* params.setAaiURL("${aaiURL}"); +* params.setAaiUsername("${aaiUsername}"); +* params.setAaiPassword("${aaiPassword}"); +* params.setMsoURL("${msoURL}"); +* params.setMsoUsername("${msoUsername}"); +* params.setMsoPassword("${msoPassword}"); +* params.setAaiNamedQueryUUID("${aaiNamedQueryUUID}"); +* params.setAaiPatternMatch(${aaiPatternMatch}); +* params.setNotificationTopic("${notificationTopic}"); +* params.setAppcTopic("${appcTopic}"); +* // +* // This stays in memory as long as the rule is alive and running +* // +* insert(params); +*end +*/ +/* +* +* This rule responds to DCAE Events +* +*/ +rule "${policyName}.EVENT" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + not ( EventManager( closedLoopControlName == $event.closedLoopControlName )) + then + System.out.println("rule EVENT is triggered."); + try { + // + // Check the requestID in the event to make sure it is not null before we create the EventManager. + // The EventManager will do extra syntax checking as well check if the closed loop is disabled/ + // + if ($event.requestID == null) { + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.from = "policy"; + notification.message = "Missing requestID from DCAE event"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + // + // Retract it from memory + // + retract($event); + System.out.println("Event with requestID=null has been retracted."); + } else { + // + // Create an EventManager + // + EventManager manager = new EventManager($params.getClosedLoopControlName(), $event.requestID, $event.target); + // + // Determine if EventManager can actively process the event (i.e. syntax) + // + VirtualControlLoopNotification notification = manager.activate($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Are we actively pursuing this event? + // + if (notification.notification == ControlLoopNotificationType.ACTIVE) { + // + // Insert Event Manager into memory, this will now kick off processing. + // + insert(manager); + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + } else { + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + // + // Retract it from memory + // + retract($event); + } + // + // Now that the manager is inserted into Drools working memory, we'll wait for + // another rule to fire in order to continue processing. This way we can also + // then screen for additional ONSET and ABATED events for this same RequestIDs + // and for different RequestIDs but with the same closedLoopControlName and target. + // + } + // + } catch (Exception e) { + e.printStackTrace(); + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + // Retract the event + // + retract($event); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager +* is created. We can start the operations for this closed loop. +* +*/ +rule "${policyName}.EVENT.MANAGER" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName, controlLoopResult == null) + then + System.out.println("rule EVENT.MANAGER is triggered."); + // + // Check which event this is. + // + EventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event); + // + // We only want the initial ONSET event in memory, + // all the other events need to be retracted to support + // cleanup and avoid the other rules being fired for this event. + // + if (eventStatus != EventManager.NEW_EVENT_STATUS.FIRST_ONSET) { + System.out.println("Retracting "+eventStatus+" Event."); + retract($event); + return; + } + // + // Now the event in memory is first onset event + // + try { + // + // Pull the known AAI field from the Event + // + // generic-vnf is needed for vFirewall case + // vserver-name is needed for vLoadBalancer case + // + String genericVNF = $event.AAI.get("generic-vnf.vnf-id"); + String vserver = $event.AAI.get("vserver.vserver-name"); + // + // Check if we are implementing a simple pattern match. + // + if ($params.getAaiPatternMatch() == 1) { + // + // Yes + // + //Basic naming characteristics: + //VF Name (9 char)+VM name (13 char total)+VFC (19 char total) + //Example: + //VF Name (9 characters): cscf0001v + //VM Name(13 characters): cscf0001vm001 + //VFC name(19 characters): cscf0001vm001cfg001 + // + // zdfw1fwl01fwl02 or zdfw1fwl01fwl01 + // replaced with + // zdfw1fwl01pgn02 or zdfw1fwl01pgn01 + // + int index = genericVNF.lastIndexOf("fwl"); + if (index == -1) { + System.err.println("The generic-vnf.vnf-id from DCAE Event is not valid."); + } else { + genericVNF = genericVNF.substring(0, index) + "pgn" + genericVNF.substring(index+"fwl".length()); + } + // + // Construct an APPC request + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "ModifyConfig"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // insert operationWrapper into memory + // + insert(operationWrapper); + // + Request request = new Request(); + request.CommonHeader = new CommonHeader(); + request.CommonHeader.RequestID = $event.requestID; + request.Action = operation.operation; + request.Payload = new HashMap<String, Object>(); + // + // Fill in the payload + // + request.Payload.put("generic-vnf.vnf-id", genericVNF); + // + PGRequest pgRequest = new PGRequest(); + pgRequest.pgStreams = new PGStreams(); + + PGStream pgStream; + for(int i = 0; i < 5; i++){ + pgStream = new PGStream(); + pgStream.streamId = "fw_udp"+(i+1); + pgStream.isEnabled = "true"; + pgRequest.pgStreams.pgStream.add(pgStream); + } + request.Payload.put("pg-streams", pgRequest.pgStreams); + + if (request != null) { + // + // Insert request into memory + // + insert(request); + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + // message and history ?? + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Now send the operation request + // + if (request instanceof Request) { + try { + System.out.println("APPC request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + PolicyEngine.manager.deliver($params.getAppcTopic(), request); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver request: " + request); + } + } + } else { + // + // what happens if it is null + // + } + // + } else { + // + // create AAI named-query request with UUID started with "F199" + // + AAINQF199Request aainqf199request = new AAINQF199Request(); + AAINQF199QueryParameters aainqf199queryparam = new AAINQF199QueryParameters(); + AAINQF199NamedQuery aainqf199namedquery = new AAINQF199NamedQuery(); + AAINQF199InstanceFilters aainqf199instancefilter = new AAINQF199InstanceFilters(); + // + // queryParameters + // + aainqf199namedquery.namedQueryUUID = UUID.fromString($params.getAaiNamedQueryUUID()); + aainqf199queryparam.namedQuery = aainqf199namedquery; + aainqf199request.queryParameters = aainqf199queryparam; + // + // instanceFilters + // + Map aainqf199instancefiltermap = new HashMap(); + Map aainqf199instancefiltermapitem = new HashMap(); + aainqf199instancefiltermapitem.put("vserver-name", vserver); + aainqf199instancefiltermap.put("vserver", aainqf199instancefiltermapitem); + aainqf199instancefilter.instanceFilter.add(aainqf199instancefiltermap); + aainqf199request.instanceFilters = aainqf199instancefilter; + // + // print aainqf199request for debug + // + System.out.println("AAI Request sent:"); + System.out.println(Serialization.gsonPretty.toJson(aainqf199request)); + // + // Create AAINQF199RequestWrapper + // + AAINQF199RequestWrapper aainqf199RequestWrapper = new AAINQF199RequestWrapper($event.requestID, aainqf199request); + // + // insert aainqf199request into memory + // + insert(aainqf199RequestWrapper); + } + // + } catch (Exception e) { + e.printStackTrace(); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled, an Event Manager +* is created, AAI Manager and AAI Request are ready in memory. We can start sending query to AAI and then wait for response. +* +*/ +rule "${policyName}.EVENT.MANAGER.AAINQF199REQUEST" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) + $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID) + then + System.out.println("rule EVENT.MANAGER.AAINQF199REQUEST is triggered."); + // + // send the request + // + AAINQF199Response aainqf199response = AAINQF199Manager.postQuery($params.getAaiURL(), $params.getAaiUsername(), $params.getAaiPassword(), + $aainqf199RequestWrapper.aainqf199request, $event.requestID); + // + // Check AAI response + // + if (aainqf199response == null) { + System.err.println("Failed to get AAI response"); + // + // Fail and retract everything + // + retract($event); + retract($manager); + retract($aainqf199RequestWrapper); + } else { + // + // Create AAINQF199ResponseWrapper + // + AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper($event.requestID, aainqf199response); + // + // insert aainqf199ResponseWrapper to memeory + // + insert(aainqf199ResponseWrapper); + } +end + +/* +* +* This rule happens when we got a valid AAI response. We can start sending request to APPC or MSO now. +* +*/ +rule "${policyName}.EVENT.MANAGER.AAINQF199RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) + $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID) + $aainqf199ResponseWrapper : AAINQF199ResponseWrapper(requestID == $event.requestID) + then + System.out.println("rule EVENT.MANAGER.AAINQF199RESPONSE is triggered."); + // + // Extract related fields out of AAINQF199RESPONSE + // + String vnfItemVnfId, vnfItemVnfType, vnfItemPersonaModelId, vnfItemPersonaModelVersion, vnfItemModelName, + vnfItemModelVersion, vnfItemModelNameVersionId, serviceItemServiceInstanceId, serviceItemPersonaModelId, + serviceItemModelName, serviceItemModelType, serviceItemModelVersion, serviceItemModelNameVersionId, + vfModuleItemVfModuleName, vfModuleItemPersonaModelId, vfModuleItemPersonaModelVersion, vfModuleItemModelName, + vfModuleItemModelNameVersionId, tenantItemTenantId, cloudRegionItemCloudRegionId; + try { + // + // vnfItem + // + vnfItemVnfId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID; + vnfItemVnfType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType; + vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf("/")+1); + vnfItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId; + vnfItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion; + vnfItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; + vnfItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(2).propertyValue; + vnfItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; + // + // serviceItem + // + serviceItemServiceInstanceId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID; + serviceItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId; + serviceItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; + serviceItemModelType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(1).propertyValue; + serviceItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion; + serviceItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; + // + // Find the index for base vf module and non-base vf module + // + int baseIndex = -1; + int nonBaseIndex = -1; + List<AAINQF199InventoryResponseItem> inventoryItems = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems; + for (AAINQF199InventoryResponseItem m : inventoryItems) { + if (m.vfModule != null && m.vfModule.isBaseVfModule == true) { + baseIndex = inventoryItems.indexOf(m); + } else if (m.vfModule != null && m.vfModule.isBaseVfModule == false && m.vfModule.orchestrationStatus == null) { + nonBaseIndex = inventoryItems.indexOf(m); + } + // + if (baseIndex != -1 && nonBaseIndex != -1) { + break; + } + } + // + // Report the error if either base vf module or non-base vf module is not found + // + if (baseIndex == -1 || nonBaseIndex == -1) { + System.err.println("Either base or non-base vf module is not found from AAI response."); + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // This comes from the base module + // + vfModuleItemVfModuleName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(baseIndex).vfModule.vfModuleName; + vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace("Vfmodule", "vDNS"); + // + // vfModuleItem - NOT the base module + // + vfModuleItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelId; + vfModuleItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelVersion; + vfModuleItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(0).propertyValue; + vfModuleItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(4).propertyValue; + // + // tenantItem + // + tenantItemTenantId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId; + // + // cloudRegionItem + // + cloudRegionItemCloudRegionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId; + // + } catch (Exception e) { + e.printStackTrace(); + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + notification.message = "Invalid named-query response from AAI"; + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + // Retract everything + // + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // Extracted fields should not be null + // + if ((vnfItemVnfId == null) || (vnfItemVnfType == null) || + (vnfItemPersonaModelId == null) || (vnfItemModelName == null) || + (vnfItemModelVersion == null) || (vnfItemModelNameVersionId == null) || + (serviceItemServiceInstanceId == null) || (serviceItemModelName == null) || + (serviceItemModelType == null) || (serviceItemModelVersion == null) || + (serviceItemModelNameVersionId == null) || (vfModuleItemVfModuleName == null) || + (vfModuleItemPersonaModelId == null) || (vfModuleItemPersonaModelVersion == null) || + (vfModuleItemModelName == null) || (vfModuleItemModelNameVersionId == null) || + (tenantItemTenantId == null) || (cloudRegionItemCloudRegionId == null)) { + // + System.err.println("some fields are missing from AAI response."); + // + // Fail and retract everything + // + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // We don't need them any more + // + retract($aainqf199ResponseWrapper); + retract($aainqf199RequestWrapper); + // + // check the actor of this closed loop + // + switch ($params.getActor()) { + case "APPC": + { + // + // Construct an APPC request + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "ModifyConfig"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // insert operationWrapper into memory + // + insert(operationWrapper); + // + Request request = new Request(); + request.CommonHeader = new CommonHeader(); + request.CommonHeader.RequestID = $event.requestID; + request.Action = operation.operation; + request.Payload = new HashMap<String, Object>(); + // + // Fill in the payload + // Hardcode genericVNF for now since AAI has not been ready for vFirewall demo case + // + String genericVNF = "zdfw1fwl01pgn02"; + request.Payload.put("generic-vnf.vnf-id", genericVNF); + // + PGRequest pgRequest = new PGRequest(); + pgRequest.pgStreams = new PGStreams(); + + PGStream pgStream; + for(int i = 0; i < 5; i++){ + pgStream = new PGStream(); + pgStream.streamId = "fw_udp"+(i+1); + pgStream.isEnabled = "true"; + pgRequest.pgStreams.pgStream.add(pgStream); + } + request.Payload.put("pg-streams", pgRequest.pgStreams); + + if (request != null) { + // + // Insert request into memory + // + insert(request); + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + // message and history ?? + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Now send the operation request + // + if (request instanceof Request) { + try { + System.out.println("APPC request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + PolicyEngine.manager.deliver($params.getAppcTopic(), request); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver request: " + request); + } + } + } else { + // + // what happens if it is null + // + } + } + break; + case "MSO": + { + // + // Construct an operation + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "createModuleInstance"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // Construct an MSO request + // + MSORequest request = new MSORequest(); + request.requestDetails = new MSORequestDetails(); + request.requestDetails.modelInfo = new MSOModelInfo(); + request.requestDetails.cloudConfiguration = new MSOCloudConfiguration(); + request.requestDetails.requestInfo = new MSORequestInfo(); + request.requestDetails.requestParameters = new MSORequestParameters(); + request.requestDetails.requestParameters.userParams = null; + // + // cloudConfiguration + // + request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId; + request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId; + // + // modelInfo + // + request.requestDetails.modelInfo.modelType = "vfModule"; + request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId; + request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId; + request.requestDetails.modelInfo.modelName = vfModuleItemModelName; + request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion; + // + // requestInfo + // + request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName; + request.requestDetails.requestInfo.source = "POLICY"; + request.requestDetails.requestInfo.suppressRollback = false; + // + // relatedInstanceList + // + MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement(); + MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement(); + relatedInstanceListElement1.relatedInstance = new MSORelatedInstance(); + relatedInstanceListElement2.relatedInstance = new MSORelatedInstance(); + // + relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId; + relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement1.relatedInstance.modelInfo.modelType = "service"; + relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId; + relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId; + relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName; + relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion; + // + relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId; + relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement2.relatedInstance.modelInfo.modelType = "vnf"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId; + relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId; + relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName; + relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemModelVersion; + relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType; + // + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1); + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2); + // + // print MSO request for debug + // + System.out.println("MSO request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + // + // + // + if (request != null) { + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Concatenate serviceItemServiceInstanceId and vnfItemVnfId to msoURL + // + String MSOUrl = $params.getMsoURL() + "/serviceInstances/v2/" + serviceItemServiceInstanceId + "/vnfs/" + vnfItemVnfId + "/vfModules"; + // + // Call MSO + // + MSOResponse response = MSOManager.createModuleInstance(MSOUrl, $params.getMsoURL(), $params.getMsoUsername(), $params.getMsoPassword(), request); + // + if (response != null) { + // + // Assign requestId + // + request.requestId = $event.requestID.toString(); + response.request.requestId = $event.requestID.toString(); + // + // Insert facts + // + insert(operationWrapper); + insert(request); + insert(response); + } else { + // + // MSO request not even accepted + // + notification.message = operationWrapper.operation.toMessage(); + operationWrapper.operation.message = operationWrapper.operation.toMessage(); + operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + notification.history.add(operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Retract everything + // + retract($event); + retract($manager); + } + } else { + System.err.println("constructed MSO request is invalid."); + } + } + break; + } +end + +/* +* +* This rule responds to APPC Response Events +* +*/ +rule "${policyName}.APPC.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) + $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID ) + $request : Request( getCommonHeader().RequestID == $event.requestID ) + $response : Response( getCommonHeader().RequestID == $event.requestID ) + then + System.out.println("rule APPC.RESPONSE is triggered."); + if ($response.Status == null) { + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + } + // + // Get the Response Code + // + ResponseCode code = ResponseCode.toResponseCode($response.Status.Code); + if (code == null) { + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + } + // + // Construct notification + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operationWrapper.operation.toMessage(); + $operationWrapper.operation.message = $operationWrapper.operation.toMessage(); + // + // Ok, let's figure out what APP-C's response is + // + switch (code) { + case ACCEPT: + $operationWrapper.operation.outcome = "PROCESSING"; + break; + case ERROR: + case REJECT: + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + break; + case SUCCESS: + $operationWrapper.operation.outcome = "SUCCESS"; + $manager.setControlLoopResult("SUCCESS"); + break; + case FAILURE: + $operationWrapper.operation.outcome = "FAILURE"; + $manager.setControlLoopResult("FAILURE"); + break; + } + if ($operationWrapper.operation.outcome.equals("SUCCESS")) { + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } else if ($operationWrapper.operation.outcome.equals("PROCESSING")) { + retract($response); + } else { + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } + +end + +/* +* +* This rule is used to clean up APPC response +* +*/ +rule "${policyName}.APPC.RESPONSE.CLEANUP" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $response : Response($id : getCommonHeader().RequestID ) + not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) + then + System.out.println("rule APPC.RESPONSE.CLEANUP is triggered."); + retract($response); +end + +/* +* +* This rule responds to MSO Response Events +* +*/ +rule "${policyName}.MSO.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) + $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID ) + $request : MSORequest( requestId == $event.requestID.toString() ) + $response : MSOResponse( request.requestId == $event.requestID.toString() ) + then + System.out.println("rule MSO.RESPONSE is triggered."); + // + // Construct notification + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operationWrapper.operation.toMessage(); + $operationWrapper.operation.message = $operationWrapper.operation.toMessage(); + // + // The operation can either be succeeded or failed + // + if($response.request.requestStatus.requestState.equals("Completed")) { + $operationWrapper.operation.outcome = "SUCCESS"; + $manager.setControlLoopResult("SUCCESS"); + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } else { + $operationWrapper.operation.outcome = "FAILURE"; + $manager.setControlLoopResult("FAILURE"); + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } + +end |