diff options
author | waqas.ikram <waqas.ikram@ericsson.com> | 2018-02-23 11:17:30 +0000 |
---|---|---|
committer | waqas.ikram <waqas.ikram@ericsson.com> | 2018-02-23 12:27:39 +0000 |
commit | 31eb647f94f15e8cde608fb5b467cae610ee2ce3 (patch) | |
tree | 1284f9908f2589c9f24842d48d0b14f5933605e5 /PolicyEngineAPI/src | |
parent | e22a2b613bda0e683043ef870d6b16e5a7e04df7 (diff) |
Add JUnit tests policy/engine PolicyEngineAPI
Change-Id: I8d7a76836759b042c83349c2b875fb77085b531c
Issue-ID: POLICY-606
Signed-off-by: waqas.ikram <waqas.ikram@ericsson.com>
Diffstat (limited to 'PolicyEngineAPI/src')
7 files changed, 1910 insertions, 613 deletions
diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyEngine.java b/PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyEngine.java index 2b5252c26..0d224cee0 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyEngine.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyEngine.java @@ -37,7 +37,7 @@ import org.onap.policy.std.StdPolicyEngine; */ public class PolicyEngine{ private String propertyFilePath = null; - private StdPolicyEngine stdPolicyEngine; + private final StdPolicyEngine stdPolicyEngine; private NotificationScheme scheme = null; private NotificationHandler handler = null; @@ -47,7 +47,7 @@ public class PolicyEngine{ * @param propertiesFilePathname the <code>String</code> format of the propertiesFilePathname * @throws PolicyEngineException PolicyEngine Exception */ - public PolicyEngine(String propertiesFilePathname) throws PolicyEngineException { + public PolicyEngine(final String propertiesFilePathname) throws PolicyEngineException { this.propertyFilePath = propertiesFilePathname ; this.stdPolicyEngine= new StdPolicyEngine(this.propertyFilePath, (String)null); } @@ -59,7 +59,7 @@ public class PolicyEngine{ * @param clientKey depicts String format of Password/ Client_Key. * @throws PolicyEngineException PolicyEngine Exception */ - public PolicyEngine(String propertiesFilePathname, String clientKey) throws PolicyEngineException { + public PolicyEngine(final String propertiesFilePathname, final String clientKey) throws PolicyEngineException { this.propertyFilePath = propertiesFilePathname ; this.stdPolicyEngine= new StdPolicyEngine(this.propertyFilePath, clientKey); } @@ -71,7 +71,7 @@ public class PolicyEngine{ * @param scheme the <code>NotificationScheme</code> of {@link org.onap.policy.api.NotificationScheme} which defines the Notification Scheme * @throws PolicyEngineException PolicyEngine Exception */ - public PolicyEngine(String propertiesFilePathname, NotificationScheme scheme) throws PolicyEngineException{ + public PolicyEngine(final String propertiesFilePathname, final NotificationScheme scheme) throws PolicyEngineException{ this.propertyFilePath = propertiesFilePathname; this.scheme = scheme; this.stdPolicyEngine = new StdPolicyEngine(this.propertyFilePath, this.scheme); @@ -85,7 +85,7 @@ public class PolicyEngine{ * @param handler the <code>NotificationHandler</code> of {@link org.onap.policy.api.NotificationHandler} which defines what should happen when a notification is received. * @throws PolicyEngineException PolicyEngine Exception */ - public PolicyEngine(String propertiesFilePathname, NotificationScheme scheme, NotificationHandler handler) throws PolicyEngineException { + public PolicyEngine(final String propertiesFilePathname, final NotificationScheme scheme, final NotificationHandler handler) throws PolicyEngineException { this.propertyFilePath = propertiesFilePathname ; this.scheme = scheme; this.handler = handler; @@ -101,7 +101,7 @@ public class PolicyEngine{ * @deprecated use {@link #getConfig(ConfigRequestParameters configRequestParameters)} Instead. */ @Deprecated - public Collection<PolicyConfig> getConfigByPolicyName(String policyName) throws PolicyConfigException { + public Collection<PolicyConfig> getConfigByPolicyName(final String policyName) throws PolicyConfigException { return getConfig(setConfigRequestParameters(policyName, null, null, null, null)); } @@ -116,7 +116,7 @@ public class PolicyEngine{ * @deprecated use {@link #getConfig(ConfigRequestParameters configRequestParameters)} Instead. */ @Deprecated - public Collection<PolicyConfig> getConfigByPolicyName(String policyName, UUID requestID) throws PolicyConfigException { + public Collection<PolicyConfig> getConfigByPolicyName(final String policyName, final UUID requestID) throws PolicyConfigException { return getConfig(setConfigRequestParameters(policyName, null, null, null, requestID)); } @@ -129,7 +129,7 @@ public class PolicyEngine{ * @deprecated use {@link #getConfig(ConfigRequestParameters)} Instead. */ @Deprecated - public Collection<PolicyConfig> getConfig(String onapName) throws PolicyConfigException { + public Collection<PolicyConfig> getConfig(final String onapName) throws PolicyConfigException { return getConfig(setConfigRequestParameters(null, onapName, null, null, null)); } @@ -144,7 +144,7 @@ public class PolicyEngine{ * @deprecated use {@link #getConfig(ConfigRequestParameters)} Instead. */ @Deprecated - public Collection<PolicyConfig> getConfig(String onapName, UUID requestID) throws PolicyConfigException { + public Collection<PolicyConfig> getConfig(final String onapName, final UUID requestID) throws PolicyConfigException { return getConfig(setConfigRequestParameters(null, onapName, null, null, requestID)); } @@ -160,7 +160,7 @@ public class PolicyEngine{ * @deprecated use {@link #getConfig(ConfigRequestParameters)} Instead. */ @Deprecated - public Collection<PolicyConfig> getConfig(String onapName, String configName) throws PolicyConfigException { + public Collection<PolicyConfig> getConfig(final String onapName, final String configName) throws PolicyConfigException { return getConfig(setConfigRequestParameters(null, onapName, configName, null, null)); } @@ -178,7 +178,7 @@ public class PolicyEngine{ * @deprecated use {@link #getConfig(ConfigRequestParameters)} Instead. */ @Deprecated - public Collection<PolicyConfig> getConfig(String onapName, String configName, UUID requestID) throws PolicyConfigException { + public Collection<PolicyConfig> getConfig(final String onapName, final String configName, final UUID requestID) throws PolicyConfigException { return getConfig(setConfigRequestParameters(null, onapName, configName, null, requestID)); } @@ -195,7 +195,7 @@ public class PolicyEngine{ * @deprecated use {@link #getConfig(ConfigRequestParameters)} Instead. */ @Deprecated - public Collection<PolicyConfig> getConfig(String onapName, String configName, Map<String, String> configAttributes) throws PolicyConfigException{ + public Collection<PolicyConfig> getConfig(final String onapName, final String configName, final Map<String, String> configAttributes) throws PolicyConfigException{ return getConfig(setConfigRequestParameters(null, onapName, configName, configAttributes, null)); } @@ -214,7 +214,7 @@ public class PolicyEngine{ * @deprecated use {@link #getConfig(ConfigRequestParameters)} Instead. */ @Deprecated - public Collection<PolicyConfig> getConfig(String onapName, String configName, Map<String, String> configAttributes, UUID requestID) throws PolicyConfigException{ + public Collection<PolicyConfig> getConfig(final String onapName, final String configName, final Map<String, String> configAttributes, final UUID requestID) throws PolicyConfigException{ return getConfig(setConfigRequestParameters(null, onapName, configName, configAttributes, requestID)); } @@ -226,7 +226,7 @@ public class PolicyEngine{ * @return <code>Collection</code> of {@link org.onap.policy.api.PolicyConfig} which has the configuration. * @throws PolicyConfigException PolicyConfig Exception */ - public Collection<PolicyConfig> getConfig(ConfigRequestParameters configRequestParameters) throws PolicyConfigException{ + public Collection<PolicyConfig> getConfig(final ConfigRequestParameters configRequestParameters) throws PolicyConfigException{ return stdPolicyEngine.getConfig(configRequestParameters); } @@ -238,7 +238,7 @@ public class PolicyEngine{ * @return <code>Collection</code> of <code>String</code> which returns the list of policies. * @throws PolicyConfigException PolicyConfig Exception */ - public Collection<String> listConfig(ConfigRequestParameters listPolicyRequestParameters) throws PolicyConfigException{ + public Collection<String> listConfig(final ConfigRequestParameters listPolicyRequestParameters) throws PolicyConfigException{ return stdPolicyEngine.listConfig(listPolicyRequestParameters); } @@ -252,7 +252,7 @@ public class PolicyEngine{ * @deprecated use {@link #sendEvent(EventRequestParameters)} Instead. */ @Deprecated - public Collection<PolicyResponse> sendEvent(Map<String, String> eventAttributes) throws PolicyEventException { + public Collection<PolicyResponse> sendEvent(final Map<String, String> eventAttributes) throws PolicyEventException { return stdPolicyEngine.sendEvent(eventAttributes, (UUID) null); } @@ -267,7 +267,7 @@ public class PolicyEngine{ * @deprecated use {@link #sendEvent(EventRequestParameters)} Instead. */ @Deprecated - public Collection<PolicyResponse> sendEvent(Map<String, String> eventAttributes, UUID requestID) throws PolicyEventException { + public Collection<PolicyResponse> sendEvent(final Map<String, String> eventAttributes, final UUID requestID) throws PolicyEventException { return stdPolicyEngine.sendEvent(eventAttributes, requestID); } @@ -278,7 +278,7 @@ public class PolicyEngine{ * @return <code>Collection</code> of {@link org.onap.policy.api.PolicyResponse} which has the Response. * @throws PolicyEventException PolicyEvent Exception */ - public Collection<PolicyResponse> sendEvent(EventRequestParameters eventRequestParameters) throws PolicyEventException { + public Collection<PolicyResponse> sendEvent(final EventRequestParameters eventRequestParameters) throws PolicyEventException { return stdPolicyEngine.sendEvent(eventRequestParameters); } @@ -292,7 +292,7 @@ public class PolicyEngine{ * @deprecated use {@link #getDecision(DecisionRequestParameters)} Instead. */ @Deprecated - public DecisionResponse getDecision(String onapName, Map<String,String> decisionAttributes) throws PolicyDecisionException { + public DecisionResponse getDecision(final String onapName, final Map<String,String> decisionAttributes) throws PolicyDecisionException { return stdPolicyEngine.getDecision(onapName, decisionAttributes, null); } @@ -308,7 +308,7 @@ public class PolicyEngine{ * @deprecated use {@link #getDecision(DecisionRequestParameters)} Instead. */ @Deprecated - public DecisionResponse getDecision(String onapName, Map<String,String> decisionAttributes, UUID requestID) throws PolicyDecisionException { + public DecisionResponse getDecision(final String onapName, final Map<String,String> decisionAttributes, final UUID requestID) throws PolicyDecisionException { return stdPolicyEngine.getDecision(onapName, decisionAttributes, requestID); } @@ -319,7 +319,7 @@ public class PolicyEngine{ * @return {@link org.onap.policy.api.DecisionResponse} which has the Decision. * @throws PolicyDecisionException PolicyDecision Exception */ - public DecisionResponse getDecision(DecisionRequestParameters decisionRequestParameters) throws PolicyDecisionException { + public DecisionResponse getDecision(final DecisionRequestParameters decisionRequestParameters) throws PolicyDecisionException { return stdPolicyEngine.getDecision(decisionRequestParameters); } @@ -331,7 +331,7 @@ public class PolicyEngine{ * @throws PolicyException PolicyException related to the operation * * */ - public MetricsResponse getMetrics(MetricsRequestParameters parameters) throws PolicyException { + public MetricsResponse getMetrics(final MetricsRequestParameters parameters) throws PolicyException { return stdPolicyEngine.getMetrics(parameters); } @@ -356,9 +356,9 @@ public class PolicyEngine{ * @deprecated use {@link #createPolicy(PolicyParameters)} Instead. */ @Deprecated - public String createConfigPolicy(String policyName, String policyDescription, String onapName, String configName, - Map<String, String> configAttributes, String configType, String body, String policyScope, UUID requestID, - String riskLevel, String riskType, String guard, String ttlDate) throws PolicyException { + public String createConfigPolicy(final String policyName, final String policyDescription, final String onapName, final String configName, + final Map<String, String> 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) throws PolicyException { return stdPolicyEngine.createUpdateConfigPolicy(policyName, policyDescription, onapName, configName, configAttributes, configType, body, policyScope, requestID, riskLevel, riskType, guard, ttlDate, false); @@ -385,9 +385,9 @@ public class PolicyEngine{ * @deprecated use {@link #updatePolicy(PolicyParameters)} Instead. */ @Deprecated - public String updateConfigPolicy(String policyName, String policyDescription, String onapName, String configName, - Map<String, String> configAttributes, String configType, String body, String policyScope, UUID requestID, - String riskLevel, String riskType, String guard, String ttlDate) throws PolicyException { + public String updateConfigPolicy(final String policyName, final String policyDescription, final String onapName, final String configName, + final Map<String, String> 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) throws PolicyException { return stdPolicyEngine.createUpdateConfigPolicy(policyName, policyDescription, onapName, configName, configAttributes, configType, body, policyScope, requestID,riskLevel, riskType, guard, ttlDate, true); } @@ -408,8 +408,8 @@ public class PolicyEngine{ * @deprecated use {@link #createPolicy(PolicyParameters)} Instead. */ @Deprecated - public String createConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, UUID requestID, - String riskLevel, String riskType, String guard, String ttlDate) throws PolicyException { + public String createConfigFirewallPolicy(final String policyName, final JsonObject firewallJson, final String policyScope, final UUID requestID, + final String riskLevel, final String riskType, final String guard, final String ttlDate) throws PolicyException { return stdPolicyEngine.createUpdateConfigFirewallPolicy(policyName, firewallJson, policyScope, requestID,riskLevel, riskType, guard, ttlDate, false); } @@ -430,8 +430,8 @@ public class PolicyEngine{ * @deprecated use {@link #updatePolicy(PolicyParameters)} Instead. */ @Deprecated - public String updateConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, UUID requestID, - String riskLevel, String riskType, String guard, String ttlDate) throws PolicyException { + public String updateConfigFirewallPolicy(final String policyName, final JsonObject firewallJson, final String policyScope, final UUID requestID, + final String riskLevel, final String riskType, final String guard, final String ttlDate) throws PolicyException { return stdPolicyEngine.createUpdateConfigFirewallPolicy(policyName, firewallJson, policyScope, requestID,riskLevel, riskType, guard, ttlDate, true); } @@ -443,7 +443,7 @@ public class PolicyEngine{ * @throws PolicyException PolicyException related to the operation * * */ - public DictionaryResponse getDictionaryItem(DictionaryParameters parameters) throws PolicyException { + public DictionaryResponse getDictionaryItem(final DictionaryParameters parameters) throws PolicyException { return stdPolicyEngine.getDictionaryItem(parameters); } @@ -454,7 +454,7 @@ public class PolicyEngine{ * @return {@link org.onap.policy.api.PolicyChangeResponse} which consists of the response related to create dictionary item Request. * @throws PolicyException PolicyException related to the operation. */ - public PolicyChangeResponse createDictionaryItem(DictionaryParameters parameters) throws PolicyException { + public PolicyChangeResponse createDictionaryItem(final DictionaryParameters parameters) throws PolicyException { return stdPolicyEngine.createDictionaryItem(parameters); } @@ -465,7 +465,7 @@ public class PolicyEngine{ * @return {@link org.onap.policy.api.PolicyChangeResponse} which consists of the response related to update dictionary item Request. * @throws PolicyException PolicyException related to the operation. */ - public PolicyChangeResponse updateDictionaryItem(DictionaryParameters parameters) throws PolicyException { + public PolicyChangeResponse updateDictionaryItem(final DictionaryParameters parameters) throws PolicyException { return stdPolicyEngine.updateDictionaryItem(parameters); } @@ -476,7 +476,7 @@ public class PolicyEngine{ * @return {@link org.onap.policy.api.PolicyChangeResponse} which consists of the response related to create policy Request. * @throws PolicyException PolicyException related to the operation. */ - public PolicyChangeResponse createPolicy(PolicyParameters policyParameters) throws PolicyException { + public PolicyChangeResponse createPolicy(final PolicyParameters policyParameters) throws PolicyException { return stdPolicyEngine.createPolicy(policyParameters); } @@ -487,7 +487,7 @@ public class PolicyEngine{ * @return {@link org.onap.policy.api.PolicyChangeResponse} which consists of the response related to create policy Request. * @throws PolicyException PolicyException related to the operation. */ - public PolicyChangeResponse updatePolicy(PolicyParameters policyParameters) throws PolicyException { + public PolicyChangeResponse updatePolicy(final PolicyParameters policyParameters) throws PolicyException { return stdPolicyEngine.updatePolicy(policyParameters); } @@ -504,7 +504,7 @@ public class PolicyEngine{ * @deprecated use {@link #pushPolicy(PushPolicyParameters)} instead. */ @Deprecated - public String pushPolicy(String policyScope, String policyName, String policyType, String pdpGroup, UUID requestID) throws PolicyException { + public String pushPolicy(final String policyScope, final String policyName, final String policyType, final String pdpGroup, final UUID requestID) throws PolicyException { return stdPolicyEngine.pushPolicy(policyScope, policyName, policyType, pdpGroup, requestID); } @@ -515,7 +515,7 @@ public class PolicyEngine{ * @return {@link org.onap.policy.api.PolicyChangeResponse} which consists of the response related to the push Policy Request. * @throws PolicyException PolicyException related to the operation. */ - public PolicyChangeResponse pushPolicy(PushPolicyParameters pushPolicyParameters) throws PolicyException { + public PolicyChangeResponse pushPolicy(final PushPolicyParameters pushPolicyParameters) throws PolicyException { return stdPolicyEngine.pushPolicy(pushPolicyParameters); } @@ -526,7 +526,7 @@ public class PolicyEngine{ * @return {@link org.onap.policy.api.PolicyChangeResponse} which consists of the response related to the Delete Policy Request. * @throws PolicyException PolicyException related to the operation. */ - public PolicyChangeResponse deletePolicy(DeletePolicyParameters deletePolicyParameters) throws PolicyException { + public PolicyChangeResponse deletePolicy(final DeletePolicyParameters deletePolicyParameters) throws PolicyException { return stdPolicyEngine.deletePolicy(deletePolicyParameters); } @@ -537,7 +537,7 @@ public class PolicyEngine{ * @return {@link org.onap.policy.api.PolicyChangeResponse} which consists of the response related to create import Service. * @throws PolicyException PolicyException related to the operation. */ - public PolicyChangeResponse policyEngineImport(ImportParameters importParameters) throws PolicyException { + public PolicyChangeResponse policyEngineImport(final ImportParameters importParameters) throws PolicyException { return stdPolicyEngine.policyEngineImport(importParameters); } @@ -547,7 +547,7 @@ public class PolicyEngine{ * @param scheme the <code>NotificationScheme</code> of {@link org.onap.policy.api.NotificationScheme} which defines the Notification Scheme * @param handler the <code>NotificationHandler</code> of {@link org.onap.policy.api.NotificationHandler} which defines what should happen when a notification is received. */ - public void setNotification(NotificationScheme scheme, NotificationHandler handler) { + public void setNotification(final NotificationScheme scheme, final NotificationHandler handler) { this.scheme = scheme; this.handler = handler; stdPolicyEngine.notification(this.scheme,this.handler); @@ -565,7 +565,7 @@ public class PolicyEngine{ * * @param scheme the <code>NotificationScheme</code> of {@link org.onap.policy.api.NotificationScheme} which defines the Notification Scheme */ - public void setScheme(NotificationScheme scheme){ + public void setScheme(final NotificationScheme scheme){ this.scheme = scheme; stdPolicyEngine.setScheme(this.scheme); } @@ -585,13 +585,13 @@ public class PolicyEngine{ * * @param clientKey depicts String format of Password/ Client_Key. */ - public void setClientKey(String clientKey){ + public void setClientKey(final String clientKey){ StdPolicyEngine.setClientKey(clientKey); } // Internal Setter Method to help build configRequestParameters. - private ConfigRequestParameters setConfigRequestParameters(String policyName, String onapName, String configName, Map<String, String> configAttributes, UUID requestID){ - ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); + private ConfigRequestParameters setConfigRequestParameters(final String policyName, final String onapName, final String configName, final Map<String, String> configAttributes, final UUID requestID){ + final ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); configRequestParameters.setPolicyName(policyName); configRequestParameters.setOnapName(onapName); configRequestParameters.setConfigName(configName); diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/MatchStore.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/MatchStore.java index fa8029908..eb3bf25e9 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/MatchStore.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/MatchStore.java @@ -20,12 +20,13 @@ package org.onap.policy.std; +import static org.onap.policy.std.utils.PolicyCommonConfigConstants.CONFIG_NAME; +import static org.onap.policy.std.utils.PolicyCommonConfigConstants.ONAP_NAME; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; - import org.onap.policy.api.LoadedPolicy; import org.onap.policy.api.NotificationType; import org.onap.policy.api.PDPNotification; @@ -34,9 +35,6 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; public class MatchStore { - private static final String CONFIG_NAME = "ConfigName"; - - private static final String ONAP_NAME = "ONAPName"; private static final Set<Matches> MATCH_STORE = new HashSet<>(); 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 5842d38d0..3d3eceead 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java @@ -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<String> pdps = null; @@ -140,19 +172,19 @@ 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 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 +193,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 +203,7 @@ public class StdPolicyEngine { /* * sendEvent API Implementation */ - public Collection<PolicyResponse> sendEvent(Map<String, String> eventAttributes, UUID requestID) + public Collection<PolicyResponse> sendEvent(final Map<String, String> eventAttributes, final UUID requestID) throws PolicyEventException { return sendEventImpl(eventAttributes, requestID); } @@ -178,10 +211,10 @@ public class StdPolicyEngine { /* * sendEvent API Implementation for eventRequestParameters */ - public Collection<PolicyResponse> sendEvent(EventRequestParameters eventRequestParameters) + public Collection<PolicyResponse> 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 +224,7 @@ public class StdPolicyEngine { /* * getConfig using configRequestParameters Implementation */ - public Collection<PolicyConfig> getConfig(ConfigRequestParameters configRequestParameters) + public Collection<PolicyConfig> getConfig(final ConfigRequestParameters configRequestParameters) throws PolicyConfigException { return getConfigImpl(configRequestParameters); } @@ -199,7 +232,7 @@ public class StdPolicyEngine { /* * listPolicies using configRequestParameters Implementation */ - public Collection<String> listConfig(ConfigRequestParameters listPolicyRequestParameters) + public Collection<String> listConfig(final ConfigRequestParameters listPolicyRequestParameters) throws PolicyConfigException { return listConfigImpl(listPolicyRequestParameters); } @@ -207,18 +240,18 @@ public class StdPolicyEngine { /* * getDecision using the decision Attributes. */ - public DecisionResponse getDecision(String onapName, Map<String, String> decisionAttributes, UUID requestID) - throws PolicyDecisionException { + public DecisionResponse getDecision(final String onapName, final Map<String, String> 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 +262,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<String> result = callNewPDP(resource, HttpMethod.GET, body, String.class); + final ResponseEntity<String> 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<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class); + final ResponseEntity<String> 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<String> result = callNewPDP(resource, HttpMethod.DELETE, body, String.class); + final ResponseEntity<String> 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 +368,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<APIDictionaryResponse> result = callNewPDP(resource, HttpMethod.POST, body, - APIDictionaryResponse.class); + final ResponseEntity<APIDictionaryResponse> 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<String, String>) 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,224 +432,202 @@ 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<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class); + final StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + final ResponseEntity<String> 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<String, Object> parameters = new LinkedMultiValueMap<>(); + public PolicyChangeResponse policyEngineImportImpl(final ImportParameters importParameters) throws PolicyException { + final LinkedMultiValueMap<String, Object> 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<String> result = callNewPDP(resource, HttpMethod.POST, parameters, String.class); + final StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + final ResponseEntity<String> 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<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class); + final ResponseEntity<String> 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<String, String> decisionAttributes, UUID requestID) - throws PolicyDecisionException { - String resource = "getDecision"; - StdDecisionResponse response; + public DecisionResponse getDecisionImpl(final String onapName, final Map<String, String> 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<StdDecisionResponse> result = callNewPDP(resource, HttpMethod.POST, body, - StdDecisionResponse.class); + final ResponseEntity<StdDecisionResponse> 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<PolicyConfig> getConfigImpl(ConfigRequestParameters configRequestParameters) + public Collection<PolicyConfig> getConfigImpl(final ConfigRequestParameters configRequestParameters) throws PolicyConfigException { - String resource = "getConfig"; - ArrayList<PolicyConfig> response; 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<APIPolicyConfigResponse[]> result = callNewPDP(resource, HttpMethod.POST, body, - APIPolicyConfigResponse[].class); + final ResponseEntity<APIPolicyConfigResponse[]> 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<PolicyConfig> configResult(APIPolicyConfigResponse[] response) throws PolicyConfigException { - ArrayList<PolicyConfig> result = new ArrayList<>(); - if (response != null && response.length > 0) { - for (APIPolicyConfigResponse policyConfigResponse : response) { - StdPolicyConfig policyConfig = new StdPolicyConfig(); + private ArrayList<PolicyConfig> configResult(final APIPolicyConfigResponse[] response) + throws PolicyConfigException { + final ArrayList<PolicyConfig> 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()); @@ -632,32 +641,31 @@ public class StdPolicyEngine { try { switch (policyConfigResponse.getType()) { case JSON: - try (JsonReader jsonReader = Json - .createReader(new StringReader(policyConfigResponse.getConfig())) ) { - JsonObject object = jsonReader.readObject(); - 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); @@ -666,14 +674,14 @@ public class StdPolicyEngine { return result; } - private void setMatches(Map<String, String> matchingConditions) { - Matches match = new Matches(); - HashMap<String, String> configAttributes = new HashMap<>(); + private void setMatches(final Map<String, String> matchingConditions) { + final Matches match = new Matches(); + final HashMap<String, String> configAttributes = new HashMap<>(); try { - for (Map.Entry<String,String> entry : matchingConditions.entrySet()) { - if ("ONAPName".equalsIgnoreCase(entry.getKey())) { + for (final Map.Entry<String, String> entry : matchingConditions.entrySet()) { + if (PolicyCommonConfigConstants.ONAP_NAME.equalsIgnoreCase(entry.getKey())) { match.setOnapName(entry.getValue()); - } else if ("ConfigName".equalsIgnoreCase(entry.getKey())) { + } else if (PolicyCommonConfigConstants.CONFIG_NAME.equalsIgnoreCase(entry.getKey())) { match.setConfigName(entry.getValue()); } else { configAttributes.put(entry.getKey(), entry.getValue()); @@ -683,7 +691,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); } } @@ -691,20 +699,20 @@ public class StdPolicyEngine { /* * Generic Rest Client to call PDP services. */ - private <T> ResponseEntity<T> callNewPDP(String resource, HttpMethod method, Object body, Class<T> responseType) - throws PolicyException { - RestTemplate restTemplate = new RestTemplate(); - HttpEntity<?> requestEntity = new HttpEntity<>(body, getHeaders()); + <T> ResponseEntity<T> callNewPDP(final String resource, final HttpMethod method, final Object body, + final Class<T> responseType) throws PolicyException { + final RestTemplate restTemplate = new RestTemplate(); + final HttpEntity<?> requestEntity = new HttpEntity<>(body, getHeaders()); ResponseEntity<T> 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()); } @@ -717,34 +725,32 @@ public class StdPolicyEngine { } } if (exception == null || exception.getStatusCode() == null) { - return result; + 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)) { - String message = XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" - + ERROR_AUTH_GET_PERM + resource; - LOGGER.error(message); - throw new PolicyException(message, exception); + return XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" + ERROR_AUTH_GET_PERM + + resource; } if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":" + return 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); + return XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps + exception; } - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":" + return XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":" + exception.getResponseBodyAsString(); - LOGGER.error(message); - throw new PolicyException(message, exception); } 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) { @@ -757,20 +763,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<String> listConfigImpl(ConfigRequestParameters listRequestParameters) + public Collection<String> listConfigImpl(final ConfigRequestParameters listRequestParameters) throws PolicyConfigException { - Collection<String> policyList = new ArrayList<>(); + final Collection<String> policyList = new ArrayList<>(); if (junit) { - policyList.add("Policy Name: listConfigTest"); + policyList.add(TEST_POLICY_NAME); return policyList; } - Collection<PolicyConfig> policyConfig = getConfigImpl(listRequestParameters); - for (PolicyConfig policy : policyConfig) { - if (policy.getPolicyConfigMessage() != null && policy.getPolicyConfigMessage().contains("PE300")) { + final Collection<PolicyConfig> 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()); @@ -779,133 +785,79 @@ public class StdPolicyEngine { return policyList; } - public Collection<PolicyResponse> sendEventImpl(Map<String, String> eventAttributes, UUID requestID) + public Collection<PolicyResponse> sendEventImpl(final Map<String, String> eventAttributes, final UUID requestID) throws PolicyEventException { - String resource = "sendEvent"; - ArrayList<PolicyResponse> response; 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<StdPolicyResponse[]> result = callNewPDP(resource, HttpMethod.POST, body, - StdPolicyResponse[].class); + final ResponseEntity<StdPolicyResponse[]> 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<PolicyResponse> eventResult(StdPolicyResponse[] response){ - ArrayList<PolicyResponse> 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<PolicyResponse> eventResult(final StdPolicyResponse[] response) { + final ArrayList<PolicyResponse> 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"); } - // Adding logic for remote Properties file. - Properties prop = new Properties(); - if (propertyFilePath.startsWith("http")) { - URL configURL; - try { - configURL = new URL(propertyFilePath); - URLConnection connection; - 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()) { - throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE - + "File doesn't exist in the specified Path " + file.toString()); - } - 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); - } - } else { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath); - throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file"); - } - } + final Properties prop = getProperties(propertyFilePath); // 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"); + final String notificationTypeValue = prop.getProperty(NOTIFICATION_TYPE_PROP_NAME); + final String serverList = prop.getProperty(NOTIFICATION_SERVERS_PROP_NAME); + topic = prop.getProperty(NOTIFICATION_TOPIC_PROP_NAME); + apiKey = prop.getProperty(UEB_API_KEY_PROP_NAME); + apiSecret = prop.getProperty(UEB_API_SECRET_PROP_NAME); + + setNotificationType(notificationTypeValue, DEFAULT_NOTIFICATION); - 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); - } + notificationURLList = getPropertyValueAsList(serverList.trim(), COMMA); } if (topic != null) { @@ -915,15 +867,9 @@ public class StdPolicyEngine { } // Client ID Authorization Settings. - String clientID = prop.getProperty("CLIENT_ID"); + final String clientID = prop.getProperty(CLIENT_ID_PROP_NAME); 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); - } + clientKey = getClientKeyFromProperties(prop); } if (clientID == null || clientKey == null || clientID.isEmpty() || clientKey.isEmpty()) { LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS @@ -937,42 +883,111 @@ public class StdPolicyEngine { setEnvironment(prop); // Initializing the values. init(); + readPdpProperites(prop); + // Get JUNIT property from properties file when running tests + checkJunit(prop); + } + + private void readPdpProperites(final Properties prop) throws PolicyEngineException { // Check the Keys for PDP_URLs - Collection<Object> unsorted = prop.keySet(); - @SuppressWarnings({ "rawtypes", "unchecked" }) - List<String> sorted = new ArrayList(unsorted); - Collections.sort(sorted); - for (String propKey : sorted) { - if (propKey.startsWith("PDP_URL")) { - String checkVal = prop.getProperty(propKey); - if (checkVal == null) { + 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 + "Properties file doesn't have the PDP_URL parameter"); } - if (checkVal.contains(";")) { - List<String> pdpDefault = new ArrayList<>(Arrays.asList(checkVal.split("\\s*;\\s*"))); - int pdpCount = 0; - while (pdpCount < pdpDefault.size()) { - String pdpVal = pdpDefault.get(pdpCount); + if (propertyValue.contains(SEMICOLLON)) { + final List<String> pdpDefault = Arrays.asList(propertyValue.split(REGEX)); + for (final String pdpVal : pdpDefault) { readPDPParam(pdpVal); - pdpCount++; } } else { - readPDPParam(checkVal); + 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"); + } + } + + 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); + } + } + + 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_SYSTEM_ERROR + "Cannot Load the Properties file", exception); + } + } + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath); + throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file"); + } + + 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 + "Cannot Proceed without PDP_URLs"); + XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL " + e.getMessage()); } - // Get JUNIT property from properties file when running tests - checkJunit(prop); } - private static void checkJunit(Properties prop) { - String junitFlag = prop.getProperty("JUNIT"); + private List<String> getPropertyValueAsList(final String propertyValue, final String split) { + if (propertyValue.contains(split)) { + return Arrays.asList(propertyValue.split(split)); + } + final List<String> 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 { @@ -989,8 +1004,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())) { @@ -1000,23 +1015,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<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); + private void readPDPParam(final String pdpVal) throws PolicyEngineException { + if (pdpVal.contains(COMMA)) { + final List<String> 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); @@ -1034,13 +1049,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 ("ueb".equals(notificationType.get(0))) { + if (UEB.equals(notificationType.get(0))) { if (this.uebThread) { AutoClientUEB.setAuto(scheme, handler); this.uebThread = registerUEBThread.isAlive(); @@ -1059,7 +1074,7 @@ public class StdPolicyEngine { } if (pdps != null) { - if ("ueb".equals(notificationType.get(0)) && !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); @@ -1092,7 +1107,7 @@ public class StdPolicyEngine { PDPNotification notification; if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS) || this.scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) { - if ("ueb".equals(notificationType.get(0))) { + if (UEB.equals(notificationType.get(0))) { ManualClientEndUEB.start(pdps.get(0), notificationURLList, UNIQUEID); notification = ManualClientEndUEB.result(scheme); } else if (notificationType.get(0).equals(DMAAP)) { @@ -1115,9 +1130,9 @@ public class StdPolicyEngine { /* * Setting the Scheme. */ - public void setScheme(NotificationScheme scheme) { + public void setScheme(final NotificationScheme scheme) { this.scheme = scheme; - if ("ueb".equals(notificationType.get(0))) { + 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); @@ -1150,10 +1165,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 ("ueb".equals(notificationType.get(0))) { + if (UEB.equals(notificationType.get(0))) { this.uebClientThread.terminate(); this.uebThread = false; } else if (notificationType.get(0).equals(DMAAP)) { @@ -1168,19 +1184,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); @@ -1188,10 +1196,15 @@ public class StdPolicyEngine { return pushPolicyImpl(pushPolicyParameters).getResponseMessage(); } - public String createUpdateConfigPolicy(String policyName, String policyDescription, String onapName, - String configName, Map<String, String> 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<String, String> 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); } @@ -1199,29 +1212,25 @@ public class StdPolicyEngine { /* * Create Config Policy API Implementation */ - public String createUpdateConfigPolicyImpl(String policyName, String policyDescription, String onapName, - String configName, Map<String, String> 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<String, String> 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<AttributeType, Map<String, String>> attributes = new HashMap<>(); + + final Map<AttributeType, Map<String, String>> attributes = new HashMap<>(); attributes.put(AttributeType.MATCHING, configAttributes); + policyParameters.setAttributes(attributes); policyParameters.setConfigBodyType(PolicyType.valueOf(configType)); policyParameters.setConfigBody(body); @@ -1229,18 +1238,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); } @@ -1248,38 +1261,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(); @@ -1307,4 +1320,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<String> getNotificationType() { + return notificationType; + } + + // Added for test + List<String> getNotificationURLList() { + return notificationURLList; + } + +} diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/utils/PolicyCommonConfigConstants.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/utils/PolicyCommonConfigConstants.java new file mode 100644 index 000000000..29d95de6a --- /dev/null +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/utils/PolicyCommonConfigConstants.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.std.utils; + +public final class PolicyCommonConfigConstants { + + public static final String CONFIG_NAME = "ConfigName"; + + public static final String ONAP_NAME = "ONAPName"; + + private PolicyCommonConfigConstants() {} +} diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/utils/PolicyConfigConstants.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/utils/PolicyConfigConstants.java new file mode 100644 index 000000000..b6a13a69f --- /dev/null +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/utils/PolicyConfigConstants.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.std.utils; + +public final class PolicyConfigConstants { + + public static final String HTTP = "http"; + public static final String REGEX = "\\s*;\\s*"; + public static final String PDP_VALUE_REGEX = "\\s*,\\s*"; + public static final String COMMA = ","; + public static final String SEMICOLLON = ";"; + + public static final String PDP_URL_PROP_NAME = "PDP_URL"; + public static final String CLIENT_KEY_PROP_NAME = "CLIENT_KEY"; + public static final String CLIENT_ID_PROP_NAME = "CLIENT_ID"; + public static final String UEB_API_SECRET_PROP_NAME = "UEB_API_SECRET"; + public static final String UEB_API_KEY_PROP_NAME = "UEB_API_KEY"; + public static final String NOTIFICATION_TOPIC_PROP_NAME = "NOTIFICATION_TOPIC"; + public static final String NOTIFICATION_SERVERS_PROP_NAME = "NOTIFICATION_SERVERS"; + public static final String NOTIFICATION_TYPE_PROP_NAME = "NOTIFICATION_TYPE"; + public static final String ENVIRONMENT_PROP_NAME = "ENVIRONMENT"; + public static final String JUNIT_PROP_NAME = "JUNIT"; + + public static final String UEB = "ueb"; + + public static final String ERROR_AUTH_GET_PERM = + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to: "; + public static final String DEFAULT_NOTIFICATION = "websocket"; + public static final String ERROR_DATA_ISSUE = "Invalid Data is given."; + public static final String DMAAP = "dmaap"; + public static final String ERROR_INVALID_PDPS = "Unable to get valid Response from PDP(s) "; + public static final String ERROR_WHILE_CONNECTING = "Error while connecting to "; + + public static final String TEST_POLICY_NAME = "Policy Name: listConfigTest"; + + public static final String SEND_EVENT_RESOURCE_NAME = "sendEvent"; + public static final String GET_CONFIG_RESOURCE_NAME = "getConfig"; + public static final String GET_DECISION_RESOURCE_NAME = "getDecision"; + public static final String GET_METRICS_RESOURCE_NAME = "getMetrics"; + public static final String PUSH_POLICY_RESOURCE_NAME = "pushPolicy"; + public static final String DELETE_POLICY_RESOURCE_NAME = "deletePolicy"; + public static final String GET_DICTIONARY_ITEMS_RESOURCE_NAME = "getDictionaryItems"; + public static final String UPDATE_DICTIONARY_ITEM_RESOURCE_NAME = "updateDictionaryItem"; + public static final String CREATE_DICTIONARY_ITEM_RESOURCE_NAME = "createDictionaryItem"; + public static final String POLICY_ENGINE_IMPORT_RESOURCE_NAME = "policyEngineImport"; + public static final String UPDATE_POLICY_RESOURCE_NAME = "updatePolicy"; + public static final String CREATE_POLICY_RESOURCE_NAME = "createPolicy"; + + + public static final String PE300 = "PE300"; + + public static final String BAD_REQUEST_STATUS_CODE = "400"; + public static final String UNAUTHORIZED_STATUS_CODE = "401"; + public static final String DATE_FORMAT = "dd-MM-yyyy"; + + private PolicyConfigConstants() {} +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/StdPolicyEngineTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/StdPolicyEngineTest.java new file mode 100644 index 000000000..d4c1012cf --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/StdPolicyEngineTest.java @@ -0,0 +1,912 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.std; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.spy; +import static org.onap.policy.std.utils.PolicyCommonConfigConstants.CONFIG_NAME; +import static org.onap.policy.std.utils.PolicyCommonConfigConstants.ONAP_NAME; +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.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.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.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.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.SEND_EVENT_RESOURCE_NAME; +import static org.onap.policy.std.utils.PolicyConfigConstants.UEB; +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.BufferedWriter; +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +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 org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.DecisionRequestParameters; +import org.onap.policy.api.DecisionResponse; +import org.onap.policy.api.DeletePolicyParameters; +import org.onap.policy.api.DictionaryParameters; +import org.onap.policy.api.DictionaryResponse; +import org.onap.policy.api.EventRequestParameters; +import org.onap.policy.api.ImportParameters; +import org.onap.policy.api.MetricsRequestParameters; +import org.onap.policy.api.MetricsResponse; +import org.onap.policy.api.NotificationScheme; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyConfig; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyDecision; +import org.onap.policy.api.PolicyDecisionException; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.PolicyEventException; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PolicyResponse; +import org.onap.policy.api.PolicyResponseStatus; +import org.onap.policy.api.PolicyType; +import org.onap.policy.api.PushPolicyParameters; +import org.onap.policy.models.APIDictionaryResponse; +import org.onap.policy.models.APIPolicyConfigResponse; +import org.onap.policy.std.utils.PolicyConfigConstants; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; + +@RunWith(MockitoJUnitRunner.class) +public class StdPolicyEngineTest { + + private static final String ONAP_NAME_VAL = "ONAP_NAME"; + private static final String POLICY_VERSION = "1.0.0"; + private static final String POLICY_NAME = "ONAP"; + private static final String COMMENTS = ""; + private static final UUID REQUEST_UUID = UUID.randomUUID(); + private static final String SERVER_NAME = "localhost.com"; + private static final String PDP_PROP_VALUE = "http://localhost:8092/pdp/ , test, test"; + private static final String PDP_PROP_VALUE_1 = "https://localhost:8091/pdp/ , onap, onap"; + private static final String JSON_CONFIGURATION = "{\"name\":\"value\"}"; + private static final String XML_CONFIGURATION = + "<map><entry><string>name</string><string>value</string></entry></map>"; + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private static final String CONFIG_PROPERTIES_FILE = "config_pass.properties"; + private static final String INVALID_CONFIG_PROPERTY_FILE = "config_fail.properties"; + + @Test + public void testStdPolicyEngineInitialize_noException() throws Exception { + final File file = temporaryFolder.newFile(CONFIG_PROPERTIES_FILE); + + creatPropertyFile(file, getDefaultProperties()); + + final StdPolicyEngine policyEngine = new StdPolicyEngine(file.toString(), (String) null); + policyEngine.setScheme(NotificationScheme.MANUAL_NOTIFICATIONS); + assertEquals("TEST", StdPolicyEngine.getEnvironment()); + assertEquals("http://localhost:8092/pdp/", StdPolicyEngine.getPDPURL()); + assertEquals(Arrays.asList(UEB, DMAAP), policyEngine.getNotificationType()); + assertEquals(Arrays.asList(SERVER_NAME, SERVER_NAME), policyEngine.getNotificationURLList()); + } + + @Test + public void testStdPolicyEngineInitializeWithSingleServerName_noException() throws Exception { + final File file = temporaryFolder.newFile(CONFIG_PROPERTIES_FILE); + + final Properties properties = new Properties(); + properties.setProperty(PDP_URL_PROP_NAME, PDP_PROP_VALUE); + properties.setProperty(CLIENT_ID_PROP_NAME, "test"); + properties.setProperty(CLIENT_KEY_PROP_NAME, "test"); + properties.setProperty(NOTIFICATION_TYPE_PROP_NAME, UEB); + properties.setProperty(NOTIFICATION_SERVERS_PROP_NAME, SERVER_NAME); + properties.setProperty(NOTIFICATION_TOPIC_PROP_NAME, "test"); + properties.setProperty(ENVIRONMENT_PROP_NAME, "TEST"); + creatPropertyFile(file, properties); + + final StdPolicyEngine policyEngine = new StdPolicyEngine(file.toString(), (String) null); + policyEngine.setScheme(NotificationScheme.MANUAL_NOTIFICATIONS); + assertEquals(Arrays.asList(SERVER_NAME), policyEngine.getNotificationURLList()); + } + + @Test + public void testStdPolicyEngineInitializeWithSingleNotificationType_noException() throws Exception { + final File file = temporaryFolder.newFile(CONFIG_PROPERTIES_FILE); + + final Properties properties = new Properties(); + properties.setProperty(PDP_URL_PROP_NAME, PDP_PROP_VALUE); + properties.setProperty(CLIENT_ID_PROP_NAME, "test"); + properties.setProperty(CLIENT_KEY_PROP_NAME, "test"); + properties.setProperty(NOTIFICATION_TYPE_PROP_NAME, UEB); + properties.setProperty(NOTIFICATION_SERVERS_PROP_NAME, SERVER_NAME); + properties.setProperty(NOTIFICATION_TOPIC_PROP_NAME, "test"); + properties.setProperty(ENVIRONMENT_PROP_NAME, "TEST"); + creatPropertyFile(file, properties); + + final StdPolicyEngine policyEngine = new StdPolicyEngine(file.toString(), (String) null); + policyEngine.setScheme(NotificationScheme.MANUAL_NOTIFICATIONS); + assertEquals(Arrays.asList(UEB), policyEngine.getNotificationType()); + } + + @Test(expected = PolicyEngineException.class) + public void testStdPolicyEngineInitialize_InvalidPropertyFile_Exception() throws PolicyEngineException { + new StdPolicyEngine("Invalid.properties", (String) null); + } + + @Test(expected = PolicyEngineException.class) + public void testStdPolicyEngineInitialize_InvalidPropertyFileWithExt_Exception() throws Exception { + final File emptyFile = temporaryFolder.newFile("EmptyFile.txt"); + new StdPolicyEngine(emptyFile.toString(), (String) null); + } + + @Test(expected = PolicyEngineException.class) + public void testStdPolicyEngineInitialize_NullArguments_Exception() throws Exception { + new StdPolicyEngine(null, (String) null); + } + + @Test(expected = PolicyEngineException.class) + public void testStdPolicyEngineInitialize_PropertyFileMissingMandatoryProperties_Exception() throws Exception { + final File file = temporaryFolder.newFile(INVALID_CONFIG_PROPERTY_FILE); + final Properties properties = new Properties(); + properties.setProperty(PDP_URL_PROP_NAME, PDP_PROP_VALUE); + creatPropertyFile(file, properties); + + new StdPolicyEngine(file.toString(), (String) null); + } + + @Test + public void testStdPolicyEngineInitialize_MultiplePdp_noException() throws Exception { + final File file = temporaryFolder.newFile(CONFIG_PROPERTIES_FILE); + + final Properties properties = new Properties(); + properties.setProperty(PDP_URL_PROP_NAME, PDP_PROP_VALUE + PolicyConfigConstants.SEMICOLLON + PDP_PROP_VALUE_1); + properties.setProperty(CLIENT_ID_PROP_NAME, "test"); + properties.setProperty(CLIENT_KEY_PROP_NAME, "test"); + properties.setProperty(NOTIFICATION_TYPE_PROP_NAME, UEB + COMMA + DMAAP); + properties.setProperty(NOTIFICATION_SERVERS_PROP_NAME, SERVER_NAME + COMMA + SERVER_NAME); + properties.setProperty(NOTIFICATION_TOPIC_PROP_NAME, "test"); + properties.setProperty(ENVIRONMENT_PROP_NAME, "TEST"); + creatPropertyFile(file, properties); + + final StdPolicyEngine policyEngine = new StdPolicyEngine(file.toString(), (String) null); + policyEngine.setScheme(NotificationScheme.MANUAL_NOTIFICATIONS); + assertEquals("http://localhost:8092/pdp/", StdPolicyEngine.getPDPURL()); + StdPolicyEngine.rotatePDPList(); + assertEquals("https://localhost:8091/pdp/", StdPolicyEngine.getPDPURL()); + assertEquals(Arrays.asList(UEB, DMAAP), policyEngine.getNotificationType()); + assertEquals(Arrays.asList(SERVER_NAME, SERVER_NAME), policyEngine.getNotificationURLList()); + } + + @Test(expected = PolicyEngineException.class) + public void testStdPolicyEngineInitialize_NoPDP_noException() throws Exception { + final File file = temporaryFolder.newFile(CONFIG_PROPERTIES_FILE); + + final Properties properties = new Properties(); + properties.setProperty(CLIENT_ID_PROP_NAME, "test"); + properties.setProperty(CLIENT_KEY_PROP_NAME, "test"); + properties.setProperty(NOTIFICATION_TYPE_PROP_NAME, UEB + COMMA + DMAAP); + properties.setProperty(NOTIFICATION_SERVERS_PROP_NAME, SERVER_NAME + COMMA + SERVER_NAME); + properties.setProperty(NOTIFICATION_TOPIC_PROP_NAME, "test"); + properties.setProperty(ENVIRONMENT_PROP_NAME, "TEST"); + creatPropertyFile(file, properties); + + new StdPolicyEngine(file.toString(), (String) null); + } + + @Test + public void testStdPolicyEngineInitializeNotificationTypeDMMAP_noException() throws Exception { + final File file = temporaryFolder.newFile(CONFIG_PROPERTIES_FILE); + + final Properties properties = new Properties(); + properties.setProperty(PDP_URL_PROP_NAME, PDP_PROP_VALUE); + properties.setProperty(CLIENT_ID_PROP_NAME, "test"); + properties.setProperty(CLIENT_KEY_PROP_NAME, "test"); + properties.setProperty(NOTIFICATION_TYPE_PROP_NAME, DMAAP); + properties.setProperty(NOTIFICATION_SERVERS_PROP_NAME, SERVER_NAME + COMMA + SERVER_NAME); + properties.setProperty(NOTIFICATION_TOPIC_PROP_NAME, "test"); + properties.setProperty(ENVIRONMENT_PROP_NAME, "TEST"); + creatPropertyFile(file, properties); + + final StdPolicyEngine policyEngine = new StdPolicyEngine(file.toString(), (String) null); + policyEngine.setScheme(NotificationScheme.MANUAL_NOTIFICATIONS); + + assertEquals(Arrays.asList(DMAAP), policyEngine.getNotificationType()); + + } + + @Test + public void testStdPolicyEngineSendEvent_noException() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + doReturn(new ResponseEntity<>(getStdPolicyResponse(), HttpStatus.ACCEPTED)).when(spyPolicyEngine) + .callNewPDP(eq(SEND_EVENT_RESOURCE_NAME), any(), any(), any()); + + final Collection<PolicyResponse> actualPolicyResponses = + spyPolicyEngine.sendEvent(Collections.emptyMap(), REQUEST_UUID); + + assertEquals(1, actualPolicyResponses.size()); + + } + + @Test(expected = PolicyEventException.class) + public void testStdPolicyEngineSendEvent_NullEventRequestParameters_Exception() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + spyPolicyEngine.sendEvent((EventRequestParameters) null); + } + + @Test(expected = PolicyEventException.class) + public void testStdPolicyEngineSendEvent_EventRequestParameters_CallPDPThrow401Exception_Exception() + throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + Mockito.doThrow(new RuntimeException(new RestClientException("Error 401"))).when(spyPolicyEngine) + .callNewPDP(any(), any(), any(), any()); + spyPolicyEngine.sendEvent(Collections.emptyMap(), REQUEST_UUID); + } + + @Test + public void testStdPolicyEngineSendEvent_EventRequestParameters_noException() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<StdPolicyResponse[]> stubbedResponse = + new ResponseEntity<>(getStdPolicyResponse(), HttpStatus.ACCEPTED); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(SEND_EVENT_RESOURCE_NAME), any(), any(), any()); + + final EventRequestParameters eventRequestParameters = new EventRequestParameters(); + eventRequestParameters.setEventAttributes(Collections.emptyMap()); + eventRequestParameters.setRequestID(REQUEST_UUID); + + final Collection<PolicyResponse> actualPolicyResponses = spyPolicyEngine.sendEvent(eventRequestParameters); + + assertEquals(1, actualPolicyResponses.size()); + + } + + @Test + public void testStdPolicyEngineGetConfig_ConfigRequestParametersPolicyConfigJSON_noException() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<APIPolicyConfigResponse[]> stubbedResponse = new ResponseEntity<>( + getAPIPolicyConfigResponse(PolicyType.JSON, JSON_CONFIGURATION), HttpStatus.ACCEPTED); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(GET_CONFIG_RESOURCE_NAME), eq(HttpMethod.POST), + any(), any()); + + final Collection<PolicyConfig> actualPolicyResponses = spyPolicyEngine.getConfig(new ConfigRequestParameters()); + + assertEquals(1, actualPolicyResponses.size()); + + final PolicyConfig actualPolicyConfig = actualPolicyResponses.iterator().next(); + assertNotNull(actualPolicyConfig.toJSON()); + + } + + @Test + public void testStdPolicyEngineGetConfig_ConfigRequestParametersPolicyConfigOther_noException() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<APIPolicyConfigResponse[]> stubbedResponse = + new ResponseEntity<>(getAPIPolicyConfigResponse(PolicyType.OTHER, COMMENTS), HttpStatus.ACCEPTED); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(GET_CONFIG_RESOURCE_NAME), eq(HttpMethod.POST), + any(), any()); + + final Collection<PolicyConfig> actualPolicyResponses = spyPolicyEngine.getConfig(new ConfigRequestParameters()); + + assertEquals(1, actualPolicyResponses.size()); + + final PolicyConfig actualPolicyConfig = actualPolicyResponses.iterator().next(); + assertNotNull(actualPolicyConfig.toOther()); + + } + + @Test + public void testStdPolicyEngineGetConfig_ConfigRequestParametersPolicyConfigXML_noException() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<APIPolicyConfigResponse[]> stubbedResponse = new ResponseEntity<>( + getAPIPolicyConfigResponse(PolicyType.XML, XML_CONFIGURATION), HttpStatus.ACCEPTED); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(GET_CONFIG_RESOURCE_NAME), eq(HttpMethod.POST), + any(), any()); + + final Collection<PolicyConfig> actualPolicyResponses = spyPolicyEngine.getConfig(new ConfigRequestParameters()); + + assertEquals(1, actualPolicyResponses.size()); + + final PolicyConfig actualPolicyConfig = actualPolicyResponses.iterator().next(); + assertNotNull(actualPolicyConfig.toXML()); + + } + + @Test + public void testStdPolicyEngineGetConfig_ConfigRequestParametersPolicyConfigProperties_noException() + throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<APIPolicyConfigResponse[]> stubbedResponse = + new ResponseEntity<>(getAPIPolicyConfigResponse(PolicyType.PROPERTIES, COMMENTS), HttpStatus.ACCEPTED); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(GET_CONFIG_RESOURCE_NAME), eq(HttpMethod.POST), + any(), any()); + + final Collection<PolicyConfig> actualPolicyResponses = spyPolicyEngine.getConfig(new ConfigRequestParameters()); + + assertEquals(1, actualPolicyResponses.size()); + + final PolicyConfig actualPolicyConfig = actualPolicyResponses.iterator().next(); + assertNotNull(actualPolicyConfig.toProperties()); + + } + + @Test(expected = PolicyConfigException.class) + public void testStdPolicyEngineSendEvent_ConfigRequestParameters_CallPDPThrow404Exception_Exception() + throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + doThrow(new RuntimeException(new RestClientException("Error 404"))).when(spyPolicyEngine).callNewPDP(any(), + any(), any(), any()); + spyPolicyEngine.getConfig(new ConfigRequestParameters()); + } + + @Test + public void testStdPolicyEngineListConfig_ConfigRequestParametersPolicyConfigProperties_noException() + throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final APIPolicyConfigResponse[] apiPolicyConfigResponse = + getAPIPolicyConfigResponse(PolicyType.JSON, JSON_CONFIGURATION); + + final ResponseEntity<APIPolicyConfigResponse[]> stubbedResponse = + new ResponseEntity<>(apiPolicyConfigResponse, HttpStatus.ACCEPTED); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(GET_CONFIG_RESOURCE_NAME), eq(HttpMethod.POST), + any(), any()); + + final Collection<String> actualResponse = spyPolicyEngine.listConfig(new ConfigRequestParameters()); + assertEquals(1, actualResponse.size()); + assertNotNull(actualResponse.iterator().next()); + + } + + @Test + public void testStdPolicyEngineListConfig_ConfigRequestParametersMessageConfigContainsPE300_noException() + throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final APIPolicyConfigResponse[] apiPolicyConfigResponse = + getAPIPolicyConfigResponse(PolicyType.JSON, JSON_CONFIGURATION, PolicyConfigConstants.PE300); + + final ResponseEntity<APIPolicyConfigResponse[]> stubbedResponse = + new ResponseEntity<>(apiPolicyConfigResponse, HttpStatus.ACCEPTED); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(GET_CONFIG_RESOURCE_NAME), eq(HttpMethod.POST), + any(), any()); + + final Collection<String> actualResponse = spyPolicyEngine.listConfig(new ConfigRequestParameters()); + + assertEquals(1, actualResponse.size()); + + } + + @Test + public void testStdPolicyEngineListConfig_ConfigRequestParametersWithTestProperty_noException() throws Exception { + final Properties defaultProperties = getDefaultProperties(); + defaultProperties.setProperty(PolicyConfigConstants.JUNIT_PROP_NAME, "test"); + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine("test" + CONFIG_PROPERTIES_FILE, defaultProperties); + + final Collection<String> actualResponse = spyPolicyEngine.listConfig(new ConfigRequestParameters()); + + assertEquals(1, actualResponse.size()); + + } + + @Test + public void testStdPolicyEnginGetDecision_PolicyDecision_noException() throws Exception { + + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<StdDecisionResponse> stubbedResponse = + new ResponseEntity<>(getStdDecisionResponse(), HttpStatus.ACCEPTED); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(GET_DECISION_RESOURCE_NAME), eq(HttpMethod.POST), + any(), any()); + + final DecisionResponse actualResponse = + spyPolicyEngine.getDecision(ONAP_NAME_VAL, Collections.emptyMap(), REQUEST_UUID); + + assertNotNull(actualResponse); + } + + @Test(expected = PolicyDecisionException.class) + public void testStdPolicyEngineGetDecision_PolicyDecision_CallPDPThrow400Exception_Exception() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + doThrow(new RuntimeException(new RestClientException("Error 400"))).when(spyPolicyEngine) + .callNewPDP(eq(GET_DECISION_RESOURCE_NAME), eq(HttpMethod.POST), any(), any()); + spyPolicyEngine.getDecision(ONAP_NAME_VAL, Collections.emptyMap(), REQUEST_UUID); + } + + @Test + public void testStdPolicyEnginGetDecision_DecisionRequestParameters_noException() throws Exception { + + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<StdDecisionResponse> stubbedResponse = + new ResponseEntity<>(getStdDecisionResponse(), HttpStatus.ACCEPTED); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(GET_DECISION_RESOURCE_NAME), eq(HttpMethod.POST), + any(), any()); + + final DecisionRequestParameters requestParameters = new DecisionRequestParameters(); + requestParameters.setOnapName(ONAP_NAME_VAL); + requestParameters.setRequestID(REQUEST_UUID); + requestParameters.setDecisionAttributes(Collections.emptyMap()); + + final DecisionResponse actualResponse = spyPolicyEngine.getDecision(requestParameters); + + assertNotNull(actualResponse); + } + + @Test(expected = PolicyDecisionException.class) + public void ttestStdPolicyEnginGetDecision_NullDecisionRequestParameters_Exception() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + spyPolicyEngine.getDecision((DecisionRequestParameters) null); + } + + @Test + public void testStdPolicyEnginGetMetrics_MetricsRequestParameters_noException() throws Exception { + + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<String> stubbedResponse = new ResponseEntity<>("Metrics", HttpStatus.ACCEPTED); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(GET_METRICS_RESOURCE_NAME), eq(HttpMethod.GET), + any(), any()); + + final MetricsResponse actualResponse = spyPolicyEngine.getMetrics(new MetricsRequestParameters()); + assertNotNull(actualResponse); + assertEquals(HttpStatus.ACCEPTED.value(), actualResponse.getResponseCode()); + + } + + @Test + public void testStdPolicyEngineGetMetrics_MetricsRequestParametersCallPDPThrowHttpException_ResponseWithHttpCode() + throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + doThrow(new PolicyException(new HttpClientErrorException(HttpStatus.BAD_GATEWAY))).when(spyPolicyEngine) + .callNewPDP(eq(GET_METRICS_RESOURCE_NAME), eq(HttpMethod.GET), any(), any()); + + final MetricsResponse actualResponse = spyPolicyEngine.getMetrics(new MetricsRequestParameters()); + assertNotNull(actualResponse); + assertEquals(HttpStatus.BAD_GATEWAY.value(), actualResponse.getResponseCode()); + + } + + @Test(expected = PolicyException.class) + public void testStdPolicyEngineGetMetrics_MetricsRequestParametersCallPDPThrowPolicyException_Exception() + throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + doThrow(PolicyException.class).when(spyPolicyEngine).callNewPDP(eq(GET_METRICS_RESOURCE_NAME), + eq(HttpMethod.GET), any(), any()); + + spyPolicyEngine.getMetrics(new MetricsRequestParameters()); + + } + + @Test + public void testStdPolicyEnginPushPolicy_PushPolicyParameters_noException() throws Exception { + + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<String> stubbedResponse = new ResponseEntity<>("Successful", HttpStatus.OK); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(PUSH_POLICY_RESOURCE_NAME), eq(HttpMethod.PUT), + any(), any()); + + final PolicyChangeResponse actualResponse = spyPolicyEngine.pushPolicy(new PushPolicyParameters()); + + assertNotNull(actualResponse); + assertEquals(HttpStatus.OK.value(), actualResponse.getResponseCode()); + } + + @Test + public void testStdPolicyEnginePushPolicy_PushPolicyParametersThrowsHttpClientErrorException_ResponseWithHttpCode() + throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + doThrow(new PolicyException(new HttpClientErrorException(HttpStatus.BAD_GATEWAY))).when(spyPolicyEngine) + .callNewPDP(eq(PUSH_POLICY_RESOURCE_NAME), eq(HttpMethod.PUT), any(), any()); + + final PolicyChangeResponse actualResponse = spyPolicyEngine.pushPolicy(new PushPolicyParameters()); + + assertNotNull(actualResponse); + assertEquals(HttpStatus.BAD_GATEWAY.value(), actualResponse.getResponseCode()); + + } + + @Test(expected = PolicyException.class) + public void testStdPolicyEnginePushPolicy_PushPolicyParameters_Exception() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + doThrow(PolicyException.class).when(spyPolicyEngine).callNewPDP(eq(PUSH_POLICY_RESOURCE_NAME), + eq(HttpMethod.PUT), any(), any()); + + spyPolicyEngine.pushPolicy(new PushPolicyParameters()); + + } + + @Test + public void testStdPolicyEnginDeletePolicy_DeletePolicyParameters_noException() throws Exception { + + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<String> stubbedResponse = new ResponseEntity<>("Successful", HttpStatus.OK); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(DELETE_POLICY_RESOURCE_NAME), + eq(HttpMethod.DELETE), any(), any()); + + final PolicyChangeResponse actualResponse = spyPolicyEngine.deletePolicy(new DeletePolicyParameters()); + + assertNotNull(actualResponse); + assertEquals(HttpStatus.OK.value(), actualResponse.getResponseCode()); + } + + @Test + public void testStdPolicyEnginGetDictionaryItem_DictionaryParameters_noException() throws Exception { + + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<APIDictionaryResponse> stubbedResponse = + new ResponseEntity<>(getAPIDictionaryResponse(), HttpStatus.OK); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(GET_DICTIONARY_ITEMS_RESOURCE_NAME), + eq(HttpMethod.POST), any(), any()); + + final DictionaryResponse actualResponse = spyPolicyEngine.getDictionaryItem(new DictionaryParameters()); + + assertNotNull(actualResponse); + } + + @Test + public void testStdPolicyGetDictionaryItem_DictionaryParametersWithHttp400ExceptionThrown_ResponseWithHttpCode() + throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + doThrow(new RuntimeException(new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Error 400"))) + .when(spyPolicyEngine) + .callNewPDP(eq(GET_DICTIONARY_ITEMS_RESOURCE_NAME), eq(HttpMethod.POST), any(), any()); + + final DictionaryResponse actualResponse = spyPolicyEngine.getDictionaryItem(new DictionaryParameters()); + + assertNotNull(actualResponse); + assertEquals(HttpStatus.BAD_REQUEST.value(), actualResponse.getResponseCode()); + + } + + @Test + public void testStdPolicyGetDictionaryItem_DictionaryParametersWithHttp401ExceptionThrown_ResponseWithHttpCode() + throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + doThrow(new RuntimeException(new HttpClientErrorException(HttpStatus.UNAUTHORIZED, "Error 401"))) + .when(spyPolicyEngine) + .callNewPDP(eq(GET_DICTIONARY_ITEMS_RESOURCE_NAME), eq(HttpMethod.POST), any(), any()); + + final DictionaryResponse actualResponse = spyPolicyEngine.getDictionaryItem(new DictionaryParameters()); + + assertNotNull(actualResponse); + assertEquals(HttpStatus.UNAUTHORIZED.value(), actualResponse.getResponseCode()); + + } + + @Test + public void testStdPolicyGetDictionaryItem_DictionaryParametersWithRunTimeExceptionThrown_ResponseWithHttpCode() + throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + doThrow(new RuntimeException(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "Error"))) + .when(spyPolicyEngine) + .callNewPDP(eq(GET_DICTIONARY_ITEMS_RESOURCE_NAME), eq(HttpMethod.POST), any(), any()); + + final DictionaryResponse actualResponse = spyPolicyEngine.getDictionaryItem(new DictionaryParameters()); + + assertNotNull(actualResponse); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), actualResponse.getResponseCode()); + + } + + @Test + public void testStdPolicyEnginCreateDictionaryItem_DictionaryParameters_noException() throws Exception { + + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<String> stubbedResponse = new ResponseEntity<>("Successful", HttpStatus.OK); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(CREATE_DICTIONARY_ITEM_RESOURCE_NAME), + eq(HttpMethod.PUT), any(), any()); + + final PolicyChangeResponse actualResponse = spyPolicyEngine.createDictionaryItem(new DictionaryParameters()); + + assertNotNull(actualResponse); + assertEquals(HttpStatus.OK.value(), actualResponse.getResponseCode()); + } + + @Test + public void testStdPolicyEnginUpdateDictionaryItem_DictionaryParameters_noException() throws Exception { + + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<String> stubbedResponse = new ResponseEntity<>("Successful", HttpStatus.OK); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(UPDATE_DICTIONARY_ITEM_RESOURCE_NAME), + eq(HttpMethod.PUT), any(), any()); + + final PolicyChangeResponse actualResponse = spyPolicyEngine.updateDictionaryItem(new DictionaryParameters()); + + assertNotNull(actualResponse); + assertEquals(HttpStatus.OK.value(), actualResponse.getResponseCode()); + } + + @Test + public void testStdPolicyEnginPolicyEngineImport_ImportParameters_noException() throws Exception { + final File emptyfile = temporaryFolder.newFile("emptyFile.txt"); + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<String> stubbedResponse = new ResponseEntity<>("Successful", HttpStatus.OK); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(POLICY_ENGINE_IMPORT_RESOURCE_NAME), + eq(HttpMethod.POST), any(), any()); + + final ImportParameters importParameters = new ImportParameters(); + importParameters.setFilePath(emptyfile.toString()); + final PolicyChangeResponse actualResponse = spyPolicyEngine.policyEngineImport(importParameters); + + assertNotNull(actualResponse); + assertEquals(HttpStatus.OK.value(), actualResponse.getResponseCode()); + } + + @Test + public void testStdPolicyEnginCreatePolicy_PolicyParameters_noException() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<String> stubbedResponse = new ResponseEntity<>("Successful", HttpStatus.OK); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(CREATE_POLICY_RESOURCE_NAME), eq(HttpMethod.PUT), + any(), any()); + + final PolicyChangeResponse actualResponse = spyPolicyEngine.createPolicy(new PolicyParameters()); + + assertNotNull(actualResponse); + assertEquals(HttpStatus.OK.value(), actualResponse.getResponseCode()); + } + + @Test + public void testStdPolicyEnginUpdatePolicy_PolicyParameters_noException() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<String> stubbedResponse = new ResponseEntity<>("Successful", HttpStatus.OK); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(UPDATE_POLICY_RESOURCE_NAME), eq(HttpMethod.PUT), + any(), any()); + + final PolicyChangeResponse actualResponse = spyPolicyEngine.updatePolicy(new PolicyParameters()); + + assertNotNull(actualResponse); + assertEquals(HttpStatus.OK.value(), actualResponse.getResponseCode()); + } + + @Test(expected = PolicyException.class) + public void testStdPolicyEnginPushPolicy_NullValues_Exception() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + spyPolicyEngine.pushPolicy(null, null, null, null, null); + } + + @Test(expected = PolicyException.class) + public void testStdPolicyEnginPushPolicy_EmptyPolicyScope_Exception() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + spyPolicyEngine.pushPolicy("", null, null, null, null); + } + + @Test(expected = PolicyException.class) + public void testStdPolicyEnginPushPolicy_EmptyPolicyName_Exception() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + spyPolicyEngine.pushPolicy("POLICY_SCOPE", "", null, null, null); + } + + @Test + public void testStdPolicyEnginPushPolicy_PolicyParameters_noException() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<String> stubbedResponse = new ResponseEntity<>("Successful", HttpStatus.OK); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(PUSH_POLICY_RESOURCE_NAME), eq(HttpMethod.PUT), + any(), any()); + + final String actualResponse = + spyPolicyEngine.pushPolicy("POLICY_SCOPE", ONAP_NAME_VAL, "POLICY_TYPE", "POLICY_GROUP", REQUEST_UUID); + + assertNotNull(actualResponse); + } + + @Test + public void testStdPolicyEnginCreateUpdateConfigPolicy_PolicyParameters_noException() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<String> stubbedResponse = new ResponseEntity<>("Successful", HttpStatus.OK); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(UPDATE_POLICY_RESOURCE_NAME), eq(HttpMethod.PUT), + any(), any()); + + final String actualResponse = spyPolicyEngine.createUpdateConfigPolicy("POLICY_NAME", ONAP_NAME_VAL, + ONAP_NAME_VAL, "CONFIG_NAME", Collections.emptyMap(), PolicyType.JSON.toString().toUpperCase(), "", + "POLICY_SCOPE", REQUEST_UUID, "", "", "", new Date().toString(), true); + + assertNotNull(actualResponse); + } + + @Test(expected = PolicyException.class) + public void testStdPolicyEnginCreateUpdateConfigPolicy_NullPolicyName_Exception() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + spyPolicyEngine.createUpdateConfigPolicy(null, null, null, null, null, null, null, null, null, null, null, null, + null, true); + } + + @Test + public void testStdPolicyEnginCreateUpdateConfigFirewallPolicy_PolicyParameters_noException() throws Exception { + final StdPolicyEngine spyPolicyEngine = getSpyPolicyEngine(); + + final ResponseEntity<String> stubbedResponse = new ResponseEntity<>("Successful", HttpStatus.OK); + + doReturn(stubbedResponse).when(spyPolicyEngine).callNewPDP(eq(UPDATE_POLICY_RESOURCE_NAME), eq(HttpMethod.PUT), + any(), any()); + + final String actualResponse = + spyPolicyEngine.createUpdateConfigFirewallPolicy("POLICY_NAME", getJsonObject(JSON_CONFIGURATION), + "POLICY_SCOPE", REQUEST_UUID, "", "", "", new Date().toString(), true); + + assertNotNull(actualResponse); + } + + private JsonObject getJsonObject(final String jsonString) { + try (final JsonReader jsonReader = Json.createReader(new StringReader(jsonString));) { + return jsonReader.readObject(); + } + } + + private StdPolicyEngine getSpyPolicyEngine() throws IOException, PolicyEngineException { + return getSpyPolicyEngine(CONFIG_PROPERTIES_FILE, getDefaultProperties()); + } + + private StdPolicyEngine getSpyPolicyEngine(final String filename, final Properties properties) + throws IOException, PolicyEngineException { + final File file = temporaryFolder.newFile(filename); + + creatPropertyFile(file, properties); + + final StdPolicyEngine spyPolicyEngine = spy(new StdPolicyEngine(file.toString(), (String) null)); + spyPolicyEngine.setScheme(NotificationScheme.MANUAL_NOTIFICATIONS); + return spyPolicyEngine; + } + + private Properties getDefaultProperties() { + final Properties properties = new Properties(); + properties.setProperty(PDP_URL_PROP_NAME, PDP_PROP_VALUE); + properties.setProperty(CLIENT_ID_PROP_NAME, "test"); + properties.setProperty(CLIENT_KEY_PROP_NAME, "test"); + properties.setProperty(NOTIFICATION_TYPE_PROP_NAME, UEB + COMMA + DMAAP); + properties.setProperty(NOTIFICATION_SERVERS_PROP_NAME, SERVER_NAME + COMMA + SERVER_NAME); + properties.setProperty(NOTIFICATION_TOPIC_PROP_NAME, "test"); + properties.setProperty(ENVIRONMENT_PROP_NAME, "TEST"); + properties.setProperty(PolicyConfigConstants.JUNIT_PROP_NAME, "false"); + return properties; + } + + private StdDecisionResponse getStdDecisionResponse() { + final StdDecisionResponse response = new StdDecisionResponse(); + response.setDecision(PolicyDecision.PERMIT); + response.setDetails(PolicyDecision.PERMIT.name()); + + return response; + } + + private APIDictionaryResponse getAPIDictionaryResponse() { + final APIDictionaryResponse response = new APIDictionaryResponse(); + response.setResponseCode(0); + response.setResponseMessage(""); + response.setDictionaryData(Collections.<String, String>emptyMap()); + response.setDictionaryJson(Collections.<String, String>emptyMap()); + return response; + } + + private StdPolicyResponse[] getStdPolicyResponse() { + final StdPolicyResponse response = new StdPolicyResponse(); + response.setPolicyResponseStatus(PolicyResponseStatus.ACTION_TAKEN); + return new StdPolicyResponse[] {response}; + } + + private void creatPropertyFile(final File file, final Properties properties) throws IOException { + try (final BufferedWriter bufferedWriter = Files.newBufferedWriter(file.toPath());) { + properties.store(bufferedWriter, COMMENTS); + } + } + + private APIPolicyConfigResponse[] getAPIPolicyConfigResponse(final PolicyType policyType, + final String configuration) { + + return getAPIPolicyConfigResponse(policyType, configuration, null); + } + + private APIPolicyConfigResponse[] getAPIPolicyConfigResponse(final PolicyType policyType, + final String configuration, final String policyConfigMessage) { + final APIPolicyConfigResponse configResponse = new APIPolicyConfigResponse(); + configResponse.setConfig(configuration); + configResponse.setMatchingConditions(getMatchingConditions()); + configResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_RETRIEVED); + configResponse.setPolicyName(POLICY_NAME); + configResponse.setPolicyType(PolicyConfigType.BRMS_RAW); + configResponse.setType(policyType); + configResponse.setPolicyVersion(POLICY_VERSION); + configResponse.setProperty(Collections.emptyMap()); + configResponse.setPolicyConfigMessage(policyConfigMessage); + + return new APIPolicyConfigResponse[] {configResponse}; + } + + private Map<String, String> getMatchingConditions() { + final Map<String, String> attributes = new HashMap<>(); + attributes.put(ONAP_NAME, POLICY_NAME); + attributes.put(CONFIG_NAME, "Configuration_name"); + return attributes; + } + +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineTest.java index abfab075b..5c6094b01 100644 --- a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineTest.java +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineTest.java @@ -23,148 +23,401 @@ package org.onap.policy.test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; - +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.any; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; - +import java.util.Collections; +import java.util.UUID; import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.internal.util.reflection.Whitebox; +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.DecisionRequestParameters; +import org.onap.policy.api.DeletePolicyParameters; +import org.onap.policy.api.DictionaryParameters; +import org.onap.policy.api.EventRequestParameters; +import org.onap.policy.api.ImportParameters; +import org.onap.policy.api.MetricsRequestParameters; import org.onap.policy.api.NotificationScheme; +import org.onap.policy.api.PolicyConfigException; import org.onap.policy.api.PolicyEngine; import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PushPolicyParameters; import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.std.StdPolicyEngine; public class PolicyEngineTest { - private static final Logger logger = FlexLogger.getLogger(PolicyEngineTest.class); - private PolicyEngine policyEngine = null; - private String filePath = null; - - @Test - public void testPolicyEngineForFail() { - filePath = null; - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNull(policyEngine); - // Test even for this case. - filePath = "NotNull"; - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNull(policyEngine); - } - - @Test - public void testPolicyEngineforPropertyFileError() { - filePath = "Test/config_error.property"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNull(policyEngine); - } - - @Test - public void testPolicyEngineforPDPURLError() { - String filePath = "Test/config_fail.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNull(policyEngine); - } - - @Test - public void testPolicyEngineForPass() { - String filePath = "Test/config_pass.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNotNull(policyEngine); - } - - @Test - public void testPolicyEngineForUEBPass() { - String filePath = "Test/config_UEB_pass.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNotNull(policyEngine); - } - - - @Test - public void testPolicyEngineForUEBBadType() { - String filePath = "Test/config_UEB_bad_type.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNotNull(policyEngine); - } - - @Test - public void testPolicyEngineForUEBBadServerType() { - String filePath = "Test/config_UEB_badservers.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNotNull(policyEngine); - } - - @Test - public void testPolicyEngineNotficationAutoUEB() { - String filePath = "Test/config_UEB_pass.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - policyEngine.setScheme(NotificationScheme.AUTO_ALL_NOTIFICATIONS); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNotNull(policyEngine); - } - - @Test - public void testPolicyEngineNotficationAuto() { - String filePath = "Test/config_pass.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - policyEngine.setScheme(NotificationScheme.AUTO_ALL_NOTIFICATIONS); - //policyEngine.getNotification(); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNotNull(policyEngine); - } - - public void isFileAvailable(String filePath) { - Path file = Paths.get(filePath); - if (Files.notExists(file)) { - logger.error("File Doesn't Exist "+ file.toString()); - fail("File: " +filePath + " Not found"); - } - } + private static final String ONAP_NAME_VALUE = "ONAP"; + private static final String STD_POLICY_ENGINE_LOCAL_VARIABLE = "stdPolicyEngine"; + private static final UUID REQUEST_UUID = UUID.randomUUID(); + private static final String TEST_CONFIG_PASS_PROPERTIES = "Test/config_pass.properties"; + private static final Logger logger = FlexLogger.getLogger(PolicyEngineTest.class); + private PolicyEngine policyEngine = null; + private String filePath = null; + + private final StdPolicyEngine mockedStdPolicyEngine = Mockito.mock(StdPolicyEngine.class); + + @Test + public void testPolicyEngineForFail() { + PolicyEngine policyEngine = null; + try { + policyEngine = new PolicyEngine(filePath); + } catch (final PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNull(policyEngine); + // Test even for this case. + filePath = "NotNull"; + try { + policyEngine = new PolicyEngine(filePath); + } catch (final PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNull(policyEngine); + } + + @Test + public void testPolicyEngineforPropertyFileError() { + filePath = "Test/config_error.property"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + } catch (final PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNull(policyEngine); + } + + @Test + public void testPolicyEngineforPDPURLError() { + final String filePath = "Test/config_fail.properties"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + } catch (final PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNull(policyEngine); + } + + @Test + public void testPolicyEngineForPass() { + final String filePath = TEST_CONFIG_PASS_PROPERTIES; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + } catch (final PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNotNull(policyEngine); + } + + @Test + public void testPolicyEngineForUEBPass() { + final String filePath = "Test/config_UEB_pass.properties"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + } catch (final PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNotNull(policyEngine); + } + + @Test + public void testPolicyEngineForUEBBadType() { + final String filePath = "Test/config_UEB_bad_type.properties"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + } catch (final PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNotNull(policyEngine); + } + + @Test + public void testPolicyEngineForUEBBadServerType() { + final String filePath = "Test/config_UEB_badservers.properties"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + } catch (final PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNotNull(policyEngine); + } + + @Test + public void testPolicyEngineNotficationAutoUEB() { + final String filePath = "Test/config_UEB_pass.properties"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + policyEngine.setScheme(NotificationScheme.AUTO_ALL_NOTIFICATIONS); + } catch (final PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNotNull(policyEngine); + } + + @Test + public void testPolicyEngineNotficationAuto() { + final String filePath = TEST_CONFIG_PASS_PROPERTIES; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + policyEngine.setScheme(NotificationScheme.AUTO_ALL_NOTIFICATIONS); + // policyEngine.getNotification(); + } catch (final PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNotNull(policyEngine); + } + + @Test + public void testGetConfig_ConfigRequestParameters_StdPolicyEngineGetConfigCalled() + throws PolicyEngineException, PolicyConfigException { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.getConfig(new ConfigRequestParameters()); + + verify(mockedStdPolicyEngine).getConfig(Mockito.any(ConfigRequestParameters.class)); + + } + + @Test + public void testlistConfig_ConfigRequestParameters_StdPolicyEngineListConfigCalled() + throws PolicyEngineException, PolicyConfigException { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.listConfig(new ConfigRequestParameters()); + + verify(mockedStdPolicyEngine).listConfig(any(ConfigRequestParameters.class)); + } + + @Test + public void testSendEvent_EventAttributes_StdPolicyEngineSendEventCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.sendEvent(Collections.emptyMap()); + + verify(mockedStdPolicyEngine).sendEvent(eq(Collections.emptyMap()), eq(null)); + } + + @Test + public void testSendEvent_EventAttributesWithUUID_StdPolicyEngineSendEventCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.sendEvent(Collections.emptyMap(), REQUEST_UUID); + + verify(mockedStdPolicyEngine).sendEvent(eq(Collections.emptyMap()), eq(REQUEST_UUID)); + } + + @Test + public void testSendEvent_EventRequestParameters_StdPolicyEngineSendEventCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.sendEvent(new EventRequestParameters()); + + verify(mockedStdPolicyEngine).sendEvent(any(EventRequestParameters.class)); + } + + @Test + public void testGetDecision_RequestParameters_StdPolicyEngineGetDecisionCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.getDecision(ONAP_NAME_VALUE, Collections.emptyMap()); + + verify(mockedStdPolicyEngine).getDecision(eq(ONAP_NAME_VALUE), eq(Collections.emptyMap()), eq(null)); + } + + @Test + public void testGetDecision_RequestParametersWithUUID_StdPolicyEngineGetDecisionCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.getDecision(ONAP_NAME_VALUE, Collections.emptyMap(), REQUEST_UUID); + + verify(mockedStdPolicyEngine).getDecision(eq(ONAP_NAME_VALUE), eq(Collections.emptyMap()), eq(REQUEST_UUID)); + } + + @Test + public void testGetDecision_DecisionRequestParameters_StdPolicyEngineGetDecisionCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.getDecision(new DecisionRequestParameters()); + + verify(mockedStdPolicyEngine).getDecision(any(DecisionRequestParameters.class)); + } + + @Test + public void testGetDecision_MetricsRequestParameters_StdPolicyEngineGetMetricsCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.getMetrics(new MetricsRequestParameters()); + + verify(mockedStdPolicyEngine).getMetrics(any(MetricsRequestParameters.class)); + } + + @Test + public void testGetDecision_DictionaryParameters_StdPolicyEngineGetDictionaryItemCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.getDictionaryItem(new DictionaryParameters()); + + verify(mockedStdPolicyEngine).getDictionaryItem(any(DictionaryParameters.class)); + } + + @Test + public void testCreateDictionaryItem_DictionaryParameters_StdPolicyEngineCreateDictionaryItemCalled() + throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.createDictionaryItem(new DictionaryParameters()); + + verify(mockedStdPolicyEngine).createDictionaryItem(any(DictionaryParameters.class)); + } + + @Test + public void testUpdateDictionaryItem_DictionaryParameters_StdPolicyEngineDictionaryItemCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.updateDictionaryItem(new DictionaryParameters()); + + verify(mockedStdPolicyEngine).updateDictionaryItem(any(DictionaryParameters.class)); + } + + @Test + public void testCreatePolicy_PolicyParameters_StdPolicyEngineCreatePolicyCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.createPolicy(new PolicyParameters()); + + verify(mockedStdPolicyEngine).createPolicy(any(PolicyParameters.class)); + } + + @Test + public void testUpdatePolicy_PolicyParameters_StdPolicyEngineUpdatePolicyCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.updatePolicy(new PolicyParameters()); + + verify(mockedStdPolicyEngine).updatePolicy(any(PolicyParameters.class)); + } + + @Test + public void testPushPolicy_PushPolicyParameters_StdPolicyEnginePushPolicyCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.pushPolicy(new PushPolicyParameters()); + + verify(mockedStdPolicyEngine).pushPolicy(any(PushPolicyParameters.class)); + } + + @Test + public void testDeletePolicy_DeletePolicyParameters_StdPolicyEngineDeletePolicyCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.deletePolicy(new DeletePolicyParameters()); + + verify(mockedStdPolicyEngine).deletePolicy(any(DeletePolicyParameters.class)); + } + + @Test + public void testPolicyEngineImport_DictionaryParameters_StdPolicyEnginePolicyEngineImportCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.policyEngineImport(new ImportParameters()); + + verify(mockedStdPolicyEngine).policyEngineImport(any(ImportParameters.class)); + } + + @Test + public void testGetNotification_StdPolicyEngineGetNotificationCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.getNotification(); + + verify(mockedStdPolicyEngine, Mockito.atLeastOnce()).getNotification(); + } + + @Test + public void testClearNotification_StdPolicyEngineClearNotificationCalled() throws Exception { + isFileAvailable(TEST_CONFIG_PASS_PROPERTIES); + + final PolicyEngine objUnderTest = new PolicyEngine(TEST_CONFIG_PASS_PROPERTIES); + Whitebox.setInternalState(objUnderTest, STD_POLICY_ENGINE_LOCAL_VARIABLE, mockedStdPolicyEngine); + + objUnderTest.clearNotification(); + + verify(mockedStdPolicyEngine, Mockito.atLeastOnce()).stopNotification(); + } + + public void isFileAvailable(final String filePath) { + final Path file = Paths.get(filePath); + if (Files.notExists(file)) { + logger.error("File Doesn't Exist " + file.toString()); + fail("File: " + filePath + " Not found"); + } + } } |