X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=PolicyEngineAPI%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fpolicy%2Fstd%2FStdPolicyEngine.java;h=f09b5779ccaca16922dc8becb8e19e621b80eca6;hb=b63b7672e6ba731c53198c69309c0d8e9ee7f138;hp=bef9641743ba67a6b3ae450fb7f995ae38cf2e93;hpb=ed2bcd773ec3dbe07311bad597ec664c4e38c009;p=policy%2Fengine.git diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java index bef964174..f09b5779c 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * PolicyEngineAPI * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,14 +20,53 @@ package org.onap.policy.std; -import java.io.FileInputStream; +import static org.onap.policy.std.utils.PolicyConfigConstants.BAD_REQUEST_STATUS_CODE; +import static org.onap.policy.std.utils.PolicyConfigConstants.CLIENT_ID_PROP_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.CLIENT_KEY_PROP_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.COMMA; +import static org.onap.policy.std.utils.PolicyConfigConstants.CREATE_DICTIONARY_ITEM_RESOURCE_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.CREATE_POLICY_RESOURCE_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.DATE_FORMAT; +import static org.onap.policy.std.utils.PolicyConfigConstants.DEFAULT_NOTIFICATION; +import static org.onap.policy.std.utils.PolicyConfigConstants.DELETE_POLICY_RESOURCE_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.DMAAP; +import static org.onap.policy.std.utils.PolicyConfigConstants.ENVIRONMENT_PROP_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.ERROR_AUTH_GET_PERM; +import static org.onap.policy.std.utils.PolicyConfigConstants.ERROR_DATA_ISSUE; +import static org.onap.policy.std.utils.PolicyConfigConstants.ERROR_INVALID_PDPS; +import static org.onap.policy.std.utils.PolicyConfigConstants.ERROR_WHILE_CONNECTING; +import static org.onap.policy.std.utils.PolicyConfigConstants.GET_CONFIG_RESOURCE_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.GET_DECISION_RESOURCE_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.GET_DICTIONARY_ITEMS_RESOURCE_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.GET_METRICS_RESOURCE_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.HTTP; +import static org.onap.policy.std.utils.PolicyConfigConstants.JUNIT_PROP_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.NOTIFICATION_SERVERS_PROP_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.NOTIFICATION_TOPIC_PROP_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.NOTIFICATION_TYPE_PROP_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.PDP_URL_PROP_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.PDP_VALUE_REGEX; +import static org.onap.policy.std.utils.PolicyConfigConstants.PE300; +import static org.onap.policy.std.utils.PolicyConfigConstants.POLICY_ENGINE_IMPORT_RESOURCE_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.PUSH_POLICY_RESOURCE_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.REGEX; +import static org.onap.policy.std.utils.PolicyConfigConstants.SEMICOLLON; +import static org.onap.policy.std.utils.PolicyConfigConstants.SEND_EVENT_RESOURCE_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.TEST_POLICY_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.UEB; +import static org.onap.policy.std.utils.PolicyConfigConstants.UEB_API_KEY_PROP_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.UEB_API_SECRET_PROP_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.UNAUTHORIZED_STATUS_CODE; +import static org.onap.policy.std.utils.PolicyConfigConstants.UPDATE_DICTIONARY_ITEM_RESOURCE_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.UPDATE_POLICY_RESOURCE_NAME; +import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStream; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.ParseException; @@ -37,18 +76,17 @@ import java.util.Arrays; import java.util.Base64; import java.util.Collection; import java.util.Collections; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; - import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; - import org.onap.policy.api.AttributeType; import org.onap.policy.api.ConfigRequestParameters; import org.onap.policy.api.DecisionRequestParameters; @@ -80,6 +118,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.models.APIDictionaryResponse; import org.onap.policy.models.APIPolicyConfigResponse; +import org.onap.policy.std.utils.PolicyCommonConfigConstants; import org.onap.policy.utils.AAFEnvironment; import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; @@ -94,7 +133,6 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import org.xml.sax.InputSource; - import com.fasterxml.jackson.core.JsonProcessingException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -105,13 +143,7 @@ import com.google.gson.GsonBuilder; * @version 1.0 */ public class StdPolicyEngine { - private static final String ERROR_AUTH_GET_PERM = "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to: "; - private static final String DEFAULT_NOTIFICATION = "websocket"; - private static final String ERROR_DATA_ISSUE = "Invalid Data is given."; - private static final String DMAAP = "dmaap"; - private static final String ERROR_INVALID_PDPS = "Unable to get valid Response from PDP(s) "; - private static final String ERROR_WHILE_CONNECTING = "Error while connecting to "; - + private static String clientEncoding = null; private String contentType = null; private static List pdps = null; @@ -140,19 +172,26 @@ public class StdPolicyEngine { /* * Taking the Property file even if it null. */ - public StdPolicyEngine(String propertyFilePath, String clientKey) throws PolicyEngineException { + public StdPolicyEngine(final String propertyFilePath, final String clientKey) throws PolicyEngineException { setProperty(propertyFilePath, clientKey); } + + /* + * Taking the Property structure even if it null. + */ + public StdPolicyEngine(final Properties properties, final String clientKey) throws PolicyEngineException { + setProperty(properties, clientKey); + } /* * Taking the Notification Constructor. */ - public StdPolicyEngine(String propertyFilePath, NotificationScheme scheme, NotificationHandler handler) - throws PolicyEngineException { + public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme, + final NotificationHandler handler) throws PolicyEngineException { setProperty(propertyFilePath, null); this.scheme = scheme; this.handler = handler; - if ((!"ueb".equals(notificationType.get(0))) || (!DMAAP.equals(notificationType.get(0)))) { + if ((!UEB.equals(notificationType.get(0))) || (!DMAAP.equals(notificationType.get(0)))) { AutoClientEnd.setAuto(scheme, handler); } notification(scheme, handler); @@ -161,7 +200,8 @@ public class StdPolicyEngine { /* * Taking the Notification Constructor. */ - public StdPolicyEngine(String propertyFilePath, NotificationScheme scheme) throws PolicyEngineException { + public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme) + throws PolicyEngineException { setProperty(propertyFilePath, null); this.scheme = scheme; setScheme(scheme); @@ -170,7 +210,7 @@ public class StdPolicyEngine { /* * sendEvent API Implementation */ - public Collection sendEvent(Map eventAttributes, UUID requestID) + public Collection sendEvent(final Map eventAttributes, final UUID requestID) throws PolicyEventException { return sendEventImpl(eventAttributes, requestID); } @@ -178,10 +218,10 @@ public class StdPolicyEngine { /* * sendEvent API Implementation for eventRequestParameters */ - public Collection sendEvent(EventRequestParameters eventRequestParameters) + public Collection sendEvent(final EventRequestParameters eventRequestParameters) throws PolicyEventException { if (eventRequestParameters == null) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Request Parameters Given. "; + final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Request Parameters Given. "; LOGGER.error(message); throw new PolicyEventException(message); } @@ -191,7 +231,7 @@ public class StdPolicyEngine { /* * getConfig using configRequestParameters Implementation */ - public Collection getConfig(ConfigRequestParameters configRequestParameters) + public Collection getConfig(final ConfigRequestParameters configRequestParameters) throws PolicyConfigException { return getConfigImpl(configRequestParameters); } @@ -199,7 +239,7 @@ public class StdPolicyEngine { /* * listPolicies using configRequestParameters Implementation */ - public Collection listConfig(ConfigRequestParameters listPolicyRequestParameters) + public Collection listConfig(final ConfigRequestParameters listPolicyRequestParameters) throws PolicyConfigException { return listConfigImpl(listPolicyRequestParameters); } @@ -207,18 +247,18 @@ public class StdPolicyEngine { /* * getDecision using the decision Attributes. */ - public DecisionResponse getDecision(String onapName, Map decisionAttributes, UUID requestID) - throws PolicyDecisionException { + public DecisionResponse getDecision(final String onapName, final Map decisionAttributes, + final UUID requestID) throws PolicyDecisionException { return getDecisionImpl(onapName, decisionAttributes, requestID); } /* * getDecision Using decisionRequestParameters. */ - public DecisionResponse getDecision(DecisionRequestParameters decisionRequestParameters) + public DecisionResponse getDecision(final DecisionRequestParameters decisionRequestParameters) throws PolicyDecisionException { if (decisionRequestParameters == null) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Parameters Given. "; + final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Parameters Given. "; LOGGER.error(message); throw new PolicyDecisionException(message); } @@ -229,104 +269,104 @@ public class StdPolicyEngine { /* * getMetrics using metricsRequestParameters */ - public MetricsResponse getMetrics(MetricsRequestParameters parameters) throws PolicyException { + public MetricsResponse getMetrics(final MetricsRequestParameters parameters) throws PolicyException { return getMetricsImpl(parameters); } - public MetricsResponse getMetricsImpl(MetricsRequestParameters parameters) throws PolicyException { - StdMetricsResponse response = new StdMetricsResponse(); - String resource = "getMetrics"; + public MetricsResponse getMetricsImpl(final MetricsRequestParameters parameters) throws PolicyException { String body = null; // Create the Request try { if (parameters != null) { body = PolicyUtils.objectToJsonString(parameters); } - } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + } catch (final JsonProcessingException jsonProcessingException) { + final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException; LOGGER.error(message); - throw new PolicyException(message, e); + throw new PolicyException(message, jsonProcessingException); } + + final StdMetricsResponse response = new StdMetricsResponse(); // Get Response. try { - ResponseEntity result = callNewPDP(resource, HttpMethod.GET, body, String.class); + final ResponseEntity result = + callNewPDP(GET_METRICS_RESOURCE_NAME, HttpMethod.GET, body, String.class); // Process response response.setResponseMessage(result.getBody()); response.setResponseCode(result.getStatusCode().value()); - } catch (PolicyException exception) { + return response; + } catch (final PolicyException exception) { if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) { LOGGER.error(exception); - HttpClientErrorException ex = (HttpClientErrorException) exception.getCause(); + final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause(); response.setResponseCode(ex.getRawStatusCode()); response.setResponseMessage(exception.getMessage()); return response; - } else { - String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "Error while processing results. please check logs."; - LOGGER.error(message, exception); - throw new PolicyException(message, exception); } + final String message = + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs."; + LOGGER.error(message, exception); + throw new PolicyException(message, exception); } - return response; } /* * PushPolicy using pushPolicyParameters. */ - public PolicyChangeResponse pushPolicy(PushPolicyParameters pushPolicyParameters) throws PolicyException { + public PolicyChangeResponse pushPolicy(final PushPolicyParameters pushPolicyParameters) throws PolicyException { return pushPolicyImpl(pushPolicyParameters); } - public PolicyChangeResponse pushPolicyImpl(PushPolicyParameters pushPolicyParameters) throws PolicyException { - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - String resource = "pushPolicy"; + public PolicyChangeResponse pushPolicyImpl(final PushPolicyParameters pushPolicyParameters) throws PolicyException { + final StdPolicyChangeResponse response = new StdPolicyChangeResponse(); String body = null; // Create Request. try { body = PolicyUtils.objectToJsonString(pushPolicyParameters); - } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + } catch (final JsonProcessingException e) { + final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyException(message, e); } // Get Response. try { - ResponseEntity result = callNewPDP(resource, HttpMethod.PUT, body, String.class); + final ResponseEntity result = + callNewPDP(PUSH_POLICY_RESOURCE_NAME, HttpMethod.PUT, body, String.class); // Process response response.setResponseMessage(result.getBody()); response.setResponseCode(result.getStatusCode().value()); - } catch (PolicyException exception) { + return response; + } catch (final PolicyException exception) { return processException(exception); } - return response; } /* * Delete a Policy using deletePolicyParameters */ - public PolicyChangeResponse deletePolicy(DeletePolicyParameters parameters) throws PolicyException { + public PolicyChangeResponse deletePolicy(final DeletePolicyParameters parameters) throws PolicyException { return deletePolicyImpl(parameters); } - public PolicyChangeResponse deletePolicyImpl(DeletePolicyParameters parameters) throws PolicyException { - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - String resource = "deletePolicy"; + public PolicyChangeResponse deletePolicyImpl(final DeletePolicyParameters parameters) throws PolicyException { + final StdPolicyChangeResponse response = new StdPolicyChangeResponse(); String body = null; // Create Request. try { body = PolicyUtils.objectToJsonString(parameters); - } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + } catch (final JsonProcessingException e) { + final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyException(message, e); } // Get Response. try { - ResponseEntity result = callNewPDP(resource, HttpMethod.DELETE, body, String.class); + final ResponseEntity result = + callNewPDP(DELETE_POLICY_RESOURCE_NAME, HttpMethod.DELETE, body, String.class); // Process response response.setResponseMessage(result.getBody()); response.setResponseCode(result.getStatusCode().value()); - } catch (PolicyException exception) { + } catch (final PolicyException exception) { return processException(exception); } return response; @@ -335,65 +375,63 @@ public class StdPolicyEngine { /* * getDictionaryItem Using dictionaryParameters */ - public DictionaryResponse getDictionaryItem(DictionaryParameters parameters) throws PolicyException { + public DictionaryResponse getDictionaryItem(final DictionaryParameters parameters) throws PolicyException { return getDictionaryItemImpl(parameters); } - public DictionaryResponse getDictionaryItemImpl(DictionaryParameters parameters) throws PolicyException { - StdDictionaryResponse response = new StdDictionaryResponse(); - String resource = "getDictionaryItems"; + public DictionaryResponse getDictionaryItemImpl(final DictionaryParameters parameters) throws PolicyException { + final StdDictionaryResponse response = new StdDictionaryResponse(); String body = "{}"; // Create Request. try { body = PolicyUtils.objectToJsonString(parameters); - } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + } catch (final JsonProcessingException e) { + final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyException(message, e); } // Get Response. try { - ResponseEntity result = callNewPDP(resource, HttpMethod.POST, body, - APIDictionaryResponse.class); + final ResponseEntity result = + callNewPDP(GET_DICTIONARY_ITEMS_RESOURCE_NAME, HttpMethod.POST, body, APIDictionaryResponse.class); // Process response - response = dictionaryResult(result.getBody()); - } catch (Exception exception) { - if (exception.getCause().getMessage().contains("401")) { - String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource; + return dictionaryResult(result.getBody()); + } catch (final Exception exception) { + if (exception.getCause().getMessage().contains(UNAUTHORIZED_STATUS_CODE)) { + final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + + GET_DICTIONARY_ITEMS_RESOURCE_NAME; LOGGER.error(message); response.setResponseMessage(message); - response.setResponseCode(401); + response.setResponseCode(HttpStatus.UNAUTHORIZED.value()); return response; } - if (exception.getCause().getMessage().contains("400")) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE; + if (exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) { + final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE; response.setResponseMessage(message); - response.setResponseCode(400); + response.setResponseCode(HttpStatus.BAD_REQUEST.value()); return response; } - String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS - + pdps; + final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps; LOGGER.error(message, exception); response.setResponseMessage(message); - response.setResponseCode(500); + response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); return response; } - return response; } @SuppressWarnings("unchecked") - private StdDictionaryResponse dictionaryResult(APIDictionaryResponse body) { - StdDictionaryResponse response = new StdDictionaryResponse(); + private StdDictionaryResponse dictionaryResult(final APIDictionaryResponse body) { + final StdDictionaryResponse response = new StdDictionaryResponse(); response.setResponseCode(body.getResponseCode()); response.setResponseMessage(body.getResponseMessage()); response.setDictionaryData((Map) body.getDictionaryData()); if (body.getDictionaryJson() != null) { - Gson objGson = new GsonBuilder().create(); - String mapToJson = objGson.toJson(body.getDictionaryJson()); - JsonReader jsonReader = Json.createReader(new StringReader(mapToJson)); - JsonObject object = jsonReader.readObject(); - jsonReader.close(); - response.setDictionaryJson(object); + final Gson objGson = new GsonBuilder().create(); + final String mapToJson = objGson.toJson(body.getDictionaryJson()); + try (final JsonReader jsonReader = Json.createReader(new StringReader(mapToJson));) { + final JsonObject object = jsonReader.readObject(); + response.setDictionaryJson(object); + } } return response; } @@ -401,262 +439,240 @@ public class StdPolicyEngine { /* * createDictinaryItem Using dictionaryParameters. */ - public PolicyChangeResponse createDictionaryItem(DictionaryParameters parameters) throws PolicyException { + public PolicyChangeResponse createDictionaryItem(final DictionaryParameters parameters) throws PolicyException { return createUpdateDictionaryItemImpl(parameters, false); } /* * updateDictinaryItem Using dictionaryParameters. */ - public PolicyChangeResponse updateDictionaryItem(DictionaryParameters parameters) throws PolicyException { + public PolicyChangeResponse updateDictionaryItem(final DictionaryParameters parameters) throws PolicyException { return createUpdateDictionaryItemImpl(parameters, true); } - public PolicyChangeResponse createUpdateDictionaryItemImpl(DictionaryParameters parameters, boolean updateFlag) - throws PolicyException { - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - String resource = "createDictionaryItem"; - if (updateFlag) { - resource = "updateDictionaryItem"; - } + public PolicyChangeResponse createUpdateDictionaryItemImpl(final DictionaryParameters parameters, + final boolean updateFlag) throws PolicyException { + + final String resource = getDictionaryResouceName(updateFlag); String body = null; // Create Request. try { body = PolicyUtils.objectToJsonString(parameters); - } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + } catch (final JsonProcessingException jsonProcessingException) { + final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException; LOGGER.error(message); - throw new PolicyException(message, e); + throw new PolicyException(message, jsonProcessingException); } // Get Response. try { - ResponseEntity result = callNewPDP(resource, HttpMethod.PUT, body, String.class); + final StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + final ResponseEntity result = callNewPDP(resource, HttpMethod.PUT, body, String.class); // Process response response.setResponseMessage(result.getBody()); response.setResponseCode(result.getStatusCode().value()); - } catch (PolicyException exception) { + return response; + } catch (final PolicyException exception) { return processException(exception); } - return response; + } + + private String getDictionaryResouceName(final boolean updateFlag) { + return updateFlag ? UPDATE_DICTIONARY_ITEM_RESOURCE_NAME : CREATE_DICTIONARY_ITEM_RESOURCE_NAME; } /* * PolicyEngine Import */ - public PolicyChangeResponse policyEngineImport(ImportParameters importParameters) throws PolicyException { + public PolicyChangeResponse policyEngineImport(final ImportParameters importParameters) throws PolicyException { return policyEngineImportImpl(importParameters); } - public PolicyChangeResponse policyEngineImportImpl(ImportParameters importParameters) throws PolicyException { - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - String resource = "policyEngineImport"; - LinkedMultiValueMap parameters = new LinkedMultiValueMap<>(); + public PolicyChangeResponse policyEngineImportImpl(final ImportParameters importParameters) throws PolicyException { + final LinkedMultiValueMap parameters = new LinkedMultiValueMap<>(); // Create Request. try { - String body = PolicyUtils.objectToJsonString(importParameters); + final String body = PolicyUtils.objectToJsonString(importParameters); parameters.set("importParametersJson", body); parameters.set("file", new FileSystemResource(importParameters.getFilePath())); - } catch (Exception e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + } catch (final Exception e) { + final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyException(message, e); } contentType = MediaType.MULTIPART_FORM_DATA_VALUE; // Get Response. try { - ResponseEntity result = callNewPDP(resource, HttpMethod.POST, parameters, String.class); + final StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + final ResponseEntity result = + callNewPDP(POLICY_ENGINE_IMPORT_RESOURCE_NAME, HttpMethod.POST, parameters, String.class); // Process response response.setResponseMessage(result.getBody()); response.setResponseCode(result.getStatusCode().value()); - } catch (PolicyException exception) { + return response; + } catch (final PolicyException exception) { return processException(exception); } finally { contentType = null; } - return response; } /* * createPolicy Using policyParameters. */ - public PolicyChangeResponse createPolicy(PolicyParameters policyParameters) throws PolicyException { + public PolicyChangeResponse createPolicy(final PolicyParameters policyParameters) throws PolicyException { return createUpdatePolicyImpl(policyParameters, false); } /* * updatePolicy using policyParameters. */ - public PolicyChangeResponse updatePolicy(PolicyParameters policyParameters) throws PolicyException { + public PolicyChangeResponse updatePolicy(final PolicyParameters policyParameters) throws PolicyException { return createUpdatePolicyImpl(policyParameters, true); } - public PolicyChangeResponse createUpdatePolicyImpl(PolicyParameters policyParameters, boolean updateFlag) - throws PolicyException { - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - String resource = "createPolicy"; - if (updateFlag) { - resource = "updatePolicy"; - } + public PolicyChangeResponse createUpdatePolicyImpl(final PolicyParameters policyParameters, + final boolean updateFlag) throws PolicyException { + final String resource = getPolicyResourceName(updateFlag); String body = null; // Create Request. try { body = PolicyUtils.objectToJsonString(policyParameters); - } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + } catch (final JsonProcessingException e) { + final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyException(message, e); } // Get Response. try { - ResponseEntity result = callNewPDP(resource, HttpMethod.PUT, body, String.class); + final ResponseEntity result = callNewPDP(resource, HttpMethod.PUT, body, String.class); + final StdPolicyChangeResponse response = new StdPolicyChangeResponse(); // Process response response.setResponseMessage(result.getBody()); response.setResponseCode(result.getStatusCode().value()); - } catch (PolicyException exception) { + return response; + } catch (final PolicyException exception) { return processException(exception); } - return response; } - private PolicyChangeResponse processException(PolicyException exception) throws PolicyException { - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + private String getPolicyResourceName(final boolean updateFlag) { + return updateFlag ? UPDATE_POLICY_RESOURCE_NAME : CREATE_POLICY_RESOURCE_NAME; + } + + private PolicyChangeResponse processException(final PolicyException exception) throws PolicyException { + final StdPolicyChangeResponse response = new StdPolicyChangeResponse(); if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) { LOGGER.error(exception); - HttpClientErrorException ex = (HttpClientErrorException) exception.getCause(); + final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause(); response.setResponseCode(ex.getRawStatusCode()); response.setResponseMessage(exception.getMessage()); return response; } else { - String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "Error while processing results. please check logs."; + final String message = + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs."; LOGGER.error(message, exception); throw new PolicyException(message, exception); } } - public DecisionResponse getDecisionImpl(String onapName, Map decisionAttributes, UUID requestID) - throws PolicyDecisionException { - String resource = "getDecision"; - StdDecisionResponse response = new StdDecisionResponse(); + public DecisionResponse getDecisionImpl(final String onapName, final Map decisionAttributes, + final UUID requestID) throws PolicyDecisionException { String body = null; // Create Request. try { - DecisionRequestParameters decisionRequestParameters = new DecisionRequestParameters(); + final DecisionRequestParameters decisionRequestParameters = new DecisionRequestParameters(); decisionRequestParameters.setDecisionAttributes(decisionAttributes); decisionRequestParameters.setOnapName(onapName); decisionRequestParameters.setRequestID(requestID); body = PolicyUtils.objectToJsonString(decisionRequestParameters); - } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + } catch (final JsonProcessingException e) { + final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyDecisionException(message, e); } // Get Response. try { - ResponseEntity result = callNewPDP(resource, HttpMethod.POST, body, - StdDecisionResponse.class); + final ResponseEntity result = + callNewPDP(GET_DECISION_RESOURCE_NAME, HttpMethod.POST, body, StdDecisionResponse.class); // Process response - response = result.getBody(); - } catch (Exception exception) { - if (exception.getCause().getMessage().contains("401")) { - String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource; - LOGGER.error(message); - throw new PolicyDecisionException(message, exception); - } - if (exception.getCause().getMessage().contains("400")) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE; - LOGGER.error(message); - throw new PolicyDecisionException(message, exception); - } - String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS - + pdps; + return result.getBody(); + } catch (final Exception exception) { + final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps; + final String message = getErrorMessage(exception, defaulMessage, GET_DECISION_RESOURCE_NAME); LOGGER.error(message, exception); throw new PolicyDecisionException(message, exception); } - return response; } - public Collection getConfigImpl(ConfigRequestParameters configRequestParameters) + public Collection getConfigImpl(final ConfigRequestParameters configRequestParameters) throws PolicyConfigException { - String resource = "getConfig"; - ArrayList response = null; String body = null; // Create Request. try { body = PolicyUtils.objectToJsonString(configRequestParameters); - } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + } catch (final JsonProcessingException e) { + final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyConfigException(message, e); } // Get Response. try { - ResponseEntity result = callNewPDP(resource, HttpMethod.POST, body, - APIPolicyConfigResponse[].class); + final ResponseEntity result = + callNewPDP(GET_CONFIG_RESOURCE_NAME, HttpMethod.POST, body, APIPolicyConfigResponse[].class); // Process Response - response = configResult(result.getBody()); - } catch (Exception exception) { - if (exception.getCause().getMessage().contains("401")) { - String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource; - LOGGER.error(message); - throw new PolicyConfigException(message, exception); - } - if (exception.getCause().getMessage().contains("400")) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE; - LOGGER.error(message); - throw new PolicyConfigException(message, exception); - } - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_INVALID_PDPS - + pdps; + return configResult(result.getBody()); + } catch (final Exception exception) { + final String defaulMessage = XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_INVALID_PDPS + pdps; + final String message = getErrorMessage(exception, defaulMessage, GET_CONFIG_RESOURCE_NAME); LOGGER.error(message, exception); throw new PolicyConfigException(message, exception); } - return response; } - private ArrayList configResult(APIPolicyConfigResponse[] response) throws PolicyConfigException { - ArrayList result = new ArrayList<>(); - if (response != null && response.length > 0) { - for (APIPolicyConfigResponse policyConfigResponse : response) { - StdPolicyConfig policyConfig = new StdPolicyConfig(); + private ArrayList configResult(final APIPolicyConfigResponse[] response) + throws PolicyConfigException { + final ArrayList result = new ArrayList<>(); + if (response != null) { + for (final APIPolicyConfigResponse policyConfigResponse : response) { + final StdPolicyConfig policyConfig = new StdPolicyConfig(); policyConfig.setConfigStatus(policyConfigResponse.getPolicyConfigMessage()); policyConfig.setMatchingConditions(policyConfigResponse.getMatchingConditions()); policyConfig.setPolicyConfigStatus(policyConfigResponse.getPolicyConfigStatus()); policyConfig.setPolicyName(policyConfigResponse.getPolicyName()); policyConfig.setPolicyType(policyConfigResponse.getType()); policyConfig.setPolicyVersion(policyConfigResponse.getPolicyVersion()); + policyConfig.setPolicyType(policyConfigResponse.getPolicyType()); policyConfig.setResponseAttributes(policyConfigResponse.getResponseAttributes()); setMatches(policyConfig.getMatchingConditions()); if (policyConfigResponse.getType() != null) { try { switch (policyConfigResponse.getType()) { case JSON: - JsonReader jsonReader = Json - .createReader(new StringReader(policyConfigResponse.getConfig())); - JsonObject object = jsonReader.readObject(); - jsonReader.close(); - policyConfig.setJsonObject(object); + final StringReader reader = new StringReader(policyConfigResponse.getConfig()); + try (final JsonReader jsonReader = Json.createReader(reader)) { + final JsonObject object = jsonReader.readObject(); + policyConfig.setJsonObject(object); + } break; case OTHER: policyConfig.setOther(policyConfigResponse.getConfig()); break; case PROPERTIES: - Properties props = new Properties(); + final Properties props = new Properties(); props.putAll(policyConfigResponse.getProperty()); policyConfig.setProperties(props); break; case XML: - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder; - builder = factory.newDocumentBuilder(); - policyConfig.setDocument(builder - .parse(new InputSource(new StringReader(policyConfigResponse.getConfig())))); + final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + final DocumentBuilder builder = factory.newDocumentBuilder(); + final StringReader stringReader = new StringReader(policyConfigResponse.getConfig()); + policyConfig.setDocument(builder.parse(new InputSource(stringReader))); break; } - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e); + } catch (final Exception exception) { + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + exception); throw new PolicyConfigException( - XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the config", e); + XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the config", exception); } } result.add(policyConfig); @@ -665,14 +681,14 @@ public class StdPolicyEngine { return result; } - private void setMatches(Map matchingConditions) { - Matches match = new Matches(); - HashMap configAttributes = new HashMap<>(); + private void setMatches(final Map matchingConditions) { + final Matches match = new Matches(); + final HashMap configAttributes = new HashMap<>(); try { - for (Map.Entry entry : matchingConditions.entrySet()) { - if (entry.getKey().equalsIgnoreCase("ONAPName")) { + for (final Map.Entry entry : matchingConditions.entrySet()) { + if (PolicyCommonConfigConstants.ONAP_NAME.equalsIgnoreCase(entry.getKey())) { match.setOnapName(entry.getValue()); - } else if (entry.getKey().equalsIgnoreCase("ConfigName")) { + } else if (PolicyCommonConfigConstants.CONFIG_NAME.equalsIgnoreCase(entry.getKey())) { match.setConfigName(entry.getValue()); } else { configAttributes.put(entry.getKey(), entry.getValue()); @@ -682,7 +698,7 @@ public class StdPolicyEngine { match.setConfigAttributes(configAttributes); } MatchStore.storeMatch(match); - } catch (Exception e) { + } catch (final Exception e) { LOGGER.error("StoreMatch failed for Onap:" + match.getOnapName() + " Config: " + match.getConfigName(), e); } } @@ -690,20 +706,20 @@ public class StdPolicyEngine { /* * Generic Rest Client to call PDP services. */ - private ResponseEntity callNewPDP(String resource, HttpMethod method, Object body, Class responseType) - throws PolicyException { - RestTemplate restTemplate = new RestTemplate(); - HttpEntity requestEntity = new HttpEntity<>(body, getHeaders()); + ResponseEntity callNewPDP(final String resource, final HttpMethod method, final Object body, + final Class responseType) throws PolicyException { + final RestTemplate restTemplate = new RestTemplate(); + final HttpEntity requestEntity = new HttpEntity<>(body, getHeaders()); ResponseEntity result = null; HttpClientErrorException exception = null; int pdpsCount = 0; while (pdpsCount < pdps.size()) { try { result = restTemplate.exchange(pdps.get(0) + "/api/" + resource, method, requestEntity, responseType); - } catch (HttpClientErrorException e) { + } catch (final HttpClientErrorException e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e); exception = e; - } catch (Exception e) { + } catch (final Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e); exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); } @@ -715,35 +731,33 @@ public class StdPolicyEngine { break; } } - if (exception != null && exception.getStatusCode() != null) { - if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) { - String message = XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" - + ERROR_AUTH_GET_PERM + resource; - LOGGER.error(message); - throw new PolicyException(message, exception); - } - if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":" - + exception.getResponseBodyAsString(); - LOGGER.error(message); - throw new PolicyException(message, exception); - } - if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) { - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps - + exception; - LOGGER.error(message); - throw new PolicyException(message, exception); - } - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":" + if (exception == null || exception.getStatusCode() == null) { + return result; + } + + final String message = getHttpErrorMessage(exception, resource); + LOGGER.error(message); + throw new PolicyException(message, exception); + } + + private String getHttpErrorMessage(final HttpClientErrorException exception, final String resource) { + if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) { + return XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" + ERROR_AUTH_GET_PERM + + resource; + } + if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) { + return XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":" + exception.getResponseBodyAsString(); - LOGGER.error(message); - throw new PolicyException(message, exception); } - return result; + if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) { + return XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps + exception; + } + return XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":" + + exception.getResponseBodyAsString(); } private HttpHeaders getHeaders() { - HttpHeaders headers = new HttpHeaders(); + final HttpHeaders headers = new HttpHeaders(); headers.set("ClientAuth", "Basic " + clientEncoding); headers.set("Authorization", "Basic " + encoding.get(0)); if (contentType != null) { @@ -756,20 +770,20 @@ public class StdPolicyEngine { } private static void setClientEncoding() { - Base64.Encoder encoder = Base64.getEncoder(); + final Base64.Encoder encoder = Base64.getEncoder(); clientEncoding = encoder.encodeToString((userName + ":" + pass).getBytes(StandardCharsets.UTF_8)); } - public Collection listConfigImpl(ConfigRequestParameters listRequestParameters) + public Collection listConfigImpl(final ConfigRequestParameters listRequestParameters) throws PolicyConfigException { - Collection policyList = new ArrayList<>(); + final Collection policyList = new ArrayList<>(); if (junit) { - policyList.add("Policy Name: listConfigTest"); + policyList.add(TEST_POLICY_NAME); return policyList; } - Collection policyConfig = getConfigImpl(listRequestParameters); - for (PolicyConfig policy : policyConfig) { - if (policy.getPolicyConfigMessage() != null && policy.getPolicyConfigMessage().contains("PE300")) { + final Collection policyConfig = getConfigImpl(listRequestParameters); + for (final PolicyConfig policy : policyConfig) { + if (policy.getPolicyConfigMessage() != null && policy.getPolicyConfigMessage().contains(PE300)) { policyList.add(policy.getPolicyConfigMessage()); } else { policyList.add("Policy Name: " + policy.getPolicyName()); @@ -778,204 +792,221 @@ public class StdPolicyEngine { return policyList; } - public Collection sendEventImpl(Map eventAttributes, UUID requestID) + public Collection sendEventImpl(final Map eventAttributes, final UUID requestID) throws PolicyEventException { - String resource = "sendEvent"; - ArrayList response = null; String body = null; // Create Request. try { // Long way here, can be shortened and will be done. - EventRequestParameters eventRequestParameters = new EventRequestParameters(); + final EventRequestParameters eventRequestParameters = new EventRequestParameters(); eventRequestParameters.setEventAttributes(eventAttributes); eventRequestParameters.setRequestID(requestID); body = PolicyUtils.objectToJsonString(eventRequestParameters); - } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + } catch (final JsonProcessingException e) { + final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyEventException(message, e); } // Get Response. try { - ResponseEntity result = callNewPDP(resource, HttpMethod.POST, body, - StdPolicyResponse[].class); + final ResponseEntity result = + callNewPDP(SEND_EVENT_RESOURCE_NAME, HttpMethod.POST, body, StdPolicyResponse[].class); // Process Response - response = eventResult(result.getBody()); - } catch (Exception exception) { - if (exception.getCause().getMessage().contains("401")) { - String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource; - LOGGER.error(message); - throw new PolicyEventException(message, exception); - } - if (exception.getCause().getMessage().contains("400")) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE; - LOGGER.error(message); - throw new PolicyEventException(message, exception); - } - String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS - + pdps; + return eventResult(result.getBody()); + } catch (final Exception exception) { + final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps; + final String message = getErrorMessage(exception, defaulMessage, SEND_EVENT_RESOURCE_NAME); LOGGER.error(message, exception); throw new PolicyEventException(message, exception); } - return response; } - private ArrayList eventResult(StdPolicyResponse[] response){ - ArrayList eventResult = new ArrayList<>(); + private String getErrorMessage(final Exception exception, final String defaulMessage, final String resource) { + final Throwable cause = exception.getCause(); + if (cause != null && cause.getMessage().contains(UNAUTHORIZED_STATUS_CODE)) { + return XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource; + } + if (cause != null && exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) { + return XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE; + } + return defaulMessage; + } + + private ArrayList eventResult(final StdPolicyResponse[] response) { + final ArrayList eventResult = new ArrayList<>(); if (response != null && response.length > 0) { - for (StdPolicyResponse policyConfigResponse : response) { + for (final StdPolicyResponse policyConfigResponse : response) { eventResult.add(policyConfigResponse); } } return eventResult; } - private void setProperty(String propertyFilePath, String clientKey) throws PolicyEngineException { + private void setProperty(final String propertyFilePath, String clientKey) throws PolicyEngineException { if (propertyFilePath == null) { throw new PolicyEngineException( XACMLErrorConstants.ERROR_DATA_ISSUE + "Error NO PropertyFile Path provided"); + } + final Properties prop = getProperties(propertyFilePath); + setProperty(prop,clientKey); + } + + private void setProperty(final Properties properties, String clientKey) throws PolicyEngineException { + if (properties == null) { + throw new PolicyEngineException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "NO properties provided, the value is NULL"); + } + + // UEB and DMAAP Settings + final String notificationTypeValue = properties.getProperty(NOTIFICATION_TYPE_PROP_NAME); + final String serverList = properties.getProperty(NOTIFICATION_SERVERS_PROP_NAME); + topic = properties.getProperty(NOTIFICATION_TOPIC_PROP_NAME); + apiKey = properties.getProperty(UEB_API_KEY_PROP_NAME); + apiSecret = properties.getProperty(UEB_API_SECRET_PROP_NAME); + + setNotificationType(notificationTypeValue, DEFAULT_NOTIFICATION); + + if (serverList == null) { + notificationType.clear(); + notificationType.add(DEFAULT_NOTIFICATION); + LOGGER.info( + "Properties file doesn't have the NOTIFICATION_SERVERS parameter system will use defualt websockets"); } else { - // Adding logic for remote Properties file. - Properties prop = new Properties(); - if (propertyFilePath.startsWith("http")) { - URL configURL; - try { - configURL = new URL(propertyFilePath); - URLConnection connection = null; - connection = configURL.openConnection(); - prop.load(connection.getInputStream()); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - throw new PolicyEngineException( - XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL " + e.getMessage()); - } - } else { - Path file = Paths.get(propertyFilePath); - if (!file.toFile().exists()) { + notificationURLList = getPropertyValueAsList(serverList.trim(), COMMA); + } + + if (topic != null) { + topic = topic.trim(); + } else { + LOGGER.error("Properties file doesn't have the NOTIFICATION_TOPIC parameter."); + } + + // Client ID Authorization Settings. + final String clientID = properties.getProperty(CLIENT_ID_PROP_NAME); + if (clientKey == null) { + clientKey = getClientKeyFromProperties(properties); + } + if (clientID == null || clientKey == null || clientID.isEmpty() || clientKey.isEmpty()) { + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!"); + throw new PolicyEngineException(XACMLErrorConstants.ERROR_PERMISSIONS + + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!"); + } else { + setClientId(clientID.trim()); + setClientKey(clientKey.trim()); + } + setEnvironment(properties); + // Initializing the values. + init(); + readPdpProperites(properties); + // Get JUNIT property from properties file when running tests + checkJunit(properties); + } + + private void readPdpProperites(final Properties prop) throws PolicyEngineException { + // Check the Keys for PDP_URLs + for (final String propertyKey : prop.stringPropertyNames()) { + if (propertyKey.startsWith(PDP_URL_PROP_NAME)) { + final String propertyValue = prop.getProperty(propertyKey); + if (propertyValue == null) { throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE - + "File doesn't exist in the specified Path " + file.toString()); + + "Properties file doesn't have the PDP_URL parameter"); } - if (file.toString().endsWith(".properties")) { - InputStream in; - prop = new Properties(); - try { - in = new FileInputStream(file.toFile()); - prop.load(in); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - throw new PolicyEngineException( - XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file", e); + if (propertyValue.contains(SEMICOLLON)) { + final List pdpDefault = Arrays.asList(propertyValue.split(REGEX)); + for (final String pdpVal : pdpDefault) { + readPDPParam(pdpVal); } } else { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath); - throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file"); - } - } - // UEB and DMAAP Settings - String checkType = prop.getProperty("NOTIFICATION_TYPE"); - String serverList = prop.getProperty("NOTIFICATION_SERVERS"); - topic = prop.getProperty("NOTIFICATION_TOPIC"); - apiKey = prop.getProperty("UEB_API_KEY"); - apiSecret = prop.getProperty("UEB_API_SECRET"); - - if (checkType == null) { - notificationType.add(DEFAULT_NOTIFICATION); - LOGGER.info( - "Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets"); - } else { - checkType = checkType.trim(); - if (checkType.contains(",")) { - notificationType = new ArrayList<>(Arrays.asList(prop.getProperty("NOTIFICATION_TYPE").split(","))); - } else { - notificationType = new ArrayList<>(); - notificationType.add(checkType); - } - } - if (serverList == null) { - notificationType.clear(); - notificationType.add(DEFAULT_NOTIFICATION); - LOGGER.info( - "Properties file doesn't have the NOTIFICATION_SERVERS parameter system will use defualt websockets"); - } else { - serverList = serverList.trim(); - if (serverList.contains(",")) { - notificationURLList = new ArrayList<>(Arrays.asList(serverList.split(","))); - } else { - notificationURLList = new ArrayList<>(); - notificationURLList.add(serverList); + readPDPParam(propertyValue); } } + } + if (pdps == null || pdps.isEmpty()) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs"); + throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs"); + } + } - if (topic != null) { - topic = topic.trim(); - } else { - LOGGER.error("Properties file doesn't have the NOTIFICATION_TOPIC parameter."); - } + private void setNotificationType(final String propertyValue, final String defaultValue) { + if (propertyValue == null) { + notificationType.add(defaultValue); + LOGGER.info( + "Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets"); + } else { + notificationType = getPropertyValueAsList(propertyValue.trim(), COMMA); + } + } - // Client ID Authorization Settings. - String clientID = prop.getProperty("CLIENT_ID"); - if (clientKey == null) { - clientKey = prop.getProperty("CLIENT_KEY"); - try { - clientKey = PolicyUtils.decode(clientKey); - } catch (UnsupportedEncodingException | IllegalArgumentException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS - + " Cannot Decode the given Password Proceeding with given Password!!", e); - } - } - if (clientID == null || clientKey == null || clientID.isEmpty() || clientKey.isEmpty()) { - LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS - + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!"); - throw new PolicyEngineException(XACMLErrorConstants.ERROR_PERMISSIONS - + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!"); - } else { - setClientId(clientID.trim()); - setClientKey(clientKey.trim()); - } - setEnvironment(prop); - // Initializing the values. - init(); - // Check the Keys for PDP_URLs - Collection unsorted = prop.keySet(); - @SuppressWarnings({ "rawtypes", "unchecked" }) - List sorted = new ArrayList(unsorted); - Collections.sort(sorted); - for (String propKey : sorted) { - if (propKey.startsWith("PDP_URL")) { - String checkVal = prop.getProperty(propKey); - if (checkVal == null) { - throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE - + "Properties file doesn't have the PDP_URL parameter"); - } - if (checkVal.contains(";")) { - List pdpDefault = new ArrayList<>(Arrays.asList(checkVal.split("\\s*;\\s*"))); - int pdpCount = 0; - while (pdpCount < pdpDefault.size()) { - String pdpVal = pdpDefault.get(pdpCount); - readPDPParam(pdpVal); - pdpCount++; - } - } else { - readPDPParam(checkVal); - } - } - } - if (pdps == null || pdps.isEmpty()) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs"); + private String getClientKeyFromProperties(final Properties prop) { + final String clientKeyValue = prop.getProperty(CLIENT_KEY_PROP_NAME); + try { + return PolicyUtils.decode(clientKeyValue); + } catch (UnsupportedEncodingException | IllegalArgumentException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + + " Cannot Decode the given Password Proceeding with given Password!!", e); + } + return clientKeyValue; + } + + private Properties getProperties(final String propertyFilePath) throws PolicyEngineException { + // Adding logic for remote Properties file. + if (propertyFilePath.startsWith(HTTP)) { + return getRemoteProperties(propertyFilePath); + } + return getFileProperties(propertyFilePath); + } + + private Properties getFileProperties(final String propertyFilePath) throws PolicyEngineException { + final Path file = Paths.get(propertyFilePath); + if (!file.toFile().exists()) { + throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + + "File doesn't exist in the specified Path " + file.toString()); + } + if (file.toString().endsWith(".properties")) { + try (BufferedReader bufferedReader = Files.newBufferedReader(file);) { + final Properties prop = new Properties(); + prop.load(bufferedReader); + return prop; + } catch (final IOException exception) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + exception); throw new PolicyEngineException( - XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs"); + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file", exception); } - // Get JUNIT property from properties file when running tests - checkJunit(prop); } + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath); + throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file"); } - private static void checkJunit(Properties prop) { - String junitFlag = prop.getProperty("JUNIT"); + private Properties getRemoteProperties(final String propertyFilePath) throws PolicyEngineException { + try { + final URL configURL = new URL(propertyFilePath); + final URLConnection connection = configURL.openConnection(); + final Properties prop = new Properties(); + prop.load(connection.getInputStream()); + return prop; + } catch (final IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + throw new PolicyEngineException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL " + e.getMessage()); + } + } + + private List getPropertyValueAsList(final String propertyValue, final String split) { + if (propertyValue.contains(split)) { + return Arrays.asList(propertyValue.split(split)); + } + final List valuesList = new ArrayList<>(); + valuesList.add(propertyValue); + return valuesList; + } + + private static void checkJunit(final Properties prop) { + final String junitFlag = prop.getProperty(JUNIT_PROP_NAME); if (junitFlag == null || junitFlag.isEmpty()) { LOGGER.info("No JUNIT property provided, this will not be executed as a test."); } else { - if (junitFlag.equalsIgnoreCase("test")) { + if ("test".equalsIgnoreCase(junitFlag)) { StdPolicyEngine.junit = true; } else { StdPolicyEngine.junit = false; @@ -988,8 +1019,8 @@ public class StdPolicyEngine { encoding = new ArrayList<>(); } - private static void setEnvironment(Properties prop) { - environment = prop.getProperty("ENVIRONMENT", AAFEnvironment.DEVL.toString()); + private static void setEnvironment(final Properties prop) { + environment = prop.getProperty(ENVIRONMENT_PROP_NAME, AAFEnvironment.DEVL.toString()); if (environment.equalsIgnoreCase(AAFEnvironment.TEST.toString())) { environment = AAFEnvironment.TEST.toString(); } else if (environment.equalsIgnoreCase(AAFEnvironment.PROD.toString())) { @@ -999,23 +1030,23 @@ public class StdPolicyEngine { } } - private static void setClientId(String clientID) { + private static void setClientId(final String clientID) { userName = clientID; } /* * Read the PDP_URL parameter */ - private void readPDPParam(String pdpVal) throws PolicyEngineException { - if (pdpVal.contains(",")) { - List pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); + private void readPDPParam(final String pdpVal) throws PolicyEngineException { + if (pdpVal.contains(COMMA)) { + final List pdpValues = Arrays.asList(pdpVal.split(PDP_VALUE_REGEX)); if (pdpValues.size() == 3) { // 0 - PDPURL pdps.add(pdpValues.get(0)); // 1:2 will be UserID:Password - String userID = pdpValues.get(1); - String userPas = pdpValues.get(2); - Base64.Encoder encoder = Base64.getEncoder(); + final String userID = pdpValues.get(1); + final String userPas = pdpValues.get(2); + final Base64.Encoder encoder = Base64.getEncoder(); encoding.add(encoder.encodeToString((userID + ":" + userPas).getBytes(StandardCharsets.UTF_8))); } else { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + pdpValues); @@ -1033,13 +1064,13 @@ public class StdPolicyEngine { /* * Allowing changes to the scheme and Handler. */ - public void notification(NotificationScheme scheme, NotificationHandler handler) { + public void notification(final NotificationScheme scheme, final NotificationHandler handler) { this.scheme = scheme; this.handler = handler; LOGGER.debug("Scheme is : " + scheme.toString()); LOGGER.debug("Handler is : " + handler.getClass().getName()); - if (notificationType.get(0).equals("ueb")) { + if (UEB.equals(notificationType.get(0))) { if (this.uebThread) { AutoClientUEB.setAuto(scheme, handler); this.uebThread = registerUEBThread.isAlive(); @@ -1058,7 +1089,7 @@ public class StdPolicyEngine { } if (pdps != null) { - if (notificationType.get(0).equals("ueb") && !this.uebThread) { + if (UEB.equals(notificationType.get(0)) && !this.uebThread) { this.uebClientThread = new AutoClientUEB(pdps.get(0), notificationURLList, apiKey, apiSecret); AutoClientUEB.setAuto(scheme, handler); this.registerUEBThread = new Thread(this.uebClientThread); @@ -1072,7 +1103,7 @@ public class StdPolicyEngine { this.dmaapThread = true; } else { if (pdps.get(0) != null) { - if (AutoClientEnd.getURL() == null) { + if (AutoClientEnd.getUrl() == null) { AutoClientEnd.start(pdps.get(0)); } else { AutoClientEnd.stop(); @@ -1088,10 +1119,10 @@ public class StdPolicyEngine { */ public PDPNotification getNotification() { // Check if there is proper scheme.. - PDPNotification notification = null; + PDPNotification notification; if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS) || this.scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) { - if (notificationType.get(0).equals("ueb")) { + if (UEB.equals(notificationType.get(0))) { ManualClientEndUEB.start(pdps.get(0), notificationURLList, UNIQUEID); notification = ManualClientEndUEB.result(scheme); } else if (notificationType.get(0).equals(DMAAP)) { @@ -1105,20 +1136,18 @@ public class StdPolicyEngine { if (notification == null) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Notification yet.."); return null; - } else { - return notification; } - } else { - return null; + return notification; } + return null; } /* * Setting the Scheme. */ - public void setScheme(NotificationScheme scheme) { + public void setScheme(final NotificationScheme scheme) { this.scheme = scheme; - if (notificationType.get(0).equals("ueb")) { + if (UEB.equals(notificationType.get(0))) { AutoClientUEB.setScheme(this.scheme); if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) { ManualClientEndUEB.createTopic(pdps.get(0), UNIQUEID, notificationURLList); @@ -1151,10 +1180,11 @@ public class StdPolicyEngine { * Stop the Notification Service if its running. */ public void stopNotification() { - if (this.scheme != null && this.handler != null && (this.scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) - || this.scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS))) { + if (this.scheme != null && this.handler != null + && (this.scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) + || this.scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS))) { LOGGER.info("Clear Notification called.. "); - if (notificationType.get(0).equals("ueb")) { + if (UEB.equals(notificationType.get(0))) { this.uebClientThread.terminate(); this.uebThread = false; } else if (notificationType.get(0).equals(DMAAP)) { @@ -1169,19 +1199,11 @@ public class StdPolicyEngine { /* * Push a policy to the PDP API implementation */ - public String pushPolicy(String policyScope, String policyName, String policyType, String pdpGroup, UUID requestID) - throws PolicyException { - PushPolicyParameters pushPolicyParameters = new PushPolicyParameters(); - if (policyScope == null || policyScope.trim().isEmpty()) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; - LOGGER.error(message); - throw new PolicyException(message); - } - if (policyName == null || policyName.trim().isEmpty()) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - LOGGER.error(message); - throw new PolicyException(message); - } + public String pushPolicy(final String policyScope, final String policyName, final String policyType, + final String pdpGroup, final UUID requestID) throws PolicyException { + validateParameters(policyName, policyScope); + + final PushPolicyParameters pushPolicyParameters = new PushPolicyParameters(); pushPolicyParameters.setPolicyName(policyScope + "." + policyName); pushPolicyParameters.setPolicyType(policyType); pushPolicyParameters.setPdpGroup(pdpGroup); @@ -1189,10 +1211,15 @@ public class StdPolicyEngine { return pushPolicyImpl(pushPolicyParameters).getResponseMessage(); } - public String createUpdateConfigPolicy(String policyName, String policyDescription, String onapName, - String configName, Map configAttributes, String configType, String body, String policyScope, - UUID requestID, String riskLevel, String riskType, String guard, String ttlDate, boolean updateFlag) - throws PolicyException { + private boolean isNotValid(final String value) { + return value == null || value.trim().isEmpty(); + } + + public String createUpdateConfigPolicy(final String policyName, final String policyDescription, + final String onapName, final String configName, final Map configAttributes, + final String configType, final String body, final String policyScope, final UUID requestID, + final String riskLevel, final String riskType, final String guard, final String ttlDate, + final boolean updateFlag) throws PolicyException { return createUpdateConfigPolicyImpl(policyName, policyDescription, onapName, configName, configAttributes, configType, body, policyScope, requestID, riskLevel, riskType, guard, ttlDate, updateFlag); } @@ -1200,29 +1227,25 @@ public class StdPolicyEngine { /* * Create Config Policy API Implementation */ - public String createUpdateConfigPolicyImpl(String policyName, String policyDescription, String onapName, - String configName, Map configAttributes, String configType, String body, String policyScope, - UUID requestID, String riskLevel, String riskType, String guard, String ttlDate, boolean updateFlag) - throws PolicyException { - PolicyParameters policyParameters = new PolicyParameters(); + public String createUpdateConfigPolicyImpl(final String policyName, final String policyDescription, + final String onapName, final String configName, final Map configAttributes, + final String configType, final String body, final String policyScope, final UUID requestID, + final String riskLevel, final String riskType, final String guard, final String ttlDate, + final boolean updateFlag) throws PolicyException { + + validateParameters(policyName, policyScope); + + final PolicyParameters policyParameters = new PolicyParameters(); policyParameters.setPolicyClass(PolicyClass.Config); policyParameters.setPolicyConfigType(PolicyConfigType.Base); - if (policyScope == null || policyScope.trim().isEmpty()) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; - LOGGER.error(message); - throw new PolicyException(message); - } - if (policyName == null || policyName.trim().isEmpty()) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - LOGGER.error(message); - throw new PolicyException(message); - } policyParameters.setPolicyName(policyScope + "." + policyName); policyParameters.setPolicyDescription(policyDescription); policyParameters.setOnapName(onapName); policyParameters.setConfigName(configName); - Map> attributes = new HashMap>(); + + final Map> attributes = new HashMap<>(); attributes.put(AttributeType.MATCHING, configAttributes); + policyParameters.setAttributes(attributes); policyParameters.setConfigBodyType(PolicyType.valueOf(configType)); policyParameters.setConfigBody(body); @@ -1230,18 +1253,22 @@ public class StdPolicyEngine { policyParameters.setRiskLevel(riskLevel); policyParameters.setRiskType(riskType); policyParameters.setGuard(Boolean.parseBoolean(guard)); + policyParameters.setTtlDate(toDate(ttlDate)); + return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage(); + } + + private Date toDate(final String dateString) { try { - policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(ttlDate)); - } catch (ParseException e) { - LOGGER.warn("Error Parsing date given " + ttlDate); - policyParameters.setTtlDate(null); + return new SimpleDateFormat(DATE_FORMAT).parse(dateString); + } catch (final ParseException e) { + LOGGER.warn("Error Parsing date given " + dateString); } - return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage(); + return null; } - public String createUpdateConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, - UUID requestID, String riskLevel, String riskType, String guard, String ttlDate, boolean updateFlag) - throws PolicyException { + public String createUpdateConfigFirewallPolicy(final String policyName, final JsonObject firewallJson, + final String policyScope, final UUID requestID, final String riskLevel, final String riskType, + final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException { return createUpdateConfigFirewallPolicyImpl(policyName, firewallJson, policyScope, requestID, riskLevel, riskType, guard, ttlDate, updateFlag); } @@ -1249,38 +1276,38 @@ public class StdPolicyEngine { /* * Create Update Config Firewall Policy API implementation */ - public String createUpdateConfigFirewallPolicyImpl(String policyName, JsonObject firewallJson, String policyScope, - UUID requestID, String riskLevel, String riskType, String guard, String ttlDate, boolean updateFlag) - throws PolicyException { - PolicyParameters policyParameters = new PolicyParameters(); + public String createUpdateConfigFirewallPolicyImpl(final String policyName, final JsonObject firewallJson, + final String policyScope, final UUID requestID, final String riskLevel, final String riskType, + final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException { + validateParameters(policyName, policyScope); + + final PolicyParameters policyParameters = new PolicyParameters(); policyParameters.setPolicyClass(PolicyClass.Config); policyParameters.setPolicyConfigType(PolicyConfigType.Firewall); - if (policyScope == null || policyScope.trim().isEmpty()) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; - LOGGER.error(message); - throw new PolicyException(message); - } - if (policyName == null || policyName.trim().isEmpty()) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - LOGGER.error(message); - throw new PolicyException(message); - } policyParameters.setPolicyName(policyScope + "." + policyName); policyParameters.setConfigBody(firewallJson.toString()); policyParameters.setRequestID(requestID); policyParameters.setRiskLevel(riskLevel); policyParameters.setRiskType(riskType); policyParameters.setGuard(Boolean.parseBoolean(guard)); - try { - policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(ttlDate)); - } catch (NullPointerException | ParseException e) { - LOGGER.warn("Error Parsing date given " + ttlDate, e); - policyParameters.setTtlDate(null); - } + policyParameters.setTtlDate(toDate(ttlDate)); return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage(); } - public static void setClientKey(String clientKey) { + private void validateParameters(final String policyName, final String policyScope) throws PolicyException { + if (isNotValid(policyScope)) { + final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + LOGGER.error(message); + throw new PolicyException(message); + } + if (isNotValid(policyName)) { + final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + LOGGER.error(message); + throw new PolicyException(message); + } + } + + public static void setClientKey(final String clientKey) { if (clientKey != null && !clientKey.isEmpty()) { StdPolicyEngine.pass = clientKey; setClientEncoding(); @@ -1308,4 +1335,20 @@ public class StdPolicyEngine { public static String getPDPURL() { return pdps.get(0); } -} \ No newline at end of file + + // Added for test + String getTopic() { + return topic; + } + + // Added for test + List getNotificationType() { + return notificationType; + } + + // Added for test + List getNotificationURLList() { + return notificationURLList; + } + +}