diff options
Diffstat (limited to 'ECOMP-PDP-REST/src/main/java/org')
25 files changed, 673 insertions, 204 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; } + } |