summaryrefslogtreecommitdiffstats
path: root/PyPDPServer/src
diff options
context:
space:
mode:
authorPamela Dragosh <pdragosh@research.att.com>2017-02-14 19:41:00 -0500
committerPamela Dragosh <pdragosh@research.att.com>2017-02-14 19:41:32 -0500
commit91d04c64771832a0b8815ffbe1f0f9920320d94d (patch)
treefb02d5e1c84a3d91def9a7ee95bc87f9c046cc96 /PyPDPServer/src
parentb9d4caa40ef8e3566ac475968bce17b9b64b6939 (diff)
Initial OpenECOMP policy/engine commit
Change-Id: I7dbff37733b661643dd4d1caefa3d7dccc361b6e Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
Diffstat (limited to 'PyPDPServer/src')
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigFirewallPolicyRequest.java128
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigRequest.java182
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/DeletePolicyRequest.java80
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/EventRequest.java83
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ListConfigRequest.java69
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PolicyCreateUpdateRequest.java124
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PushPolicyRequest.java90
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationFilter.java80
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationService.java232
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/Config.java300
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/Application.java80
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/PolicyEngineServices.java556
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMBeanListener.java75
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitor.java90
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitorMBean.java28
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigFirewallPolicyRequest.java82
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyNameRequest.java39
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyRequest.java187
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepPushPolicyRequest.java66
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PyPolicyConfig.java95
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/Notification.java50
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationController.java149
-rw-r--r--PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationServer.java90
-rw-r--r--PyPDPServer/src/main/resources/log4j.properties56
-rw-r--r--PyPDPServer/src/main/resources/logback.xml252
-rw-r--r--PyPDPServer/src/test/java/testpypdp/AuthorizationTest.java382
-rw-r--r--PyPDPServer/src/test/java/testpypdp/ConfigRequestTest.java82
-rw-r--r--PyPDPServer/src/test/java/testpypdp/NotificationControllerTest.java129
-rw-r--r--PyPDPServer/src/test/java/testpypdp/PolicyEngineServicesTest.java969
29 files changed, 4825 insertions, 0 deletions
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigFirewallPolicyRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigFirewallPolicyRequest.java
new file mode 100644
index 000000000..4a11b8c9e
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigFirewallPolicyRequest.java
@@ -0,0 +1,128 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp;
+
+import java.io.StringReader;
+import java.util.UUID;
+
+import javax.json.Json;
+import javax.json.JsonObject;
+import javax.json.JsonReader;
+
+import org.openecomp.policy.api.PolicyConfigException;
+import org.openecomp.policy.pypdp.model_pojo.PepConfigFirewallPolicyRequest;
+import org.openecomp.policy.std.StdPolicyEngine;
+
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+
+public class ConfigFirewallPolicyRequest {
+
+ private StdPolicyEngine pe;
+ public ConfigFirewallPolicyRequest(StdPolicyEngine pe){
+ this.pe= pe;
+ }
+
+ public String run(PepConfigFirewallPolicyRequest pep, String requestID, String operation, String userID, String passcode) {
+
+ String result = null;
+
+ // construct a UUID from the request string
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ }
+ catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ PolicyLogger.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }
+
+ if (pep.getPolicyName()!= null && !pep.getPolicyName().isEmpty()) {
+ if (pep.getFirewallJson() != null && !pep.getFirewallJson().isEmpty()) {
+ if (pep.getPolicyScope() != null && !pep.getPolicyScope().isEmpty()) {
+ try {
+
+ JsonObject json = stringToJson(pep.getFirewallJson());
+
+ if(!json.toString().contains("errorMessage")){
+ if (operation.equalsIgnoreCase("create")) {
+ result = pe.createConfigFirewallPolicy(pep.getPolicyName(), json, pep.getPolicyScope(), requestUUID, userID, passcode,
+ pep.getRiskLevel(), pep.getRiskType(), pep.getGuard(), pep.getTtlDate());
+ } else {
+ result = pe.updateConfigFirewallPolicy(pep.getPolicyName(), json, pep.getPolicyScope(), requestUUID, userID, passcode,
+ pep.getRiskLevel(), pep.getRiskType(), pep.getGuard(), pep.getTtlDate());
+ }
+ } else {
+ result = XACMLErrorConstants.ERROR_SCHEMA_INVALID + "BAD REQUEST: Invalid Json for firewallJson: " + pep.getFirewallJson();
+ }
+ } catch (PolicyConfigException e) {
+ result = e.getMessage();
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ } else {
+ result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyScope was null or empty.";
+ }
+ } else {
+ result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: firewallJson was null or empty.";
+ }
+ } else {
+ result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyName was null or empty.";
+ }
+
+ return result;
+
+ }
+
+ private JsonObject stringToJson(String jsonString) {
+
+ JsonObject json = null;
+ if (jsonString != null) {
+
+ try {
+
+ //Read jsonBody to JsonObject
+ StringReader in = null;
+
+ in = new StringReader(jsonString);
+
+ JsonReader jsonReader = Json.createReader(in);
+ json = jsonReader.readObject();
+
+ } catch (Exception e) {
+ String jsonError = "{\"errorMessage\": \"" + e.getMessage() + "\"}";
+ StringReader error = null;
+ error = new StringReader(jsonError);
+ JsonReader jsonReader = Json.createReader(error);
+ JsonObject badJson = jsonReader.readObject();
+ return badJson;
+ }
+
+ }
+
+ return json;
+ }
+
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigRequest.java
new file mode 100644
index 000000000..694d010f3
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigRequest.java
@@ -0,0 +1,182 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp;
+
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+
+import javax.json.JsonObject;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.openecomp.policy.api.ConfigRequestParameters;
+import org.openecomp.policy.api.PolicyConfig;
+import org.openecomp.policy.api.PolicyConfigException;
+import org.openecomp.policy.api.PolicyConfigStatus;
+import org.openecomp.policy.api.PolicyType;
+import org.openecomp.policy.pypdp.model_pojo.PepConfigPolicyNameRequest;
+import org.openecomp.policy.pypdp.model_pojo.PyPolicyConfig;
+import org.openecomp.policy.std.StdPolicyConfig;
+import org.openecomp.policy.std.StdPolicyEngine;
+import org.w3c.dom.Document;
+
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+
+public class ConfigRequest {
+
+ private StdPolicyEngine pe;
+ public ConfigRequest(StdPolicyEngine pe){
+ this.pe= pe;
+ }
+
+ public Collection<PyPolicyConfig> run(ConfigRequestParameters pep, String requestID, String userID, String passcode) {
+ PolicyLogger.debug("... Request Params : \n"
+ + "configName " + pep.getConfigName() + "\n"
+ + "ecompName" + pep.getEcompName() + "\n"
+ + "policyName" + pep.getPolicyName() + "\n");
+ StdPolicyConfig policyConfig = new StdPolicyConfig();
+ Collection<PyPolicyConfig> result = new ArrayList<PyPolicyConfig>();
+ // construct a UUID from the request string
+ if(pep.getRequestID()==null){
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ }
+ catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ PolicyLogger.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }
+ pep.setRequestID(requestUUID);
+ }
+ try {
+ PolicyLogger.debug("\n\n calling PEP.. ");
+ Collection<PolicyConfig> pConfigs = pe.configRequest(pep, userID, passcode);
+ for(PolicyConfig pConfig: pConfigs){
+ PyPolicyConfig pyPolicyConfig = checkResponse(pConfig);
+ result.add(pyPolicyConfig);
+ }
+ return result;
+ } catch(Exception e){
+ policyConfig.setConfigStatus(e.getMessage(), PolicyConfigStatus.CONFIG_NOT_FOUND);
+ PyPolicyConfig pyPolicyConfig = checkResponse(policyConfig);
+ result.add(pyPolicyConfig);
+ return result;
+ }
+ }
+
+ public Collection<PyPolicyConfig> run(PepConfigPolicyNameRequest pep, String requestID, String userID, String passcode) {
+ PolicyLogger.debug("... Request Params : \n"
+ + "policyName" + pep.getPolicyName() + "\n");
+ StdPolicyConfig policyConfig = new StdPolicyConfig();
+ Collection<PyPolicyConfig> result = new ArrayList<PyPolicyConfig>();
+ // construct a UUID from the request string
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ }
+ catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ PolicyLogger.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }
+ if(pep.getPolicyName()!= null && !pep.getPolicyName().isEmpty()) {
+ try {
+ Collection<PolicyConfig> pConfigs = pe.configPolicyName(pep.getPolicyName(), requestUUID, userID, passcode);
+ for(PolicyConfig pConfig: pConfigs){
+ PyPolicyConfig pyPolicyConfig = checkResponse(pConfig);
+ result.add(pyPolicyConfig);
+ }
+ return result;
+ } catch (PolicyConfigException e) {
+ policyConfig.setConfigStatus(e.getMessage(), PolicyConfigStatus.CONFIG_NOT_FOUND);
+ PyPolicyConfig pyPolicyConfig = checkResponse(policyConfig);
+ result.add(pyPolicyConfig);
+ return result;
+ }
+ }
+ else {
+ policyConfig.setConfigStatus(XACMLErrorConstants.ERROR_DATA_ISSUE + "PolicyFile Name is empty", PolicyConfigStatus.CONFIG_NOT_FOUND);
+ PyPolicyConfig pyPolicyConfig = checkResponse(policyConfig);
+ result.add(pyPolicyConfig);
+ return result;
+ }
+ }
+
+ public PyPolicyConfig checkResponse(PolicyConfig pConfig) {
+ PyPolicyConfig policyConfig = new PyPolicyConfig();
+ policyConfig.setPolicyConfigMessage(pConfig.getPolicyConfigMessage());
+ policyConfig.setPolicyConfigStatus(pConfig.getPolicyConfigStatus());
+ policyConfig.setType(pConfig.getType());
+ policyConfig.setPolicyName(pConfig.getPolicyName());
+ policyConfig.setMatchingConditions(pConfig.getMatchingConditions());
+ policyConfig.setResponseAttributes(pConfig.getResponseAttributes());
+ policyConfig.setPolicyVersion(pConfig.getPolicyVersion());
+ if (pConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)) {
+ PolicyType policyType = policyConfig.getType();
+ if(policyType.equals(PolicyType.PROPERTIES)) {
+ Properties properties = pConfig.toProperties();
+ Map<String, String> propVal = new HashMap<String, String>();
+ for(String name: properties.stringPropertyNames()) {
+ propVal.put(name, properties.getProperty(name));
+ }
+ policyConfig.setProperty(propVal);
+ } else if(policyType.equals(PolicyType.OTHER)) {
+ String other = pConfig.toOther();
+ policyConfig.setConfig(other);
+ } else if (policyType.equals(PolicyType.JSON)) {
+ JsonObject json = pConfig.toJSON();
+ policyConfig.setConfig(json.toString());
+ } else if (policyType.equals(PolicyType.XML)) {
+ Document document = pConfig.toXML();
+ DOMSource domSource = new DOMSource(document);
+ StringWriter writer = new StringWriter();
+ StreamResult result = new StreamResult(writer);
+ TransformerFactory tf = TransformerFactory.newInstance();
+ Transformer transformer;
+ try {
+ transformer = tf.newTransformer();
+ transformer.transform(domSource, result);
+ policyConfig.setConfig(writer.toString());
+ } catch (TransformerException e) {
+ policyConfig.setConfig(null);
+ policyConfig.setPolicyConfigMessage(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "XML error in the Configuration. " + e.getMessage());
+ policyConfig.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
+ }
+ }
+ } else {
+ policyConfig.setConfig(null);
+ }
+ return policyConfig;
+ }
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/DeletePolicyRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/DeletePolicyRequest.java
new file mode 100644
index 000000000..0ca5bb0d2
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/DeletePolicyRequest.java
@@ -0,0 +1,80 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp;
+
+import java.util.UUID;
+
+import org.openecomp.policy.api.DeletePolicyParameters;
+import org.openecomp.policy.api.PolicyConfigException;
+import org.openecomp.policy.std.StdPolicyEngine;
+
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+
+public class DeletePolicyRequest {
+ private StdPolicyEngine pe;
+ public DeletePolicyRequest(StdPolicyEngine pe){
+ this.pe= pe;
+ }
+
+ public String run(DeletePolicyParameters pep, String requestID, String userID, String passcode) {
+
+ String result = null;
+
+ // construct a UUID from the request string
+ if(pep.getRequestID()==null){
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ pep.setRequestID(UUID.fromString(requestID));
+ }
+ catch (IllegalArgumentException e) {
+ pep.setRequestID(UUID.randomUUID());
+ PolicyLogger.info("Generated Random UUID: " + pep.getRequestID().toString());
+ }
+ }
+ }
+
+ if (pep.getPolicyName()!= null && !pep.getPolicyName().isEmpty()) {
+ if (pep.getPolicyComponent() != null && !pep.getPolicyComponent().isEmpty()) {
+
+ try {
+
+ result = pe.deletePolicy(pep, userID, passcode).getResponseMessage();
+
+ } catch (PolicyConfigException e) {
+ result = e.getMessage();
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ } else {
+ result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyComponent was null or empty.";
+ }
+ } else {
+ result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyName was null or empty.";
+ }
+
+ return result;
+
+ }
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/EventRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/EventRequest.java
new file mode 100644
index 000000000..021b3d7f0
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/EventRequest.java
@@ -0,0 +1,83 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.UUID;
+
+import org.openecomp.policy.api.EventRequestParameters;
+import org.openecomp.policy.api.PolicyResponse;
+import org.openecomp.policy.api.PolicyResponseStatus;
+import org.openecomp.policy.std.StdPolicyEngine;
+import org.openecomp.policy.std.StdPolicyResponse;
+
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+
+public class EventRequest {
+
+ private StdPolicyEngine pe;
+ public EventRequest(StdPolicyEngine pe){
+ this.pe= pe;
+ }
+
+ public Collection<PolicyResponse> run(EventRequestParameters pep, String requestID, String userID, String passcode){
+ StdPolicyResponse policyResponse = new StdPolicyResponse();
+ Collection<PolicyResponse> result = new ArrayList<PolicyResponse>();
+ // construct a UUID from the request string
+ if(pep.getRequestID()==null){
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ }
+ catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ PolicyLogger.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }
+ pep.setRequestID(requestUUID);
+ }
+ try {
+ Collection<PolicyResponse> pResponses = pe.event(pep.getEventAttributes(), pep.getRequestID(), userID, passcode);
+ for(PolicyResponse pResponse: pResponses){
+ pResponse = checkResponse(pResponse);
+ result.add(pResponse);
+ }
+ return result;
+ } catch(Exception e){
+ policyResponse.setPolicyResponseStatus(e.getMessage(), PolicyResponseStatus.NO_ACTION_REQUIRED);
+ policyResponse = checkResponse(policyResponse);
+ result.add(policyResponse);
+ return result;
+ }
+ }
+
+ private StdPolicyResponse checkResponse(PolicyResponse pResponse) {
+ StdPolicyResponse policyResponse= new StdPolicyResponse();
+ policyResponse.setActionAdvised(pResponse.getActionAdvised());
+ policyResponse.setActionTaken(pResponse.getActionTaken());
+ policyResponse.setPolicyResponseMessage(pResponse.getPolicyResponseMessage());
+ policyResponse.setPolicyResponseStatus(pResponse.getPolicyResponseStatus());
+ policyResponse.setRequestAttributes(pResponse.getRequestAttributes());
+ return policyResponse;
+ }
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ListConfigRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ListConfigRequest.java
new file mode 100644
index 000000000..8aac105bf
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ListConfigRequest.java
@@ -0,0 +1,69 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.UUID;
+
+import org.openecomp.policy.api.ConfigRequestParameters;
+import org.openecomp.policy.api.PolicyConfigStatus;
+import org.openecomp.policy.std.StdPolicyConfig;
+import org.openecomp.policy.std.StdPolicyEngine;
+
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+
+public class ListConfigRequest {
+
+ private StdPolicyEngine pe;
+ public ListConfigRequest(StdPolicyEngine pe){
+ this.pe= pe;
+ }
+
+ public Collection<String> run(ConfigRequestParameters pep, String requestID, String userID, String passcode) {
+
+ StdPolicyConfig policyConfig = new StdPolicyConfig();
+ Collection<String> configList = new ArrayList<String>();
+
+ // construct a UUID from the request string
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ }
+ catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ PolicyLogger.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }
+ pep.setRequestID(requestUUID);
+ try {
+ PolicyLogger.debug("\n\n calling PEP.. ");
+ configList = pe.listConfigRequest(pep, userID, passcode);
+ return configList;
+ } catch(Exception e){
+ policyConfig.setConfigStatus(e.getMessage(), PolicyConfigStatus.CONFIG_NOT_FOUND);
+ configList.add(policyConfig.getPolicyConfigStatus().toString());
+ return configList;
+ }
+ }
+
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PolicyCreateUpdateRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PolicyCreateUpdateRequest.java
new file mode 100644
index 000000000..56151f483
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PolicyCreateUpdateRequest.java
@@ -0,0 +1,124 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp;
+
+import java.util.UUID;
+
+import org.openecomp.policy.api.PolicyConfigException;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.pypdp.model_pojo.PepConfigPolicyRequest;
+import org.openecomp.policy.std.StdPolicyEngine;
+
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+
+public class PolicyCreateUpdateRequest {
+ private StdPolicyEngine pe;
+ public PolicyCreateUpdateRequest(StdPolicyEngine pe){
+ this.pe= pe;
+ }
+
+ public String run(PolicyParameters pep, String requestID, String operation, String userID, String passcode) {
+ String result = null;
+ if(pep.getRequestID()==null){
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ pep.setRequestID(UUID.fromString(requestID));
+ }
+ catch (IllegalArgumentException e) {
+ pep.setRequestID(UUID.randomUUID());
+ PolicyLogger.info("Generated Random UUID: " + pep.getRequestID().toString());
+ }
+ }
+ }
+ // check if this is create
+ try{
+ if (operation.equalsIgnoreCase("create")) {
+ result = pe.createPolicy(pep, userID, passcode ).getResponseMessage();
+ }else{
+ // this is Update policy.
+ result = pe.updatePolicy(pep, userID, passcode ).getResponseMessage();
+ }
+ }catch(Exception e){
+ result = e.getMessage();
+ }
+ return result;
+ }
+
+ public String run(PepConfigPolicyRequest pep, String requestID, String operation, String userID, String passcode) {
+
+ String result = null;
+
+ // construct a UUID from the request string
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ }
+ catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ PolicyLogger.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }
+
+ if (pep.getPolicyName()!= null && !pep.getPolicyName().isEmpty()) {
+ if (pep.getEcompName() != null && !pep.getEcompName().isEmpty()) {
+ if (pep.getConfigName() != null && !pep.getConfigName().isEmpty()){
+ if (pep.getPolicyScope() != null && !pep.getPolicyScope().isEmpty()) {
+ try {
+
+ if (operation.equalsIgnoreCase("create")) {
+
+ result = pe.createConfigPolicy(pep.getPolicyName(), pep.getPolicyDescription(), pep.getEcompName(),
+ pep.getConfigName(), pep.getConfigAttributes(), pep.getConfigType(), pep.getBody(),
+ pep.getPolicyScope(), requestUUID, userID, passcode, pep.getRiskLevel(), pep.getRiskType(), pep.getGuard(), pep.getTtlDate());
+ } else {
+ result = pe.updateConfigPolicy(pep.getPolicyName(), pep.getPolicyDescription(), pep.getEcompName(),
+ pep.getConfigName(), pep.getConfigAttributes(), pep.getConfigType(), pep.getBody(),
+ pep.getPolicyScope(), requestUUID, userID, passcode, pep.getRiskLevel(), pep.getRiskType(), pep.getGuard(), pep.getTtlDate());
+ }
+
+
+ } catch (PolicyConfigException e) {
+ result = e.getMessage();
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ } else {
+ result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyScope was null or empty.";
+ }
+
+ } else {
+ result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: configName was null or empty.";
+ }
+ } else {
+ result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: ecompName was null or empty.";
+ }
+ } else {
+ result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyName was null or empty.";
+ }
+
+ return result;
+ }
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PushPolicyRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PushPolicyRequest.java
new file mode 100644
index 000000000..47326b326
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PushPolicyRequest.java
@@ -0,0 +1,90 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp;
+
+import java.util.UUID;
+
+import org.openecomp.policy.api.PolicyConfigException;
+import org.openecomp.policy.pypdp.model_pojo.PepPushPolicyRequest;
+import org.openecomp.policy.std.StdPolicyEngine;
+
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+
+import org.openecomp.policy.common.logging.eelf.MessageCodes;
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+
+public class PushPolicyRequest {
+ private StdPolicyEngine pe;
+ public PushPolicyRequest(StdPolicyEngine pe){
+ this.pe= pe;
+ }
+
+ public String run(PepPushPolicyRequest pep, String requestID, String userID, String passcode) {
+
+ String result = null;
+
+ // construct a UUID from the request string
+ UUID requestUUID = null;
+ if (requestID != null && !requestID.isEmpty()) {
+ try {
+ requestUUID = UUID.fromString(requestID);
+ }
+ catch (IllegalArgumentException e) {
+ requestUUID = UUID.randomUUID();
+ PolicyLogger.info("Generated Random UUID: " + requestUUID.toString());
+ }
+ }else{
+ requestUUID = UUID.randomUUID();
+ PolicyLogger.error("No Request UUID Given, hence generating one random ID: " + requestUUID.toString());
+ }
+ String policyName = pep.getPolicyName();
+ String policyScope = pep.getPolicyScope();
+ if(policyName==null || policyName.isEmpty()){
+ return XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyName was null or empty.";
+ }
+ if(policyScope== null || policyScope.isEmpty()){
+ try{
+ policyName = pep.getPolicyName().substring(pep.getPolicyName().lastIndexOf(".")+1, pep.getPolicyName().length());
+ policyScope = pep.getPolicyName().substring(0, pep.getPolicyName().lastIndexOf("."));
+ } catch (Exception e){
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "BAD REQUEST: policyScope was null or empty.");
+ return XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyScope was null or empty.";
+ }
+ }
+ PolicyLogger.info("policyName: " + policyName + " policyScope is : " + policyScope);
+ if (pep.getPolicyType() != null && !pep.getPolicyType().isEmpty()) {
+ if (pep.getPdpGroup() != null && !pep.getPdpGroup().isEmpty()) {
+ try {
+ result = pe.pushPolicy(policyScope ,policyName , pep.getPolicyType(), pep.getPdpGroup(), requestUUID, userID, passcode);
+ } catch (PolicyConfigException e) {
+ result = e.getMessage();
+ } catch (Exception e) {
+ result = e.getMessage();
+ }
+ } else {
+ result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyGroup was null or empty.";
+ }
+ } else {
+ result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyType was null or empty.";
+ }
+ return result;
+ }
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationFilter.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationFilter.java
new file mode 100644
index 000000000..c5526d753
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationFilter.java
@@ -0,0 +1,80 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.authorization;
+
+import java.io.IOException;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.annotation.WebFilter;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+@WebFilter("/*")
+public class AuthenticationFilter implements Filter {
+
+ public static final String AUTHENTICATION_HEADER = "Authorization";
+ public static final String ENVIRONMENT_HEADER = "Environment";
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain filter) throws IOException, ServletException {
+ if (request instanceof HttpServletRequest) {
+ HttpServletRequest httpServletRequest = (HttpServletRequest) request;
+ String authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER);
+ String environment = httpServletRequest.getHeader(ENVIRONMENT_HEADER);
+ String path = ((HttpServletRequest) request).getRequestURI();
+
+ // better injected
+ AuthenticationService authenticationService = new AuthenticationService();
+
+ boolean authenticationStatus = authenticationService.authenticate(authCredentials);
+
+ if (authenticationStatus && environment!=null && (environment.equalsIgnoreCase(Config.getEnvironment()))) {
+ filter.doFilter(request, response);
+ } else if(environment==null| path.contains("org.openecomp.policy.pypdp.notifications") || path.contains("swagger") || path.contains("api-docs") || path.contains("configuration") || path.contains("pdps") || path.contains("count") || path.contains("paps")){
+ filter.doFilter(request, response);
+ } else {
+ if (response instanceof HttpServletResponse) {
+ HttpServletResponse httpServletResponse = (HttpServletResponse) response;
+ httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ }
+ if (path.contains("error")){
+ HttpServletResponse httpServletResponse = (HttpServletResponse) response;
+ httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ }
+ }
+
+ @Override
+ public void destroy() {
+ }
+
+ @Override
+ public void init(FilterConfig arg0) throws ServletException {
+ Config.setProperty();
+ }
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationService.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationService.java
new file mode 100644
index 000000000..c7deac910
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationService.java
@@ -0,0 +1,232 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.authorization;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.Properties;
+import java.util.StringTokenizer;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.openecomp.policy.common.logging.eelf.MessageCodes;
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+
+public class AuthenticationService {
+ private String pyPDPID = Config.getPYPDPID();
+ private String pyPDPPass = Config.getPYPDPPass();
+ private static Path clientPath = null;
+ private static HashMap<String, ArrayList<String>> clientMap = null;
+ private static Long oldModified = null;
+ private static Long newModified = null;
+ private static final Log logger = LogFactory.getLog(AuthenticationService.class);
+
+ public boolean authenticate(String authCredentials) {
+
+ if (null == authCredentials)
+ return false;
+ // header value format will be "Basic encodedstring" for Basic authentication.
+ final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", "");
+ String usernameAndPassword = null;
+ try {
+ byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
+ usernameAndPassword = new String(decodedBytes, "UTF-8");
+ } catch (Exception e) {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "");
+ return false;
+ }
+ try {
+ final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
+ final String username = tokenizer.nextToken();
+ final String password = tokenizer.nextToken();
+
+ boolean authenticationStatus = pyPDPID.equals(username) && pyPDPPass.equals(password);
+ return authenticationStatus;
+ } catch (Exception e){
+ logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "");
+ return false;
+ }
+ }
+
+ public static boolean clientAuth(String clientCredentials) {
+ if(clientCredentials == null){
+ return false;
+ }
+ // Decode the encoded Client Credentials.
+ String usernameAndPassword = null;
+ try {
+ byte[] decodedBytes = Base64.getDecoder().decode(clientCredentials);
+ usernameAndPassword = new String(decodedBytes, "UTF-8");
+ } catch (Exception e) {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "");
+ return false;
+ }
+ try {
+ final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
+ final String username = tokenizer.nextToken();
+ final String password = tokenizer.nextToken();
+ return checkClient(username,password);
+ } catch(Exception e){
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "");
+ return false;
+ }
+ }
+
+ public static boolean checkClientScope(String clientCredentials, String scope) {
+ if(clientCredentials == null){
+ return false;
+ }
+ // Decode the encoded Client Credentials.
+ String usernameAndPassword = null;
+ try {
+ byte[] decodedBytes = Base64.getDecoder().decode(clientCredentials);
+ usernameAndPassword = new String(decodedBytes, "UTF-8");
+ } catch (Exception e) {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "");
+ return false;
+ }
+ final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
+ final String username = tokenizer.nextToken();
+ // Read the properties and compare.
+ try{
+ readFile();
+ }catch(Exception e){
+ logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "");
+ return false;
+ }
+ // Check ID, Scope
+ if (clientMap.containsKey(username) && (clientMap.get(username).get(1).equals(scope) || clientMap.get(username).get(1).equals("MASTER"))) {
+ return true;
+ }
+ return false;
+ }
+
+ private static boolean checkClient(String username, String password) {
+ // Read the properties and compare.
+ try{
+ readFile();
+ }catch(Exception e){
+ logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "");
+ return false;
+ }
+ // Check ID, Key
+ if (clientMap.containsKey(username) && clientMap.get(username).get(0).equals(password)) {
+ return true;
+ }
+ return false;
+ }
+
+ private static void readFile() throws Exception {
+ String clientFile = Config.getClientFile();
+ if (clientFile == null) {
+ Config.setProperty();
+ if(clientFile == null){
+ logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Missing CLIENT_FILE property value: " + clientFile);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Missing CLIENT_FILE property value: " + clientFile);
+ throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Missing CLIENT_FILE property value: " + clientFile);
+ }
+ }
+ if (clientPath == null) {
+ clientPath = Paths.get(clientFile);
+ if (Files.notExists(clientPath)) {
+ logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + clientPath.toString());
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "File doesn't exist in the specified Path : " + clientPath.toString());
+ throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ clientPath.toString());
+ }
+ if (clientPath.toString().endsWith(".properties")) {
+ readProps();
+ } else {
+ logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + clientFile);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Not a .properties file " + clientFile);
+ throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file " + clientFile);
+ }
+ }
+ // Check if File is updated recently
+ else {
+ newModified = clientPath.toFile().lastModified();
+ if (newModified != oldModified) {
+ // File has been updated.
+ readProps();
+ }
+ }
+ }
+
+ private static void readProps() throws Exception{
+ InputStream in;
+ Properties clientProp = new Properties();
+ try {
+ in = new FileInputStream(clientPath.toFile());
+ oldModified = clientPath.toFile().lastModified();
+ clientProp.load(in);
+ } catch (IOException e) {
+ logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "");
+ throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Load the Properties file", e);
+
+ }
+ // Read the Properties and Load the PDPs and encoding.
+ clientMap = new HashMap<String, ArrayList<String>>();
+ //
+ for (Object propKey : clientProp.keySet()) {
+ String clientID = (String)propKey;
+ String clientValue = clientProp.getProperty(clientID);
+ if (clientValue != null) {
+ if (clientValue.contains(",")) {
+ ArrayList<String> clientValues = new ArrayList<String>(Arrays.asList(clientValue.split("\\s*,\\s*")));
+ if(clientValues.get(0)!=null || clientValues.get(1)!=null || clientValues.get(0).isEmpty() || clientValues.get(1).isEmpty()){
+ clientMap.put(clientID, clientValues);
+ }
+ }
+ }
+ }
+ if (clientMap == null || clientMap.isEmpty()) {
+ logger.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "No Clients ID , Client Key and Scopes are available. Cannot serve any Clients !!");
+ }
+ }
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/Config.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/Config.java
new file mode 100644
index 000000000..388909ecf
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/Config.java
@@ -0,0 +1,300 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.authorization;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.openecomp.policy.common.logging.eelf.MessageCodes;
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+
+import org.openecomp.policy.common.im.IntegrityMonitor;
+
+
+public class Config {
+ private static final String propertyFilePath = "config.properties";
+ private static Properties prop = new Properties();
+ private static List<String> pdps = null;
+ private static List<String> paps = null;
+ private static List<String> encoding = null;
+ private static List<String> encodingPAP = null;
+ private static String pyPDPPass = null;
+ private static String pyPDPID = null;
+ private static String environment = null;
+ private static final Log logger = LogFactory.getLog(Config.class);
+ private static String clientFile = null;
+ private static boolean test = false;
+
+ private static IntegrityMonitor im;
+ private static String resourceName = null;
+
+ public static String getProperty(String propertyKey) {
+ return prop.getProperty(propertyKey);
+ }
+
+ /*
+ * Set Property by reading the properties File.
+ */
+ public static void setProperty() {
+ Path file = Paths.get(propertyFilePath);
+ if (Files.notExists(file)) {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "File doesn't exist in the specified Path "+ file.toString());
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "File doesn't exist in the specified Path "+ file.toString());
+ } else {
+ InputStream in;
+ prop = new Properties();
+ try {
+ in = new FileInputStream(file.toFile());
+ prop.load(in);
+ } catch (IOException e) {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Cannot Load the Properties file" + e);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "Cannot Load the Properties file");
+ }
+ }
+ // Initializing the values.
+ pdps = new ArrayList<String>();
+ paps = new ArrayList<String>();
+ encoding = new ArrayList<String>();
+ encodingPAP = new ArrayList<String>();
+
+ // Check the Keys for PDP_URLs
+ Collection<Object> unsorted = prop.keySet();
+ List<String> sorted = new ArrayList(unsorted);
+ Collections.sort(sorted);
+ for (String propKey : sorted) {
+ if (propKey.startsWith("PDP_URL")) {
+ String check_val = prop.getProperty(propKey);
+ logger.debug("Property file value for Key : \"" + propKey + "\" Value is : \"" + check_val + "\"");
+ if (check_val == null) {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Properties file doesn't have the PDP_URL parameter");
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Properties file doesn't have the PDP_URL parameter");
+ }
+ if (check_val.contains(";")) {
+ List<String> pdp_default = new ArrayList<String>(Arrays.asList(check_val.split("\\s*;\\s*")));
+ int pdpCount = 0;
+ while (pdpCount < pdp_default.size()) {
+ String pdpVal = pdp_default.get(pdpCount);
+ readPDPParam(pdpVal);
+ pdpCount++;
+ }
+ } else {
+ readPDPParam(check_val);
+ }
+ } else if (propKey.startsWith("PAP_URL")) {
+ String check_val = prop.getProperty(propKey);
+ logger.debug("Property file value for Key : \"" + propKey + "\" Value is : \"" + check_val + "\"");
+ if (check_val == null) {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Properties file doesn't have the PAP_URL parameter");
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Properties file doesn't have the PAP_URL parameter");
+ }
+ if (check_val.contains(";")) {
+ List<String> pap_default = new ArrayList<String>(Arrays.asList(check_val.split("\\s*;\\s*")));
+ int papCount=0;
+ while (papCount < pap_default.size()) {
+ String papVal = pap_default.get(papCount);
+ readPAPParam(papVal);
+ papCount++;
+ }
+ } else {
+ readPAPParam(check_val);
+ }
+ }
+ }
+ if (pdps == null || pdps.isEmpty()) {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Cannot Proceed without PDP_URLs");
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Cannot Proceed without PDP_URLs");
+ }
+
+ if (prop.containsKey("PYPDP_ID")) {
+ String id = prop.getProperty("PYPDP_ID");
+ logger.debug("Property file value key: \"PYPDP_ID\" Value is : \"" + id + "\"");
+ if (id == null) {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Properties file doesn't have PYPDP_ID parameter");
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Properties file doesn't have PYPDP_ID parameter");
+ }
+ Config.pyPDPID = id;
+ } else {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Properties file doesn't have PYPDP_ID parameter");
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Properties file doesn't have PYPDP_ID parameter");
+ }
+ if (prop.containsKey("PYPDP_PASSWORD")) {
+ String pass = prop.getProperty("PYPDP_PASSWORD");
+ logger.debug("Property file value key: \"PYPDP_PASSWORD\" Value is : \"" + pass + "\"");
+ if (pass == null) {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Properties file doesn't have PYPDP_PASSWORD parameter");
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Properties file doesn't have PYPDP_PASSWORD parameter");
+ }
+ Config.pyPDPPass = pass;
+ } else {
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Properties file doesn't have PYPDP_PASSWORD parameter");
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Properties file doesn't have PYPDP_PASSWORD parameter");
+ }
+ environment = prop.getProperty("ENVIRONMENT", "DEVL");
+ logger.info("Property value for Environment " + environment);
+ String value = prop.getProperty("Test");
+ if(value!= null && value.equalsIgnoreCase("true")){
+ test = true;
+ }
+ if(prop.containsKey("CLIENT_FILE")){
+ clientFile = prop.getProperty("CLIENT_FILE");
+ logger.debug("Property file value key: \"CLIENT_FILE\" Value is : \"" + clientFile + "\"");
+ if(clientFile == null){
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"CLIENT_FILE value is missing.");
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "CLIENT_FILE value is missing.");
+ }
+ }else{
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"CLIENT_FILE paramter is missing from the property file.");
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "CLIENT_FILE paramter is missing from the property file.");
+ }
+ logger.info("Trying to set up IntegrityMonitor");
+ try {
+ logger.info("Trying to set up IntegrityMonitor");
+ resourceName = prop.getProperty("RESOURCE_NAME").replaceAll(" ", "");;
+ if(resourceName==null){
+ logger.warn("RESOURCE_NAME is missing setting default value. ");
+ resourceName = "pypdp_pdp01";
+ }
+ im = IntegrityMonitor.getInstance(resourceName, prop);
+ } catch (Exception e) {
+ logger.error("Error starting Integerity Monitor: " + e);
+ }
+ }
+
+ private static void readPDPParam(String pdpVal) {
+ if (pdpVal.contains(",")) {
+ List<String> pdpValues = new ArrayList<String>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
+ if (pdpValues.size() == 3) {
+ // 0 - PDPURL
+ pdps.add(pdpValues.get(0));
+ // 1:2 will be UserID:Password
+ String userID = pdpValues.get(1);
+ String pass = pdpValues.get(2);
+ Base64.Encoder encoder = Base64.getEncoder();
+ encoding.add(encoder.encodeToString((userID + ":" + pass)
+ .getBytes(StandardCharsets.UTF_8)));
+ } else {
+ logger.error(XACMLErrorConstants.ERROR_PERMISSIONS+"No enough Credentials to send Request. "+ pdpValues);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No enough Credentials to send Request. "+ pdpValues);
+ }
+ } else {
+ logger.error(XACMLErrorConstants.ERROR_PERMISSIONS+"No enough Credentials to send Request.");
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No enough Credentials to send Request.");
+ }
+ }
+
+ private static void readPAPParam(String papVal) {
+ if (papVal.contains(",")) {
+ List<String> papValues = new ArrayList<String>(Arrays.asList(papVal.split("\\s*,\\s*")));
+ if (papValues.size() == 3) {
+ // 0 - PAPURL
+ paps.add(papValues.get(0));
+ // 1:2 will be UserID:Password
+ String userID = papValues.get(1);
+ String pass = papValues.get(2);
+ Base64.Encoder encoder = Base64.getEncoder();
+ encodingPAP.add(encoder.encodeToString((userID + ":" + pass)
+ .getBytes(StandardCharsets.UTF_8)));
+ } else {
+ logger.error(XACMLErrorConstants.ERROR_PERMISSIONS+"Not enough Credentials to send Request. "+ papValues);
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, "Not enough Credentials to send Request. "+ papValues);
+ }
+ } else {
+ logger.error(XACMLErrorConstants.ERROR_PERMISSIONS+"Not enough Credentials to send Request.");
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, "Not enough Credentials to send Request.");
+ }
+ }
+
+ public static List<String> getPDPs() {
+ setProperty();
+ return Config.pdps;
+ }
+
+ public static List<String> getPAPs() {
+ setProperty();
+ return Config.paps;
+ }
+
+ public static List<String> getEncoding() {
+ return Config.encoding;
+ }
+
+ public static List<String> getEncodingPAP() {
+ return Config.encodingPAP;
+ }
+
+ public static String getPYPDPID() {
+ return Config.pyPDPID;
+ }
+
+ public static String getPYPDPPass() {
+ return Config.pyPDPPass;
+ }
+
+ public static String getEnvironment(){
+ return Config.environment;
+ }
+
+ public static IntegrityMonitor getIntegrityMonitor(){
+ if(im==null){
+ setProperty();
+ }
+ return im;
+ }
+
+ public static String getClientFile() {
+ return Config.clientFile;
+ }
+
+ public static Boolean isTest() {
+ return Config.test;
+ }
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/Application.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/Application.java
new file mode 100644
index 000000000..a98e1109d
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/Application.java
@@ -0,0 +1,80 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.controller;
+
+import javax.servlet.Filter;
+
+import org.openecomp.policy.pypdp.authorization.AuthenticationFilter;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.builder.SpringApplicationBuilder;
+import org.springframework.boot.context.web.SpringBootServletInitializer;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+
+import springfox.documentation.builders.ApiInfoBuilder;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.service.ApiInfo;
+import springfox.documentation.service.Contact;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spring.web.plugins.Docket;
+import springfox.documentation.swagger2.annotations.EnableSwagger2;
+
+@SpringBootApplication
+@EnableSwagger2
+@ComponentScan(basePackageClasses = {PolicyEngineServices.class})
+public class Application extends SpringBootServletInitializer {
+
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args);
+ }
+
+ @Override
+ protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
+ return application.sources(applicationClass);
+ }
+
+ private static Class<Application> applicationClass = Application.class;
+
+ @Bean
+ public Filter authenticationFilter(){
+ return new AuthenticationFilter();
+ }
+
+ private ApiInfo apiInfo(){
+ return new ApiInfoBuilder()
+ .title("Policy Engine REST API")
+ .description("This API helps applications across Domain 2.0 Platform to make queries against Policy Engine")
+ .version("2.0")
+ .build();
+ }
+
+ @Bean
+ public Docket policyAPI(){
+ return new Docket(DocumentationType.SWAGGER_2)
+ .apiInfo(apiInfo())
+ .select()
+ .apis(RequestHandlerSelectors.basePackage("org.openecomp.policy.pypdp.controller"))
+ .build()
+ .pathMapping("/")
+ ;
+ }
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/PolicyEngineServices.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/PolicyEngineServices.java
new file mode 100644
index 000000000..12a5f25f5
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/PolicyEngineServices.java
@@ -0,0 +1,556 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.controller;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+
+import java.util.Base64;
+import java.util.Collection;
+import java.util.List;
+import java.util.StringTokenizer;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.openecomp.policy.api.ConfigRequestParameters;
+import org.openecomp.policy.api.DeletePolicyParameters;
+import org.openecomp.policy.api.EventRequestParameters;
+import org.openecomp.policy.api.NotificationScheme;
+import org.openecomp.policy.api.PolicyParameters;
+import org.openecomp.policy.api.PolicyResponse;
+import org.openecomp.policy.pypdp.ConfigFirewallPolicyRequest;
+import org.openecomp.policy.pypdp.ConfigRequest;
+import org.openecomp.policy.pypdp.DeletePolicyRequest;
+import org.openecomp.policy.pypdp.EventRequest;
+import org.openecomp.policy.pypdp.ListConfigRequest;
+import org.openecomp.policy.pypdp.PolicyCreateUpdateRequest;
+import org.openecomp.policy.pypdp.PushPolicyRequest;
+import org.openecomp.policy.pypdp.authorization.AuthenticationService;
+import org.openecomp.policy.pypdp.authorization.Config;
+import org.openecomp.policy.pypdp.jmx.PyPdpMonitor;
+import org.openecomp.policy.pypdp.model_pojo.PepConfigFirewallPolicyRequest;
+import org.openecomp.policy.pypdp.model_pojo.PepConfigPolicyNameRequest;
+import org.openecomp.policy.pypdp.model_pojo.PepConfigPolicyRequest;
+import org.openecomp.policy.pypdp.model_pojo.PepPushPolicyRequest;
+import org.openecomp.policy.pypdp.model_pojo.PyPolicyConfig;
+import org.openecomp.policy.pypdp.notifications.NotificationController;
+import org.openecomp.policy.std.StdPolicyEngine;
+import org.openecomp.policy.utils.PolicyUtils;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import springfox.documentation.annotations.ApiIgnore;
+
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+import org.openecomp.policy.common.im.AdministrativeStateException;
+import org.openecomp.policy.common.im.StandbyStatusException;
+
+@RestController
+@Api(value="Policy Engine Services")
+public class PolicyEngineServices {
+ private final NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS;
+ private final NotificationController handler = new NotificationController();
+ private final AtomicLong configCounter = PyPdpMonitor.singleton.getAtomicConfigCounter();
+ private final AtomicLong eventCounter = PyPdpMonitor.singleton.getAtomicEventCounter();
+ private final AtomicLong configPolicyNameCounter = PyPdpMonitor.singleton.getAtomicConfigPolicyNameCounter();
+ private final StdPolicyEngine policyEngine = new StdPolicyEngine(Config.getPDPs(), Config.getPAPs(), Config.getEncodingPAP(), Config.getEncoding(), scheme, handler, Config.getEnvironment(), Config.getClientFile(), Config.isTest());
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value= "Gets the configuration from the PolicyDecisionPoint(PDP)")
+ @RequestMapping(value = "/getConfig", method = RequestMethod.POST)
+ public @ResponseBody ResponseEntity<Collection<PyPolicyConfig>> createConfigRequest(@RequestBody ConfigRequestParameters pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding, @RequestHeader(value="X-ECOMP-RequestID", required=false)String requestID) {
+ Collection<PyPolicyConfig> policyConfig = null;
+ String[] userNamePass = null;
+ try {
+ userNamePass = decodeEncoding(clientEncoding, "CONFIG");
+ } catch (Exception e1) {
+ return new ResponseEntity<Collection<PyPolicyConfig>>(policyConfig, HttpStatus.UNAUTHORIZED);
+ }
+ ConfigRequest configRequest = new ConfigRequest(policyEngine);
+ try{
+ Config.getIntegrityMonitor().startTransaction();
+ } catch (AdministrativeStateException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ } catch (Exception e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ }
+ policyConfig = configRequest.run(pep, requestID, userNamePass[0], userNamePass[1]);
+ configCounter.incrementAndGet();
+ Config.getIntegrityMonitor().endTransaction();
+ for(PyPolicyConfig pythonConfig: policyConfig){
+ if(pythonConfig.getPolicyConfigMessage()!=null && pythonConfig.getPolicyConfigMessage().contains("PE300")){
+ return new ResponseEntity<Collection<PyPolicyConfig>>(policyConfig, HttpStatus.BAD_REQUEST);
+ }
+ }
+ return new ResponseEntity<Collection<PyPolicyConfig>>(policyConfig, HttpStatus.OK);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value= "Gets the configuration from the PDP")
+ @RequestMapping(value = "/listConfig", method = RequestMethod.POST)
+ public @ResponseBody ResponseEntity<Collection<String>> createListConfigRequest(@RequestBody ConfigRequestParameters pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding, @RequestHeader(value="X-ECOMP-RequestID", required=false)String requestID) {
+ Collection<String> policyList = null;
+ String[] userNamePass = null;
+ try {
+ userNamePass = decodeEncoding(clientEncoding, "CONFIG");
+ } catch (Exception e1) {
+ return new ResponseEntity<Collection<String>>(policyList, HttpStatus.UNAUTHORIZED);
+ }
+ ListConfigRequest listConfigRequest = new ListConfigRequest(policyEngine);
+ try{
+ Config.getIntegrityMonitor().startTransaction();
+ } catch (AdministrativeStateException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ } catch (StandbyStatusException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ }
+ policyList = listConfigRequest.run(pep, requestID, userNamePass[0], userNamePass[1]);
+
+ configCounter.incrementAndGet();
+ Config.getIntegrityMonitor().endTransaction();
+
+ for(String response : policyList){
+ if(response!=null && response.contains("PE300")){
+ return new ResponseEntity<Collection<String>>(policyList, HttpStatus.BAD_REQUEST);
+ }
+ }
+ return new ResponseEntity<Collection<String>>(policyList, HttpStatus.OK);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value= "Sends the Events specified to the Policy Engine")
+ @RequestMapping(value = "/sendEvent", method = RequestMethod.POST)
+ public @ResponseBody ResponseEntity<Collection<PolicyResponse>> createEventParameterRequest(@RequestBody EventRequestParameters pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding, @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) {
+ Collection<PolicyResponse> policyResponse = null;
+ String[] userNamePass = null;
+ try {
+ userNamePass = decodeEncoding(clientEncoding, "ACTION");
+ } catch (Exception e1) {
+ return new ResponseEntity<Collection<PolicyResponse>>(policyResponse, HttpStatus.UNAUTHORIZED);
+ }
+ EventRequest eventRequest = new EventRequest(policyEngine);
+ try{
+ Config.getIntegrityMonitor().startTransaction();
+ } catch (AdministrativeStateException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ } catch (Exception e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ }
+ policyResponse = eventRequest.run(pep, requestID, userNamePass[0], userNamePass[1]);
+ eventCounter.incrementAndGet();
+ Config.getIntegrityMonitor().endTransaction();
+ for(PolicyResponse response: policyResponse ){
+ if(response.getPolicyResponseMessage()!=null && response.getPolicyResponseMessage().contains("PE300")){
+ return new ResponseEntity<Collection<PolicyResponse>>(policyResponse,HttpStatus.BAD_REQUEST);
+ }
+ }
+ return new ResponseEntity<Collection<PolicyResponse>>(policyResponse,HttpStatus.OK);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value= "Gets the configuration from the PolicyDecisionPoint(PDP)")
+ @RequestMapping(value = "/getConfigByPolicyName", method = RequestMethod.POST)
+ @Deprecated
+ public @ResponseBody ResponseEntity<Collection<PyPolicyConfig>> createConfigRequest(@RequestBody PepConfigPolicyNameRequest pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding, @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) {
+ Collection<PyPolicyConfig> policyConfig = null;
+ String[] userNamePass = null;
+ try {
+ userNamePass = decodeEncoding(clientEncoding, "CONFIG");
+ } catch (Exception e1) {
+ return new ResponseEntity<Collection<PyPolicyConfig>>(policyConfig, HttpStatus.UNAUTHORIZED);
+ }
+ ConfigRequest configRequest = new ConfigRequest(policyEngine);
+ try{
+ Config.getIntegrityMonitor().startTransaction();
+ } catch (AdministrativeStateException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ } catch (Exception e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ }
+ policyConfig = configRequest.run(pep, requestID, userNamePass[0], userNamePass[1]);
+ configPolicyNameCounter.incrementAndGet();
+ Config.getIntegrityMonitor().endTransaction();
+ return new ResponseEntity<Collection<PyPolicyConfig>>(policyConfig, HttpStatus.OK);
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value="Pushes the specified policy to the PDP Group.")
+ @RequestMapping(value = "/pushPolicy", method = RequestMethod.PUT)
+ public @ResponseBody ResponseEntity<String> pushPolicyRequest(@RequestBody PepPushPolicyRequest pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding,
+ @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) {
+ String response = null;
+ String[] userNamePass = null;
+ try {
+ userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY");
+ } catch (Exception e1) {
+ return new ResponseEntity<String>(response, HttpStatus.UNAUTHORIZED);
+ }
+ PushPolicyRequest pushPolicy = new PushPolicyRequest(policyEngine);
+ try{
+ Config.getIntegrityMonitor().startTransaction();
+ } catch (AdministrativeStateException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ } catch (Exception e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ }
+ response = pushPolicy.run(pep, requestID, userNamePass[0], userNamePass[1]);
+
+ Config.getIntegrityMonitor().endTransaction();
+ if (response.contains("BAD REQUEST")||response.contains("PE300")) {
+ return new ResponseEntity<String>(response, HttpStatus.BAD_REQUEST);
+ } else {
+ return new ResponseEntity<String>(response, HttpStatus.OK);
+ }
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value="Deletes the specified policy from the PDP Group or PAP.")
+ @RequestMapping(value = "/deletePolicy", method = RequestMethod.DELETE)
+ public @ResponseBody ResponseEntity<String> deletePolicyRequest(@RequestBody DeletePolicyParameters pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding,
+ @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) {
+ String response = null;
+ String[] userNamePass = null;
+ try {
+ userNamePass = decodeEncoding(clientEncoding, "DELETEPOLICY");
+ } catch (Exception e1) {
+ return new ResponseEntity<String>(response, HttpStatus.UNAUTHORIZED);
+ }
+ DeletePolicyRequest deletePolicy = new DeletePolicyRequest(policyEngine);
+ try{
+ Config.getIntegrityMonitor().startTransaction();
+ } catch (AdministrativeStateException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ } catch (Exception e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ }
+ response = deletePolicy.run(pep, requestID, userNamePass[0], userNamePass[1]);
+
+ Config.getIntegrityMonitor().endTransaction();
+ if (response.contains("BAD REQUEST")||response.contains("PE300")||response.contains("not exist")||response.contains("Invalid policyName")) {
+ return new ResponseEntity<String>(response, HttpStatus.BAD_REQUEST);
+ } else if (response.contains("locked down")){
+ return new ResponseEntity<String>(response, HttpStatus.ACCEPTED);
+ } else if (response.contains("not Authorized")) {
+ return new ResponseEntity<String>(response, HttpStatus.FORBIDDEN);
+ } else if (response.contains("groupId")) {
+ return new ResponseEntity<String>(response, HttpStatus.NOT_FOUND);
+ } else if (response.contains("JPAUtils")||response.contains("database")||response.contains("policy file")||
+ response.contains("unknown")||response.contains("configuration")) {
+ return new ResponseEntity<String>(response, HttpStatus.INTERNAL_SERVER_ERROR);
+ } else {
+ return new ResponseEntity<String>(response, HttpStatus.OK);
+ }
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value= "Creates a Policy based on given Policy Parameters.")
+ @RequestMapping(value = "/createPolicy", method = RequestMethod.PUT)
+ public @ResponseBody ResponseEntity<String> createRequest(@RequestBody PolicyParameters pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding,
+ @RequestHeader(value="X-ECOMP-RequestID", required=false)String requestID) {
+ String response = null;
+ String[] userNamePass = null;
+ try {
+ userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY");
+ } catch (Exception e1) {
+ return new ResponseEntity<String>(response, HttpStatus.UNAUTHORIZED);
+ }
+ PolicyCreateUpdateRequest policyCreateUpdateRequest = new PolicyCreateUpdateRequest(policyEngine);
+ try{
+ Config.getIntegrityMonitor().startTransaction();
+ } catch (AdministrativeStateException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ } catch (Exception e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ }
+ response = policyCreateUpdateRequest.run(pep, requestID, "create", userNamePass[0], userNamePass[1]);
+
+ Config.getIntegrityMonitor().endTransaction();
+ if(response== null || response.contains("BAD REQUEST")||response.contains("PE300")){
+ return new ResponseEntity<String>(response, HttpStatus.BAD_REQUEST);
+ }
+ else if (response.contains("Policy Exist Error")) {
+ return new ResponseEntity<String>(response, HttpStatus.CONFLICT);
+ } else if (response.contains("PE200")){
+ return new ResponseEntity<String>(response, HttpStatus.INTERNAL_SERVER_ERROR);
+ } else {
+ return new ResponseEntity<String>(response, HttpStatus.OK);
+ }
+
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value= "Updates a Policy based on given Policy Parameters.")
+ @RequestMapping(value = "/updatePolicy", method = RequestMethod.PUT)
+ public @ResponseBody ResponseEntity<String> updateRequest(@RequestBody PolicyParameters pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding,
+ @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) {
+ String response = null;
+ String[] userNamePass = null;
+ try {
+ userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY");
+ } catch (Exception e1) {
+ return new ResponseEntity<String>(response, HttpStatus.UNAUTHORIZED);
+ }
+ PolicyCreateUpdateRequest policyCreateUpdateRequest = new PolicyCreateUpdateRequest(policyEngine);
+ try{
+ Config.getIntegrityMonitor().startTransaction();
+ } catch (AdministrativeStateException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ } catch (Exception e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ }
+ response = policyCreateUpdateRequest.run(pep, requestID, "update", userNamePass[0], userNamePass[1]);
+
+ Config.getIntegrityMonitor().endTransaction();
+ if (response==null|| response.contains("BAD REQUEST")||response.contains("PE300")){
+ return new ResponseEntity<String>(response, HttpStatus.BAD_REQUEST);
+ } else if (response.contains("PE200")){
+ return new ResponseEntity<String>(response, HttpStatus.INTERNAL_SERVER_ERROR);
+ } else {
+ return new ResponseEntity<String>(response, HttpStatus.OK);
+ }
+
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value= "Creates a Config Policy based on given Policy Parameters.")
+ @RequestMapping(value = "/createConfig", method = RequestMethod.PUT)
+ @Deprecated
+ public @ResponseBody ResponseEntity<String> createConfigRequest(@RequestBody PepConfigPolicyRequest pep, @RequestHeader(value="ClientAuth", required=true)String clientEncoding,
+ @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) {
+ String response = null;
+ String[] userNamePass = null;
+ try {
+ userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY");
+ } catch (Exception e1) {
+ return new ResponseEntity<String>(response, HttpStatus.UNAUTHORIZED);
+ }
+ PolicyCreateUpdateRequest policyCreateUpdateRequest = new PolicyCreateUpdateRequest(policyEngine);
+ try{
+ Config.getIntegrityMonitor().startTransaction();
+ } catch (AdministrativeStateException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ } catch (Exception e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ }
+ response = policyCreateUpdateRequest.run(pep, requestID, "create", userNamePass[0], userNamePass[1]);
+
+ Config.getIntegrityMonitor().endTransaction();
+ if (response!=null && !response.contains("BAD REQUEST")) {
+ return new ResponseEntity<String>(response, HttpStatus.OK);
+ } else {
+ return new ResponseEntity<String>(response, HttpStatus.BAD_REQUEST);
+ }
+
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value= "Updates a Config Policy based on given Policy Parameters.")
+ @RequestMapping(value = "/updateConfig", method = RequestMethod.PUT)
+ @Deprecated
+ public @ResponseBody ResponseEntity<String> updateConfigRequest(@RequestBody PepConfigPolicyRequest pep, @RequestHeader(value="ClientAuth", required=true)String clientEncoding,
+ @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) {
+ String response = null;
+ String[] userNamePass = null;
+ try {
+ userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY");
+ } catch (Exception e1) {
+ return new ResponseEntity<String>(response, HttpStatus.UNAUTHORIZED);
+ }
+ PolicyCreateUpdateRequest policyCreateUpdateRequest = new PolicyCreateUpdateRequest(policyEngine);
+ try{
+ Config.getIntegrityMonitor().startTransaction();
+ } catch (AdministrativeStateException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ } catch (Exception e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ }
+ response = policyCreateUpdateRequest.run(pep, requestID, "update", userNamePass[0], userNamePass[1]);
+
+ Config.getIntegrityMonitor().endTransaction();
+ if (response!=null && !response.contains("BAD REQUEST")) {
+ return new ResponseEntity<String>(response, HttpStatus.OK);
+ } else {
+ return new ResponseEntity<String>(response, HttpStatus.BAD_REQUEST);
+ }
+
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value = "Creates a Config Firewall Policy")
+ @RequestMapping(value = "/createFirewallConfig", method = RequestMethod.PUT)
+ @Deprecated
+ public @ResponseBody ResponseEntity<String> createFirewallConfigRequest(@RequestBody PepConfigFirewallPolicyRequest pep, @RequestHeader(value="ClientAuth", required=true)String clientEncoding,
+ @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) {
+ String response = null;
+ String[] userNamePass = null;
+ try {
+ userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY");
+ } catch (Exception e1) {
+ return new ResponseEntity<String>(response, HttpStatus.UNAUTHORIZED);
+ }
+ ConfigFirewallPolicyRequest firewallPolicyRequest = new ConfigFirewallPolicyRequest(policyEngine);
+ try{
+ Config.getIntegrityMonitor().startTransaction();
+ } catch (AdministrativeStateException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ } catch (Exception e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ }
+ response = firewallPolicyRequest.run(pep, requestID, "create", userNamePass[0], userNamePass[1]);
+
+ Config.getIntegrityMonitor().endTransaction();
+ if (response!=null && !response.contains("BAD REQUEST")) {
+ return new ResponseEntity<String>(response, HttpStatus.OK);
+ } else {
+ return new ResponseEntity<String>(response, HttpStatus.BAD_REQUEST);
+ }
+
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"),
+ @ApiImplicitParam(name ="Environment", required = true, paramType = "Header")
+ })
+ @ApiOperation(value = "Updates a Config Firewall Policy")
+ @RequestMapping(value = "/updateFirewallConfig", method = RequestMethod.PUT)
+ @Deprecated
+ public @ResponseBody ResponseEntity<String> updateFirewallConfigRequest(@RequestBody PepConfigFirewallPolicyRequest pep, @RequestHeader(value="ClientAuth", required=true)String clientEncoding,
+ @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) {
+ String response = null;
+ String[] userNamePass = null;
+ try {
+ userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY");
+ } catch (Exception e1) {
+ return new ResponseEntity<String>(response, HttpStatus.UNAUTHORIZED);
+ }
+ ConfigFirewallPolicyRequest firewallPolicyRequest = new ConfigFirewallPolicyRequest(policyEngine);
+ try{
+ Config.getIntegrityMonitor().startTransaction();
+ } catch (AdministrativeStateException e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ } catch (Exception e) {
+ PolicyLogger.error("Error while starting Transaction " + e);
+ }
+ response = firewallPolicyRequest.run(pep, requestID, "update", userNamePass[0], userNamePass[1]);
+
+ Config.getIntegrityMonitor().endTransaction();
+ if (response!=null && !response.contains("BAD REQUEST")) {
+ return new ResponseEntity<String>(response, HttpStatus.OK);
+ } else {
+ return new ResponseEntity<String>(response, HttpStatus.BAD_REQUEST);
+ }
+
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header")
+ })
+ @ApiOperation(value= "Gets the API Services usage Information")
+ @ApiIgnore
+ @RequestMapping(value = "/count", method = RequestMethod.GET)
+ public String getCount() {
+ return "Total Config Calls : " + configCounter + "\n"
+ +"Total Config calls made using Policy File Name: " + configPolicyNameCounter + "\n"
+ + "Total Event Calls : " + eventCounter;
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header")
+ })
+ @ApiOperation(value = "Gets the PDPs that are listed to provide service.")
+ @RequestMapping(value = "/pdps", method = RequestMethod.GET)
+ public List<String> listPDPs() {
+ return Config.getPDPs();
+ }
+
+ @ApiImplicitParams({
+ @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header")
+ })
+ @ApiOperation(value = "Gets the PAPs that are listed to provide service.")
+ @RequestMapping(value = "/paps", method = RequestMethod.GET)
+ public List<String> listPAPs() {
+ return Config.getPAPs();
+ }
+
+ /*
+ * Internal Decoding System. to support old and new Calls.
+ */
+ private String[] decodeEncoding(String clientEncoding, String scope) throws Exception{
+ String[] userNamePass = PolicyUtils.decodeBasicEncoding(clientEncoding);
+ if(userNamePass==null){
+ if(AuthenticationService.clientAuth(clientEncoding)){
+ if(AuthenticationService.checkClientScope(clientEncoding, scope)){
+ String usernameAndPassword = null;
+ byte[] decodedBytes = Base64.getDecoder().decode(clientEncoding);
+ usernameAndPassword = new String(decodedBytes, "UTF-8");
+ StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
+ String username = tokenizer.nextToken();
+ String password = tokenizer.nextToken();
+ userNamePass= new String[]{username, password};
+ }
+ }
+ }
+ if(userNamePass==null){
+ throw new Exception("Client is Not authrorized to make this call. Please contact PyPDP Admin.");
+ }
+ return userNamePass;
+ }
+} \ No newline at end of file
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMBeanListener.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMBeanListener.java
new file mode 100644
index 000000000..cd1c95d53
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMBeanListener.java
@@ -0,0 +1,75 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.jmx;
+
+import java.lang.management.ManagementFactory;
+
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+import javax.servlet.annotation.WebListener;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+
+@WebListener
+public class PyPdpMBeanListener implements ServletContextListener {
+ private static final String JMX_OBJECT_NAME = "PyPdp:type=PyPdpMonitor";
+// private static final Log logger = LogFactory.getLog(PyPdpMBeanListener.class);
+ private static final Logger logger = FlexLogger.getLogger(PyPdpMBeanListener.class);
+
+ private ObjectName objectName;
+
+ @Override
+ public void contextInitialized(ServletContextEvent contextEvent) {
+ if (logger.isInfoEnabled())
+ logger.info("Registering.");
+
+ final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
+ try {
+ objectName = new ObjectName(JMX_OBJECT_NAME);
+ server.registerMBean(PyPdpMonitor.singleton, objectName);
+ logger.info("MBean registered: " + objectName);
+ } catch (Exception e) {
+ logger.warn(e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public void contextDestroyed(ServletContextEvent arg0) {
+ if (logger.isInfoEnabled())
+ logger.info("Unregistering");
+ final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
+ try {
+ objectName = new ObjectName(JMX_OBJECT_NAME);
+ server.unregisterMBean(objectName);
+ if (logger.isInfoEnabled())
+ logger.info("MBean unregistered: " + objectName);
+ } catch (Exception e) {
+ logger.warn(e.getMessage(), e);
+ }
+ }
+
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitor.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitor.java
new file mode 100644
index 000000000..849d8ae3f
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitor.java
@@ -0,0 +1,90 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.jmx;
+
+import java.util.concurrent.atomic.AtomicLong;
+
+public class PyPdpMonitor implements PyPdpMonitorMBean {
+
+ public static PyPdpMonitor singleton = new PyPdpMonitor();
+
+ private final AtomicLong configCounter;
+ private final AtomicLong eventCounter;
+ private final AtomicLong configPolicyNameCounter;
+
+ private PyPdpMonitor() {
+ this.configCounter = new AtomicLong();
+ this.eventCounter = new AtomicLong();
+ this.configPolicyNameCounter = new AtomicLong();
+ }
+
+ /**
+ * @return the configCounter
+ */
+ public AtomicLong getAtomicConfigCounter() {
+ return configCounter;
+ }
+
+ /**
+ * @return the eventCounter
+ */
+ public AtomicLong getAtomicEventCounter() {
+ return eventCounter;
+ }
+
+ /**
+ * @return the configPolicyNameCounter
+ */
+ public AtomicLong getAtomicConfigPolicyNameCounter() {
+ return configPolicyNameCounter;
+ }
+ /**
+ * @return the configCounter
+ */
+ @Override
+ public long getConfigCounter() {
+ return configCounter.longValue();
+ }
+
+ /**
+ * @return the eventCounter
+ */
+ @Override
+ public long getEventCounter() {
+ return eventCounter.longValue();
+ }
+
+ /**
+ * @return the configPolicyNameCounter
+ */
+ @Override
+ public long getConfigPolicyNameCounter() {
+ return configPolicyNameCounter.longValue();
+ }
+
+ @Override
+ public synchronized void resetCounters() {
+ this.configCounter.set(0);
+ this.eventCounter.set(0);
+ this.configPolicyNameCounter.set(0);
+ }
+
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitorMBean.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitorMBean.java
new file mode 100644
index 000000000..b111bb6f1
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitorMBean.java
@@ -0,0 +1,28 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.jmx;
+
+public interface PyPdpMonitorMBean {
+ public long getConfigCounter();
+ public long getEventCounter();
+ public long getConfigPolicyNameCounter();
+ public void resetCounters();
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigFirewallPolicyRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigFirewallPolicyRequest.java
new file mode 100644
index 000000000..1e76854c5
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigFirewallPolicyRequest.java
@@ -0,0 +1,82 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.model_pojo;
+
+import java.io.Serializable;
+import java.util.Map;
+
+import javax.json.JsonObject;
+
+public class PepConfigFirewallPolicyRequest implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String policyName = null;
+ private String policyScope = null;
+ private String firewallJson = null;
+ private String riskType = "defualt";
+ private String riskLevel = "5";
+ private String guard = "false";
+ private String ttlDate = null;
+
+ public String getPolicyName() {
+ return policyName;
+ }
+ public String getPolicyScope() {
+ return policyScope;
+ }
+ public String getFirewallJson() {
+ return firewallJson;
+ }
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+ public void setPolicyScope(String policyScope) {
+ this.policyScope = policyScope;
+ }
+ public void setFirewallJson(String firewallJson) {
+ this.firewallJson = firewallJson;
+ }
+ public String getRiskType() {
+ return riskType;
+ }
+ public void setRiskType(String riskType) {
+ this.riskType = riskType;
+ }
+ public String getRiskLevel() {
+ return riskLevel;
+ }
+ public void setRiskLevel(String riskLevel) {
+ this.riskLevel = riskLevel;
+ }
+ public String getGuard() {
+ return guard;
+ }
+ public void setGuard(String guard) {
+ this.guard = guard;
+ }
+ public String getTtlDate() {
+ return ttlDate;
+ }
+ public void setTtlDate(String ttlDate) {
+ this.ttlDate = ttlDate;
+ }
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyNameRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyNameRequest.java
new file mode 100644
index 000000000..14979b8a1
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyNameRequest.java
@@ -0,0 +1,39 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.model_pojo;
+
+import java.io.Serializable;
+
+public class PepConfigPolicyNameRequest implements Serializable{
+
+ private static final long serialVersionUID = -5045734290192376081L;
+
+ private String policyName = null;
+
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+
+ public String getPolicyName() {
+ return policyName;
+ }
+
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyRequest.java
new file mode 100644
index 000000000..9776e5091
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyRequest.java
@@ -0,0 +1,187 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.model_pojo;
+
+import java.io.Serializable;
+import java.util.Map;
+
+public class PepConfigPolicyRequest implements Serializable {
+
+ private static final long serialVersionUID = 7946941587312347282L;
+
+ private String policyScope = null;
+ private String policyName = null;
+ private String policyDescription = null;
+ private String ecompName = null;
+ private String configName = null;
+ private Map<String,String> configAttributes = null;
+ private String configType = null;
+ private String body = null;
+ private String riskType = "defualt";
+ private String riskLevel = "5";
+ private String guard = "false";
+ private String ttlDate = null;
+
+ /**
+ * @return the policyScope
+ */
+ public String getPolicyScope() {
+ return policyScope;
+ }
+ /**
+ * @return the policyName
+ */
+ public String getPolicyName() {
+ return policyName;
+ }
+ /**
+ * @return the policyDescription
+ */
+ public String getPolicyDescription() {
+ return policyDescription;
+ }
+ /**
+ * @return the ecompName
+ */
+ public String getEcompName() {
+ return ecompName;
+ }
+ /**
+ * @return the configName
+ */
+ public String getConfigName() {
+ return configName;
+ }
+ /**
+ * @return the configAttributes
+ */
+ public Map<String, String> getConfigAttributes() {
+ return configAttributes;
+ }
+ /**
+ * @return the configType
+ */
+ public String getConfigType() {
+ return configType;
+ }
+ /**
+ * @return the body
+ */
+ public String getBody() {
+ return body;
+ }
+ /**
+ * @param policyScope the policyScope to set
+ */
+ public void setPolicyScope(String policyScope) {
+ this.policyScope = policyScope;
+ }
+ /**
+ * @param policyName the policyName to set
+ */
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+ /**
+ * @param policyDescription the policyDescription to set
+ */
+ public void setPolicyDescription(String policyDescription) {
+ this.policyDescription = policyDescription;
+ }
+ /**
+ * @param ecompName the ecompName to set
+ */
+ public void setEcompName(String ecompName) {
+ this.ecompName = ecompName;
+ }
+ /**
+ * @param configName the configName to set
+ */
+ public void setConfigName(String configName) {
+ this.configName = configName;
+ }
+ /**
+ * @param configAttributes the configAttributes to set
+ */
+ public void setConfigAttributes(Map<String, String> configAttributes) {
+ this.configAttributes = configAttributes;
+ }
+ /**
+ * @param configType the configType to set
+ */
+ public void setConfigType(String configType) {
+ this.configType = configType;
+ }
+ /**
+ * @param body the body to set
+ */
+ public void setBody(String body) {
+ this.body = body;
+ }
+ /**
+ * @return the guard
+ */
+ public String getGuard() {
+ return guard;
+ }
+ /**
+ * @param guard the guard to set
+ */
+ public void setGuard(String guard) {
+ this.guard = guard;
+ }
+ /**
+ * @return the riskLevel
+ */
+ public String getRiskLevel() {
+ return riskLevel;
+ }
+ /**
+ * @param riskLevel the riskLevel to set
+ */
+ public void setRiskLevel(String riskLevel) {
+ this.riskLevel = riskLevel;
+ }
+ /**
+ * @return the ttlDate
+ */
+ public String getTtlDate() {
+ return ttlDate;
+ }
+ /**
+ * @param ttlDate the ttlDate to set
+ */
+ public void setTtlDate(String ttlDate) {
+ this.ttlDate = ttlDate;
+ }
+ /**
+ * @return the riskType
+ */
+ public String getRiskType() {
+ return riskType;
+ }
+ /**
+ * @param riskType the riskType to set
+ */
+ public void setRiskType(String riskType) {
+ this.riskType = riskType;
+ }
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepPushPolicyRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepPushPolicyRequest.java
new file mode 100644
index 000000000..0c3c8efd9
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepPushPolicyRequest.java
@@ -0,0 +1,66 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.model_pojo;
+
+import java.io.Serializable;
+
+public class PepPushPolicyRequest implements Serializable {
+
+ private static final long serialVersionUID = 2638006651985508836L;
+
+ private String policyScope = null;
+ private String policyName = null;
+ private String policyType = null;
+ private String pdpGroup = null;
+
+ public String getPolicyScope() {
+ return policyScope;
+ }
+
+ public String getPolicyName() {
+ return policyName;
+ }
+
+ public String getPolicyType() {
+ return policyType;
+ }
+
+ public String getPdpGroup() {
+ return pdpGroup;
+ }
+
+ public void setPolicyScope(String policyScope) {
+ this.policyScope = policyScope;
+ }
+
+ public void setPolicyType(String policyType) {
+ this.policyType = policyType;
+ }
+
+ public void setPdpGroup(String pdpGroup) {
+ this.pdpGroup = pdpGroup;
+ }
+
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PyPolicyConfig.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PyPolicyConfig.java
new file mode 100644
index 000000000..22882764c
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PyPolicyConfig.java
@@ -0,0 +1,95 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.model_pojo;
+
+import io.swagger.annotations.ApiModel;
+
+import java.util.Map;
+
+import org.openecomp.policy.api.PolicyConfigStatus;
+import org.openecomp.policy.api.PolicyType;
+
+@ApiModel
+public class PyPolicyConfig{
+ private String policyConfigMessage;
+ private PolicyConfigStatus policyConfigStatus;
+ private PolicyType type;
+ private String config;
+ private String policyName;
+ private String policyVersion;
+ private Map<String, String> matchingConditions;
+ private Map<String, String> responseAttributes;
+ private Map<String, String> property;
+ public String getConfig() {
+ return config;
+ }
+ public void setConfig(String config) {
+ this.config = config;
+ }
+ public PolicyType getType() {
+ return type;
+ }
+ public void setType(PolicyType type) {
+ this.type = type;
+ }
+ public PolicyConfigStatus getPolicyConfigStatus() {
+ return policyConfigStatus;
+ }
+ public void setPolicyConfigStatus(PolicyConfigStatus policyConfigStatus) {
+ this.policyConfigStatus = policyConfigStatus;
+ }
+ public String getPolicyConfigMessage() {
+ return policyConfigMessage;
+ }
+ public void setPolicyConfigMessage(String policyConfigMessage) {
+ this.policyConfigMessage = policyConfigMessage;
+ }
+ public Map<String, String> getProperty() {
+ return property;
+ }
+ public void setProperty(Map<String, String> property) {
+ this.property = property;
+ }
+ public String getPolicyName(){
+ return policyName;
+ }
+ public void setPolicyName(String policyName){
+ this.policyName = policyName;
+ }
+ public String getPolicyVersion(){
+ return policyVersion;
+ }
+ public void setPolicyVersion(String policyVersion){
+ this.policyVersion = policyVersion;
+ }
+ public Map<String, String> getMatchingConditions(){
+ return matchingConditions;
+ }
+ public void setMatchingConditions(Map<String, String> matchingConditions){
+ this.matchingConditions = matchingConditions;
+ }
+ public void setResponseAttributes(Map<String,String> responseAttributes){
+ this.responseAttributes = responseAttributes;
+ }
+ public Map<String,String> getResponseAttributes(){
+ return responseAttributes;
+ }
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/Notification.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/Notification.java
new file mode 100644
index 000000000..a1717c275
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/Notification.java
@@ -0,0 +1,50 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.notifications;
+
+import java.util.Collection;
+
+import org.openecomp.policy.api.LoadedPolicy;
+import org.openecomp.policy.api.RemovedPolicy;
+
+public class Notification{
+
+ private Collection<RemovedPolicy> removedPolicies = null;
+ private Collection<LoadedPolicy> loadedPolicies = null;
+
+ public Collection<RemovedPolicy> getRemovedPolicies() {
+ return removedPolicies;
+ }
+
+ public Collection<LoadedPolicy> getLoadedPolicies() {
+ return loadedPolicies;
+ }
+
+
+ public void setRemovedPolicies(Collection<RemovedPolicy> removedPolicies){
+ this.removedPolicies = removedPolicies;
+ }
+
+ public void setLoadedPolicies(Collection<LoadedPolicy> loadedPolicies){
+ this.loadedPolicies = loadedPolicies;
+ }
+
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationController.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationController.java
new file mode 100644
index 000000000..0f2ed9b45
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationController.java
@@ -0,0 +1,149 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.notifications;
+
+import java.util.HashSet;
+import java.util.Iterator;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.openecomp.policy.api.LoadedPolicy;
+import org.openecomp.policy.api.NotificationHandler;
+import org.openecomp.policy.api.PDPNotification;
+import org.openecomp.policy.api.RemovedPolicy;
+import org.openecomp.policy.common.logging.eelf.MessageCodes;
+import org.openecomp.policy.common.logging.eelf.PolicyLogger;
+
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectWriter;
+
+public class NotificationController implements NotificationHandler{
+ private static final Log logger = LogFactory.getLog(NotificationController.class);
+ private static Notification record = new Notification();
+ //private static CountDownLatch latch;
+
+ @Override
+ public void notificationReceived(PDPNotification notification) {
+ //latch = new CountDownLatch(1);
+ if(notification!=null){
+ // Take this into our Record holder for polling requests.
+ NotificationServer.setUpdate(record(notification));
+ // Send the Update as is for AUTO clients.
+ ObjectWriter ow = new ObjectMapper().writer();
+ try{
+ String json = ow.writeValueAsString(notification);
+ System.out.println("\n Notification: "+json);
+ logger.info(json);
+ NotificationServer.sendNotification(json);
+ //latch.await();
+ } catch (JsonProcessingException e) {
+ logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e.getMessage());
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "");
+ }
+
+ }
+ }
+
+ public static String record(PDPNotification notification) {
+ // Initialization with updates.
+ if(record.getRemovedPolicies()== null){
+ record.setRemovedPolicies(notification.getRemovedPolicies());
+ }
+ if(record.getLoadedPolicies()== null){
+ record.setLoadedPolicies(notification.getLoadedPolicies());
+ }
+ // Check if there is anything new and update the record..
+ if(record.getLoadedPolicies()!= null || record.getRemovedPolicies()!=null) {
+ HashSet<RemovedPolicy> removedPolicies = (HashSet<RemovedPolicy>) record.getRemovedPolicies();
+ HashSet<LoadedPolicy> updatedPolicies = (HashSet<LoadedPolicy>) record.getLoadedPolicies();
+ // Checking with New updated policies.
+ if(notification.getLoadedPolicies()!= null && !notification.getLoadedPolicies().isEmpty()) {
+ for( LoadedPolicy newUpdatedPolicy : notification.getLoadedPolicies()) {
+ // If it was removed earlier then we need to remove from our record
+ Iterator<RemovedPolicy> oldRemovedPolicy = removedPolicies.iterator();
+ while(oldRemovedPolicy.hasNext()){
+ RemovedPolicy policy = oldRemovedPolicy.next();
+ if(newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) {
+ if(newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) {
+ oldRemovedPolicy.remove();
+ }
+ }
+ }
+ // If it was previously updated need to Overwrite it to the record.
+ Iterator<LoadedPolicy> oldUpdatedPolicy = updatedPolicies.iterator();
+ while(oldUpdatedPolicy.hasNext()){
+ LoadedPolicy policy = oldUpdatedPolicy.next();
+ if(newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) {
+ if(newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) {
+ oldUpdatedPolicy.remove();
+ }
+ }
+ }
+ updatedPolicies.add(newUpdatedPolicy);
+ }
+ }
+ // Checking with New Removed policies.
+ if(notification.getRemovedPolicies()!= null && !notification.getRemovedPolicies().isEmpty()) {
+ for( RemovedPolicy newRemovedPolicy : notification.getRemovedPolicies()) {
+ // If it was removed earlier then we need to remove from our record
+ Iterator<RemovedPolicy> oldRemovedPolicy = removedPolicies.iterator();
+ while(oldRemovedPolicy.hasNext()){
+ RemovedPolicy policy = oldRemovedPolicy.next();
+ if(newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) {
+ if(newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) {
+ oldRemovedPolicy.remove();
+ }
+ }
+ }
+ // If it was previously updated need to Overwrite it to the record.
+ Iterator<LoadedPolicy> oldUpdatedPolicy = updatedPolicies.iterator();
+ while(oldUpdatedPolicy.hasNext()){
+ LoadedPolicy policy = oldUpdatedPolicy.next();
+ if(newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) {
+ if(newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) {
+ oldUpdatedPolicy.remove();
+ }
+ }
+ }
+ removedPolicies.add(newRemovedPolicy);
+ }
+ }
+ record.setRemovedPolicies(removedPolicies);
+ record.setLoadedPolicies(updatedPolicies);
+ }
+ // Send the Result to the caller.
+ ObjectWriter om = new ObjectMapper().writer();
+ String json = null;
+ try {
+ json = om.writeValueAsString(record);
+ } catch (JsonProcessingException e) {
+ logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e.getMessage());
+ // TODO:EELF Cleanup - Remove logger
+ PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "");
+ }
+ logger.info(json);
+ return json;
+ }
+
+}
diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationServer.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationServer.java
new file mode 100644
index 000000000..44324b55c
--- /dev/null
+++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationServer.java
@@ -0,0 +1,90 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.pypdp.notifications;
+
+import java.io.IOException;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+import javax.websocket.OnClose;
+import javax.websocket.OnError;
+import javax.websocket.OnMessage;
+import javax.websocket.OnOpen;
+import javax.websocket.Session;
+import javax.websocket.server.ServerEndpoint;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+
+import org.openecomp.policy.xacml.api.XACMLErrorConstants;
+
+
+@ServerEndpoint(value = "/org.openecomp.policy.pypdp.notifications")
+public class NotificationServer {
+ private static final Logger logger = FlexLogger.getLogger(NotificationServer.class);
+ private static Queue<Session> queue = new ConcurrentLinkedQueue<Session>();
+ private static String update = null;
+
+ @OnOpen
+ public void openConnection(Session session) {
+ logger.info("Session Connected: " + session.getId());
+ queue.add(session);
+ }
+
+ @OnClose
+ public void closeConnection(Session session) {
+ queue.remove(session);
+ }
+
+ @OnError
+ public void error(Session session, Throwable t) {
+ queue.remove(session);
+ logger.info(XACMLErrorConstants.ERROR_SYSTEM_ERROR+ "Session Error for : " + session.getId() + " Error: " + t.getMessage());
+
+ }
+
+ @OnMessage
+ public void Message(String message, Session session) {
+ if(message.equalsIgnoreCase("Manual")) {
+ try {
+ session.getBasicRemote().sendText(update);
+ } catch (IOException e) {
+ logger.info(XACMLErrorConstants.ERROR_SYSTEM_ERROR+ "Error in sending the Event Notification: "+ e.getMessage());
+ }
+ }
+ }
+
+ public static void sendNotification(String notification){
+ for(Session session: queue) {
+ try {
+ session.getBasicRemote().sendText(notification);
+ } catch (IOException e) {
+ logger.info(XACMLErrorConstants.ERROR_SYSTEM_ERROR+ "Error in sending the Event Notification: "+ e.getMessage());
+ }
+ }
+ }
+
+ public static void setUpdate(String update) {
+ NotificationServer.update = update;
+ }
+} \ No newline at end of file
diff --git a/PyPDPServer/src/main/resources/log4j.properties b/PyPDPServer/src/main/resources/log4j.properties
new file mode 100644
index 000000000..2d810f0ad
--- /dev/null
+++ b/PyPDPServer/src/main/resources/log4j.properties
@@ -0,0 +1,56 @@
+###
+# ============LICENSE_START=======================================================
+# ECOMP Policy Engine
+# ================================================================================
+# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# ================================================================================
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ============LICENSE_END=========================================================
+###
+
+#
+# Use this properties for Deployments.
+#
+#
+# Set root logger level to DEBUG and its only appender to FILE.
+#log4j.rootLogger=DEBUG, FILE, CONSOLE
+log4j.rootLogger=INFO, FILE
+
+# FILE appender
+log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
+log4j.appender.FILE.File=${catalina.base}/logs/pypdp.log
+log4j.appender.FILE.ImmediateFlush=true
+log4j.appender.FILE.Threshold=debug
+log4j.appender.FILE.append=true
+log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
+log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
+log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss}{GMT+0}+00:00|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%l||%m%n
+
+# for Developments and Debugging
+#log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
+#log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
+#log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n
+
+#
+# audit (transaction) logging -- CURRENTLY NOT DONE IN PYPDP
+#
+#log4j.logger.auditLogger=INFO,AUDIT_LOG
+#log4j.additivity.auditLogger=false
+
+#log4j.appender.AUDIT_LOG=org.apache.log4j.DailyRollingFileAppender
+#log4j.appender.AUDIT_LOG.File=${catalina.base}/logs/audit.log
+#log4j.appender.AUDIT_LOG.Append=true
+#log4j.appender.AUDIT_LOG.DatePattern='.'yyyy-MM-dd
+#log4j.appender.AUDIT_LOG.threshold=INFO
+#log4j.appender.AUDIT_LOG.layout=org.apache.log4j.EnhancedPatternLayout
+#log4j.appender.AUDIT_LOG.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss}{GMT+0}+00:00|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%X{className}|%X{timer}|%m%n
diff --git a/PyPDPServer/src/main/resources/logback.xml b/PyPDPServer/src/main/resources/logback.xml
new file mode 100644
index 000000000..f89074199
--- /dev/null
+++ b/PyPDPServer/src/main/resources/logback.xml
@@ -0,0 +1,252 @@
+<!--
+ ============LICENSE_START=======================================================
+ ECOMP Policy Engine
+ ================================================================================
+ Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ ================================================================================
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ ============LICENSE_END=========================================================
+ -->
+
+<configuration scan="true" scanPeriod="3 seconds" debug="true">
+ <!--<jmxConfigurator /> -->
+ <!-- directory path for all other type logs -->
+ <property name="logDir" value="logs" />
+
+ <!-- directory path for debugging type logs -->
+ <property name="debugDir" value="logs" />
+
+ <!-- specify the component name
+ <ECOMP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" -->
+ <property name="componentName" value="Policy"></property>
+ <property name="subComponentName" value="PyPDPServer"></property>
+
+ <!-- log file names -->
+ <property name="errorLogName" value="error" />
+ <property name="metricsLogName" value="metrics" />
+ <property name="auditLogName" value="audit" />
+ <property name="debugLogName" value="debug" />
+
+
+ <!-- modified time stamp format -->
+
+ <!-- A U D I T
+ <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{ElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ -->
+ <property name="defaultAuditPattern" value="%X{TransactionBeginTimestamp}|%X{TransactionEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{TransactionElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+
+
+ <!-- M E T R I C
+ <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ -->
+ <property name="defaultMetricPattern" value="%X{MetricBeginTimestamp}|%X{MetricEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%p|%X{severity}|%X{serverIpAddress}|%X{MetricElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+
+
+ <!-- E R R O R
+ <property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
+ -->
+ <property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{requestId}|%t|%X{serviceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
+
+
+
+ <!-- D E B U G
+ <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
+ <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
+ -->
+ <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
+
+
+
+ <!-- D E F A U L T
+ <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
+ <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ -->
+ <property name="defaultPattern" value="%d{&quot;yyyy-MM-dd'T'HH:mm:ss.SSSXXX&quot;, UTC}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%c||%msg%n" />
+
+
+
+ <!-- P A T H
+ <property name="logDirectory" value="${catalina.base}/${logDir}/${componentName}/${subComponentName}" />
+ <property name="debugLogDirectory" value="${catalina.base}/${debugDir}/${componentName}/${subComponentName}" />
+ -->
+ <property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
+ <property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
+
+
+
+
+ <!-- Example evaluator filter applied against console appender -->
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>${defaultPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <!-- ============================================================================ -->
+ <!-- EELF Appenders -->
+ <!-- ============================================================================ -->
+
+ <!-- The EELFAppender is used to record events to the general application
+ log -->
+
+ <!-- EELF Audit Appender. This appender is used to record audit engine
+ related logging events. The audit logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
+ these events as part of the application root log. -->
+
+ <appender name="EELFAudit"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${auditLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${auditLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${defaultAuditPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFAudit" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFAudit" />
+ </appender>
+
+
+
+
+<appender name="EELFMetrics"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${metricsLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${metricsLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} -
+ %msg%n"</pattern> -->
+ <pattern>${defaultMetricPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFMetrics"/>
+ </appender>
+
+
+
+
+ <appender name="EELFError"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${errorLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${errorLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
+ <level>ERROR</level>
+ </filter>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${defaultErrorPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFError"/>
+ </appender>
+
+
+
+ <appender name="EELFDebug"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${debugLogDirectory}/${debugLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${debugLogDirectory}/${debugLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
+ <level>INFO</level>
+ </filter>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${debugLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFDebug" />
+ <includeCallerData>true</includeCallerData>
+ </appender>
+
+
+ <!-- ============================================================================ -->
+ <!-- EELF loggers -->
+ <!-- ============================================================================ -->
+
+ <logger name="com.att.eelf.audit" level="info" additivity="false">
+ <appender-ref ref="asyncEELFAudit" />
+ </logger>
+
+ <logger name="com.att.eelf.metrics" level="info" additivity="false">
+ <appender-ref ref="asyncEELFMetrics" />
+ </logger>
+
+ <logger name="com.att.eelf.error" level="error" additivity="false">
+ <appender-ref ref="asyncEELFError" />
+ </logger>
+
+ <logger name="com.att.eelf.debug" level="info" additivity="false">
+ <appender-ref ref="asyncEELFDebug" />
+ </logger>
+
+
+
+ <root level="INFO">
+ <appender-ref ref="asyncEELFDebug" />
+ <appender-ref ref="asyncEELFError" />
+ </root>
+
+</configuration> \ No newline at end of file
diff --git a/PyPDPServer/src/test/java/testpypdp/AuthorizationTest.java b/PyPDPServer/src/test/java/testpypdp/AuthorizationTest.java
new file mode 100644
index 000000000..228e926a8
--- /dev/null
+++ b/PyPDPServer/src/test/java/testpypdp/AuthorizationTest.java
@@ -0,0 +1,382 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package testpypdp;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import org.openecomp.policy.pypdp.authorization.AuthenticationFilter;
+
+/*
+ * Authentication Filter Testing
+ */
+public class AuthorizationTest {
+ private static final String MASTERCLIENT= "cHl0aG9uOnRlc3Q=";
+ /*private static final String CONFIGCLIENT= "Y29uZmlnOmNvbmZpZw==";
+ private static final String ACTIONCLIENT= "YWN0aW9uOmFjdGlvbg==";
+ private static final String DECIDECLIENT= "ZGVjaWRlOmRlY2lkZQ==";
+ private static final String CREATECLIENT= "Y3JlYXRlOmNyZWF0ZQ==";
+ private static final String DELETECLIENT= "ZGVsZXRlOmRlbGV0ZQ==";*/
+
+ private AuthenticationFilter authenticationFilter = new AuthenticationFilter();
+
+ @Before
+ public void setUp() throws Exception{
+ authenticationFilter.init(null);
+ }
+
+ @Test
+ public void testDoFilterError() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getRequestURI()).thenReturn("error");
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+
+ // verify if unauthorized
+ verify(httpServletResponse).setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ }
+
+ @Test
+ public void testDoFilterNotification() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getRequestURI()).thenReturn("org.openecomp.policy.pypdp.notifications swagger api-docs configuration");
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+
+ verify(filterChain).doFilter(httpServletRequest,httpServletResponse);
+ }
+
+ /*@Test
+ public void testDoFilterWrongAuthenticaton() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("error");
+ when(httpServletRequest.getRequestURI()).thenReturn("getConfig");
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+
+ // verify if unauthorized
+ verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }*/
+
+ /*@Test
+ public void testDoFilterWrongClientAuthenticaton() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("getConfig");
+ when(httpServletRequest.getHeader("ClientAuth")).thenReturn("Error");
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+ // verify if unauthorized
+ verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }*/
+
+ @Test
+ public void testDoFilterWrongClientAuthenticatonCount() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("count");
+ when(httpServletRequest.getHeader("ClientAuth")).thenReturn("Error");
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+
+ verify(filterChain).doFilter(httpServletRequest,httpServletResponse);
+ }
+
+ /*@Test
+ public void testDoFilterWrongGetConfigAuthorization() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("getConfig");
+ when(httpServletRequest.getHeader("ClientAuth")).thenReturn(ACTIONCLIENT);
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+ // verify if unauthorized
+ verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }*/
+
+ /*@Test
+ public void testDoFilterWrongSendEventAuthorization() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("sendEvent");
+ when(httpServletRequest.getHeader("ClientAuth")).thenReturn(CONFIGCLIENT);
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+ // verify if unauthorized
+ verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }*/
+
+ /*@Test
+ public void testDoFilterWrongUpdatePolicyAuthorization() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("updatePolicy");
+ when(httpServletRequest.getHeader("ClientAuth")).thenReturn(ACTIONCLIENT);
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+ // verify if unauthorized
+ verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }*/
+
+ /*@Test
+ public void testDoFilterWrongCreatePolicyAuthorization() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("createPolicy");
+ when(httpServletRequest.getHeader("ClientAuth")).thenReturn(ACTIONCLIENT);
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+ // verify if unauthorized
+ verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }*/
+
+ /*@Test
+ public void testDoFilterWrongPushPolicyAuthorization() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("pushPolicy");
+ when(httpServletRequest.getHeader("ClientAuth")).thenReturn(DELETECLIENT);
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+ // verify if unauthorized
+ verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }*/
+
+ /*@Test
+ public void testDoFilterWrongDeletePolicyAuthorization() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("deletePolicy");
+ when(httpServletRequest.getHeader("ClientAuth")).thenReturn(DECIDECLIENT);
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+ // verify if unauthorized
+ verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }*/
+
+ /*@Test
+ public void testDoFilterWrongDecidePolicyAuthorization() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("getDecision");
+ when(httpServletRequest.getHeader("ClientAuth")).thenReturn(CREATECLIENT);
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+ // verify if unauthorized
+ verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ }*/
+
+ @Test
+ public void testDoFilterAuthorizedError() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("error");
+ when(httpServletRequest.getHeader("ClientAuth")).thenReturn(MASTERCLIENT);
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+ // verify if unauthorized
+ verify(httpServletResponse).setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ }
+
+ @Test
+ public void testDoFilterAuthorizedPDPs() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("pdps paps");
+ when(httpServletRequest.getHeader("ClientAuth")).thenReturn(MASTERCLIENT);
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+
+ verify(filterChain).doFilter(httpServletRequest,httpServletResponse);
+ }
+
+ @Test
+ public void testDoFilterDecideAuthorized() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("getDecision");
+ when(httpServletRequest.getHeader(AuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("DEVL");
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+
+ verify(filterChain).doFilter(httpServletRequest,httpServletResponse);
+ }
+
+ @Test
+ public void testDoFilterDeleteAuthorized() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("deletePolicy");
+ when(httpServletRequest.getHeader(AuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("DEVL");
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+
+ verify(filterChain).doFilter(httpServletRequest,httpServletResponse);
+ }
+
+ @Test
+ public void testDoFilterEventAuthorized() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("sendEvent");
+ when(httpServletRequest.getHeader(AuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("DEVL");
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+
+ verify(filterChain).doFilter(httpServletRequest,httpServletResponse);
+ }
+
+ @Test
+ public void testDoFilterCreateAuthorized() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("createPolicy pushPolicy updatePolicy");
+ when(httpServletRequest.getHeader(AuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("DEVL");
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+
+ verify(filterChain).doFilter(httpServletRequest,httpServletResponse);
+ }
+
+ @Test
+ public void testDoFilterConfigAuthorized() throws IOException, ServletException {
+ // create the objects to be mocked
+ HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
+ HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
+ FilterChain filterChain = mock(FilterChain.class);
+ //
+ when(httpServletRequest.getHeader(AuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic dGVzdHJlc3Q6c2VjVXJl");
+ when(httpServletRequest.getRequestURI()).thenReturn("getConfig");
+ when(httpServletRequest.getHeader(AuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("DEVL");
+
+ authenticationFilter.doFilter(httpServletRequest, httpServletResponse,
+ filterChain);
+
+ verify(filterChain).doFilter(httpServletRequest,httpServletResponse);
+ }
+
+ @After
+ public void tearDown(){
+ authenticationFilter.destroy();
+ }
+}
diff --git a/PyPDPServer/src/test/java/testpypdp/ConfigRequestTest.java b/PyPDPServer/src/test/java/testpypdp/ConfigRequestTest.java
new file mode 100644
index 000000000..30e94fed9
--- /dev/null
+++ b/PyPDPServer/src/test/java/testpypdp/ConfigRequestTest.java
@@ -0,0 +1,82 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package testpypdp;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.Properties;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.openecomp.policy.pypdp.model_pojo.PyPolicyConfig;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.openecomp.policy.api.PolicyConfigStatus;
+import org.openecomp.policy.api.PolicyType;
+import org.openecomp.policy.std.StdPolicyConfig;
+import org.w3c.dom.Document;
+import org.xml.sax.InputSource;
+
+import org.openecomp.policy.pypdp.ConfigRequest;
+
+public class ConfigRequestTest {
+
+ private StdPolicyConfig config;
+ private ConfigRequest request;
+
+ @Before
+ public void setUp() {
+ request = new ConfigRequest(null);
+ config = new StdPolicyConfig();
+ config.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_RETRIEVED);
+ }
+
+ @Test
+ public void checkResponsePropertiesTest() {
+ config.setPolicyType(PolicyType.PROPERTIES);
+ Properties prop = new Properties();
+ prop.put("Key", "value");
+ config.setProperties(prop);
+ PyPolicyConfig pConfig = request.checkResponse(config);
+ HashMap<String, String> result = new HashMap<String, String>();
+ result.put("Key", "value");
+ assertEquals(pConfig.getProperty(), result);
+ }
+
+ @Test
+ public void checkResponseDocumentTest() throws Exception {
+ config.setPolicyType(PolicyType.XML);
+ String xmlString = "<test></test>";
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder builder;
+ builder = factory.newDocumentBuilder();
+ Document document = builder.parse(new InputSource(new StringReader(
+ xmlString)));
+ config.setDocument(document);
+ PyPolicyConfig pConfig = request.checkResponse(config);
+ assertNotNull(pConfig.getConfig());
+ }
+}
diff --git a/PyPDPServer/src/test/java/testpypdp/NotificationControllerTest.java b/PyPDPServer/src/test/java/testpypdp/NotificationControllerTest.java
new file mode 100644
index 000000000..c2d9089e3
--- /dev/null
+++ b/PyPDPServer/src/test/java/testpypdp/NotificationControllerTest.java
@@ -0,0 +1,129 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package testpypdp;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.policy.pypdp.notifications.NotificationController;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.openecomp.policy.api.LoadedPolicy;
+import org.openecomp.policy.api.NotificationType;
+import org.openecomp.policy.api.PDPNotification;
+import org.openecomp.policy.api.RemovedPolicy;
+import org.openecomp.policy.api.UpdateType;
+import org.openecomp.policy.std.StdLoadedPolicy;
+import org.openecomp.policy.std.StdPDPNotification;
+import org.openecomp.policy.std.StdRemovedPolicy;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class NotificationControllerTest {
+ private NotificationController notificationController = new NotificationController();
+ private StdPDPNotification notification;
+
+ @Before
+ public void setUp() {
+ notification = new StdPDPNotification();
+ notification.setNotificationType(NotificationType.BOTH);
+ Collection<StdRemovedPolicy> removedPolicies = new ArrayList<StdRemovedPolicy>();
+ Collection<StdLoadedPolicy> loadedPolicies = new ArrayList<StdLoadedPolicy>();
+ StdRemovedPolicy removedPolicy = new StdRemovedPolicy();
+ StdLoadedPolicy updatedPolicy = new StdLoadedPolicy();
+ removedPolicy.setPolicyName("Test");
+ removedPolicy.setVersionNo("1");
+ removedPolicies.add(removedPolicy);
+ updatedPolicy.setPolicyName("Testing");
+ updatedPolicy.setVersionNo("1");
+ updatedPolicy.setUpdateType(UpdateType.NEW);
+ Map<String, String> matches = new HashMap<String, String>();
+ matches.put("key", "value");
+ updatedPolicy.setMatches(matches);
+ loadedPolicies.add(updatedPolicy);
+ notification.setRemovedPolicies(removedPolicies);
+ notification.setLoadedPolicies(loadedPolicies);
+ NotificationController.record(notification);
+ }
+
+ @Test
+ public void notificationReceivedUpdateTest() throws Exception{
+ StdPDPNotification notification = new StdPDPNotification();
+ notification.setNotificationType(NotificationType.UPDATE);
+ Collection<StdLoadedPolicy> loadedPolicies = new ArrayList<StdLoadedPolicy>();
+ StdLoadedPolicy updatedPolicy = new StdLoadedPolicy();
+ updatedPolicy.setPolicyName("Test");
+ updatedPolicy.setVersionNo("1");
+ updatedPolicy.setUpdateType(UpdateType.NEW);
+ Map<String, String> matches = new HashMap<String, String>();
+ matches.put("key", "value");
+ updatedPolicy.setMatches(matches);
+ loadedPolicies.add(updatedPolicy);
+ notification.setLoadedPolicies(loadedPolicies);
+ notificationController.notificationReceived(notification);
+ Boolean result = false;
+ PDPNotification newNotification= jsonStringToNotification(NotificationController.record(notification));
+ for(LoadedPolicy loadedPolicy: newNotification.getLoadedPolicies()){
+ if(loadedPolicy.getPolicyName().equals("Test") && loadedPolicy.getVersionNo().equals("1")){
+ result = true;
+ }
+ }
+ assertEquals(result,true);
+ /*assertEquals(
+ NotificationController.record(notification),
+ "{\"removedPolicies\":[],\"updatedPolicies\":[{\"policyName\":\"Test\",\"versionNo\":\"1\",\"matches\":{\"key\":\"value\"},\"updateType\":\"NEW\"},{\"policyName\":\"Testing\",\"versionNo\":\"1\",\"matches\":{\"key\":\"value\"},\"updateType\":\"NEW\"}]}");*/
+ }
+
+ @Test
+ public void notificationReceivedRemovedTest() throws Exception{
+ StdPDPNotification notification = new StdPDPNotification();
+ notification.setNotificationType(NotificationType.REMOVE);
+ Collection<StdRemovedPolicy> removedPolicies = new ArrayList<StdRemovedPolicy>();
+ StdRemovedPolicy removedPolicy = new StdRemovedPolicy();
+ removedPolicy.setPolicyName("Testing");
+ removedPolicy.setVersionNo("1");
+ removedPolicies.add(removedPolicy);
+ notification.setRemovedPolicies(removedPolicies);
+ notificationController.notificationReceived(notification);
+ Boolean result = false;
+ PDPNotification newNotification= jsonStringToNotification(NotificationController.record(notification));
+ for(RemovedPolicy removed: newNotification.getRemovedPolicies()){
+ if(removed.getPolicyName().equals("Testing") && removed.getVersionNo().equals("1")){
+ result = true;
+ }
+ }
+ assertEquals(result,true);
+ /*assertEquals(
+ NotificationController.record(notification),
+ "{\"removedPolicies\":[{\"policyName\":\"Test\",\"versionNo\":\"1\"},{\"policyName\":\"Testing\",\"versionNo\":\"1\"}],\"updatedPolicies\":[]}");*/
+ }
+
+ public StdPDPNotification jsonStringToNotification(String json) throws Exception{
+ ObjectMapper mapper = new ObjectMapper();
+ return notification = mapper.readValue(json, StdPDPNotification.class);
+ }
+
+}
diff --git a/PyPDPServer/src/test/java/testpypdp/PolicyEngineServicesTest.java b/PyPDPServer/src/test/java/testpypdp/PolicyEngineServicesTest.java
new file mode 100644
index 000000000..a451c84f0
--- /dev/null
+++ b/PyPDPServer/src/test/java/testpypdp/PolicyEngineServicesTest.java
@@ -0,0 +1,969 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package testpypdp;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.ws.rs.core.MediaType;
+
+import org.openecomp.policy.pypdp.model_pojo.PepConfigFirewallPolicyRequest;
+import org.openecomp.policy.pypdp.model_pojo.PepConfigPolicyNameRequest;
+import org.openecomp.policy.pypdp.model_pojo.PepConfigPolicyRequest;
+import org.openecomp.policy.pypdp.model_pojo.PepPushPolicyRequest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.policy.api.ConfigRequestParameters;
+import org.openecomp.policy.api.DeletePolicyParameters;
+import org.openecomp.policy.api.EventRequestParameters;
+import org.openecomp.policy.api.PolicyParameters;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.SpringApplicationConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.web.WebAppConfiguration;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.web.context.WebApplicationContext;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.openecomp.policy.pypdp.controller.Application;
+import org.openecomp.policy.pypdp.controller.PolicyEngineServices;
+
+/**
+ * Test for Policy Engine REST Services
+ *
+ *
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@SpringApplicationConfiguration(classes = { Application.class,
+ PolicyEngineServices.class })
+@WebAppConfiguration
+public class PolicyEngineServicesTest {
+ private MockMvc mockMvc;
+ // Don't Change this.
+ private static final String CONFIG_ERROR_MESSAGE = "[{\"policyConfigMessage\": \"PE300 - Data Issue: PolicyFile Name is empty\","
+ + "\"policyConfigStatus\": \"CONFIG_NOT_FOUND\","
+ + "\"type\": null,"
+ + "\"config\": null,"
+ + "\"policyName\": null,"
+ + "\"policyVersion\": null,"
+ + "\"matchingConditions\": null,"
+ + "\"responseAttributes\": null," + "\"property\": null" + "}]";
+ private static final String VALID_JSON = "{\"serviceTypeId\": \"/v0/firewall/pan\",\"configName\": \"rule1607\",\"deploymentOption\":{\"deployNow\": false},\"securityZoneId\": \"/v0/firewall/pan\",\"serviceGroups\": [{\"name\": \"1607Group\",\"description\": null,\"members\": [{\"type\": \"REFERENCE\",\"name\": \"SList\"},{\"type\": \"REFERENCE\",\"name\": \"Syslog\"}]}, {\"name\": \"Syslog\",\"description\": \"NA\",\"type\": \"SERVICE\",\"transportProtocol\": \"udp\",\"appProtocol\": null,\"ports\": \"514\"}, {\"name\": \"SList\",\"description\": \"Service List\",\"type\": \"SERVICE\",\"transportProtocol\": \"tcp\",\"appProtocol\": null,\"ports\": \"8080\"}],\"addressGroups\": [{\"name\": \"1607Group\",\"description\": null,\"members\": [{\"type\": \"REFERENCE\",\"name\": \"10.11.12.13/14\"},{\"type\": \"REFERENCE\",\"name\": \"10.11.12.13/14\"}]},{\"name\": \"PL_CCE3\",\"description\": \"CCE Routers\",\"members\":[{\"type\": \"REFERENCE\",\"name\": \"10.11.12.13/14\"}]}],\"firewallRuleList\": [{\"position\": \"1\",\"ruleName\": \"1607Rule\",\"fromZones\": [\"Trusted\"],\"toZones\": [\"Untrusted\"],\"negateSource\": false,\"negateDestination\": false,\"sourceList\": [{\"type\": \"REFERENCE\",\"name\": \"PL_CCE3\"}, {\"type\": \"REFERENCE\",\"name\": \"1607Group\"}],\"destinationList\": [{\"type\": \"REFERENCE\",\"name\": \"1607Group\"}],\"sourceServices\": [],\"destServices\": [{\"type\": \"REFERENCE\",\"name\": \"1607Group\"}],\"action\": \"accept\",\"description\": \"Rule for 1607 templates\",\"enabled\": true,\"log\": true}]}";
+ private static final String INVALID_JSON = "{\"test\": \"value}";
+
+ @Autowired
+ private PolicyEngineServices policyEngineServicesMock;
+
+ @Autowired
+ private WebApplicationContext webApplicationContext;
+
+ @Before
+ public void setup() throws Exception {
+ this.mockMvc = webAppContextSetup(webApplicationContext).build();
+
+ }
+
+ // Tests for getConfig API
+ @Test
+ public void getConfigUsingNoHeader() throws Exception {
+ ConfigRequestParameters pep = new ConfigRequestParameters();
+ pep.setPolicyName(".*");
+ mockMvc.perform(
+ post("/getConfig").content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().is(400));
+ }
+
+ @Test
+ public void getConfigUsingErrorHeader() throws Exception {
+ ConfigRequestParameters pep = new ConfigRequestParameters();
+ pep.setPolicyName(".*");
+ mockMvc.perform(
+ post("/getConfig").header("X-ECOMP-RequestID", "Error123")
+ .header("ClientAuth", "Basic bTAzNzQyOlBvbGljeVIwY2sk")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isOk());
+ }
+
+ @Test
+ public void getConfigEmptyEcompName() throws Exception {
+ ConfigRequestParameters pep = new ConfigRequestParameters();
+ pep.setEcompName("");
+ mockMvc.perform(
+ post("/getConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void getConfigEmptyPolicyName() throws Exception {
+ ConfigRequestParameters pep = new ConfigRequestParameters();
+ pep.setPolicyName("");
+ mockMvc.perform(
+ post("/getConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void getConfigUsingErrorPolicyName() throws Exception {
+ ConfigRequestParameters pep = new ConfigRequestParameters();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ post("/getConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void getConfigUsingErrorEcompName() throws Exception {
+ ConfigRequestParameters pep = new ConfigRequestParameters();
+ pep.setEcompName("test");
+ mockMvc.perform(
+ post("/getConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void getConfigUsingALLPolicyName() throws Exception {
+ ConfigRequestParameters pep = new ConfigRequestParameters();
+ pep.setPolicyName(".*");
+ mockMvc.perform(
+ post("/getConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .header("ClientAuth", "Basic bTAzNzQyOlBvbGljeVIwY2sk")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isOk());
+ }
+
+ @Test
+ public void getConfigUsingNullPolicyName() throws Exception {
+ ConfigRequestParameters pep = new ConfigRequestParameters();
+ mockMvc.perform(
+ post("/getConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void getConfigUsingNullEcompName() throws Exception {
+ ConfigRequestParameters pep = new ConfigRequestParameters();
+ pep.setEcompName(null);
+ mockMvc.perform(
+ post("/getConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ // Tests for GetConfigByPolicyName API
+ @Test
+ public void getConfigByPolicyNameUsingErrorHeader() throws Exception {
+ PepConfigPolicyNameRequest pep = new PepConfigPolicyNameRequest();
+ pep.setPolicyName(null);
+ mockMvc.perform(
+ post("/getConfigByPolicyName")
+ .header("X-ECOMP-RequestID", "ERROR123")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().is(400));
+ }
+
+ @Test
+ public void getConfigByPolicyNameUsingNoHeader() throws Exception {
+ PepConfigPolicyNameRequest pep = new PepConfigPolicyNameRequest();
+ pep.setPolicyName(null);
+ mockMvc.perform(
+ post("/getConfigByPolicyName").content(
+ this.ObjectToJsonString(pep)).contentType(
+ MediaType.APPLICATION_JSON)).andExpect(status().is(400));
+ }
+
+ @Test
+ public void getConfigByPolicyNameUsingEmptyPolicyName() throws Exception {
+ PepConfigPolicyNameRequest pep = new PepConfigPolicyNameRequest();
+ pep.setPolicyName("");
+ mockMvc.perform(
+ post("/getConfigByPolicyName")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .header("ClientAuth", "Basic bTAzNzQyOlBvbGljeVIwY2sk")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk())
+ .andExpect(content().json(CONFIG_ERROR_MESSAGE));
+ }
+
+ @Test
+ public void getConfigByPolicyNameUsingNullPolicyName() throws Exception {
+ PepConfigPolicyNameRequest pep = new PepConfigPolicyNameRequest();
+ pep.setPolicyName(null);
+ mockMvc.perform(
+ post("/getConfigByPolicyName")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .header("ClientAuth", "Basic bTAzNzQyOlBvbGljeVIwY2sk")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON))
+ .andExpect(status().isOk())
+ .andExpect(content().json(CONFIG_ERROR_MESSAGE));
+ }
+
+ @Test
+ public void getConfigByPolicyNameUsingALLPolicyName() throws Exception {
+ PepConfigPolicyNameRequest pep = new PepConfigPolicyNameRequest();
+ pep.setPolicyName(".*");
+ mockMvc.perform(
+ post("/getConfigByPolicyName")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .header("ClientAuth", "Basic bTAzNzQyOlBvbGljeVIwY2sk")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isOk());
+ }
+
+ // Tests for SendEvent API
+ @Test
+ public void sendEventUsingNoHeader() throws Exception {
+ EventRequestParameters pep = new EventRequestParameters();
+ pep.setEventAttributes(null);
+ mockMvc.perform(
+ post("/sendEvent").content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void sendEventUsingErrorHeader() throws Exception {
+ EventRequestParameters pep = new EventRequestParameters();
+ pep.setEventAttributes(null);
+ mockMvc.perform(
+ post("/sendEvent").header("X-ECOMP-RequestID", "ERROR123")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void sendEventUsingNullEventAttributes() throws Exception {
+ EventRequestParameters pep = new EventRequestParameters();
+ pep.setEventAttributes(null);
+ mockMvc.perform(
+ post("/sendEvent")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void sendEventUsingEmptyEventAttributes() throws Exception {
+ EventRequestParameters pep = new EventRequestParameters();
+ Map<String, String> emptyMap = new HashMap<String, String>();
+ pep.setEventAttributes(emptyMap);
+ mockMvc.perform(
+ post("/sendEvent")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void sendEventUsingErrorEventAttributes() throws Exception {
+ EventRequestParameters pep = new EventRequestParameters();
+ Map<String, String> eventMap = new HashMap<String, String>();
+ eventMap.put("key", "value");
+ pep.setEventAttributes(eventMap);
+ mockMvc.perform(
+ post("/sendEvent")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ // Tests for Push Policy API
+ @Test
+ public void pushPolicyUsingNoHeader() throws Exception {
+ PepPushPolicyRequest pep = new PepPushPolicyRequest();
+ mockMvc.perform(
+ put("/pushPolicy").content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void pushPolicyUsingErrorHeader() throws Exception {
+ PepPushPolicyRequest pep = new PepPushPolicyRequest();
+ mockMvc.perform(
+ put("/pushPolicy").header("X-ECOMP-RequestID", "Error123")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void pushPolicyUsingNullRequest() throws Exception {
+ PepPushPolicyRequest pep = new PepPushPolicyRequest();
+ mockMvc.perform(
+ put("/pushPolicy")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void pushPolicyUsingNoScope() throws Exception {
+ PepPushPolicyRequest pep = new PepPushPolicyRequest();
+ pep.setPolicyName("Tarun");
+ mockMvc.perform(
+ put("/pushPolicy")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void pushPolicyUsingScopeinName() throws Exception {
+ PepPushPolicyRequest pep = new PepPushPolicyRequest();
+ pep.setPolicyName("Test.PolicyName");
+ mockMvc.perform(
+ put("/pushPolicy")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void pushPolicyUsingPolicyType() throws Exception {
+ PepPushPolicyRequest pep = new PepPushPolicyRequest();
+ pep.setPolicyName("Test.PolicyName");
+ pep.setPolicyType("CONFIG BASE");
+ mockMvc.perform(
+ put("/pushPolicy")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void pushPolicyUsingErrorRequest() throws Exception {
+ PepPushPolicyRequest pep = new PepPushPolicyRequest();
+ pep.setPolicyName("Test.PolicyName");
+ pep.setPolicyType("CONFIG BASE");
+ pep.setPdpGroup("default");
+ mockMvc.perform(
+ put("/pushPolicy")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ // Tests for Delete Policy API
+ @Test
+ public void deletePolicyUsingNoHeader() throws Exception {
+ DeletePolicyParameters pep = new DeletePolicyParameters();
+ mockMvc.perform(
+ delete("/deletePolicy").content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void deletePolicyUsingErrorHeader() throws Exception {
+ DeletePolicyParameters pep = new DeletePolicyParameters();
+ mockMvc.perform(
+ delete("/deletePolicy").header("X-ECOMP-RequestID", "ERROR123")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void deletePolicyUsingErrorPolicyName() throws Exception {
+ DeletePolicyParameters pep = new DeletePolicyParameters();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ delete("/deletePolicy")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void deletePolicyUsingErrorPolicyComponent() throws Exception {
+ DeletePolicyParameters pep = new DeletePolicyParameters();
+ pep.setPolicyName("test");
+ pep.setPolicyComponent("test");
+ mockMvc.perform(
+ delete("/deletePolicy")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ // Tests for CreatePolicy API
+ @Test
+ public void createPolicyUsingNoHeader() throws Exception {
+ PolicyParameters pep = new PolicyParameters();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ put("/createPolicy").content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createPolicyUsingErrorHeader() throws Exception {
+ PolicyParameters pep = new PolicyParameters();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ put("/createPolicy").content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID", "Error123")
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createPolicyUsingNullParameters() throws Exception {
+ PolicyParameters pep = new PolicyParameters();
+ mockMvc.perform(
+ put("/createPolicy")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createPolicyUsingEmptyPolicyName() throws Exception {
+ PolicyParameters pep = new PolicyParameters();
+ pep.setPolicyName("");
+ mockMvc.perform(
+ put("/createPolicy")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ // Tests for UpdatePolicy API
+ @Test
+ public void updatePolicyUsingNoHeader() throws Exception {
+ PolicyParameters pep = new PolicyParameters();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ put("/updatePolicy").content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updatePolicyUsingErrorHeader() throws Exception {
+ PolicyParameters pep = new PolicyParameters();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ put("/updatePolicy").content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID", "Error123")
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updatePolicyUsingNullParameters() throws Exception {
+ PolicyParameters pep = new PolicyParameters();
+ mockMvc.perform(
+ put("/updatePolicy")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updatePolicyUsingEmptyPolicyName() throws Exception {
+ PolicyParameters pep = new PolicyParameters();
+ pep.setPolicyName("");
+ mockMvc.perform(
+ put("/updatePolicy")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ // Tests for createConfig API
+ @Test
+ public void createConfigUsingNoHeader() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ put("/createConfig").content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createConfigUsingErrorHeader() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ put("/createConfig").content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID", "Error123")
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createConfigUsingNullParameters() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ mockMvc.perform(
+ put("/createConfig")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createConfigUsingEmptyPolicyName() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ pep.setPolicyName("");
+ mockMvc.perform(
+ put("/createConfig")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createConfigUsingEmptyConfigName() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ pep.setPolicyName("test");
+ pep.setEcompName("ecomp");
+ mockMvc.perform(
+ put("/createConfig")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createConfigUsingEmptyPolicyScope() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ pep.setPolicyName("test");
+ pep.setEcompName("ecomp");
+ pep.setConfigName("config");
+ mockMvc.perform(
+ put("/createConfig")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createConfigUsingErrorPolicyScope() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ pep.setPolicyName("test");
+ pep.setEcompName("ecomp");
+ pep.setConfigName("config");
+ pep.setPolicyScope("test");
+ mockMvc.perform(
+ put("/createConfig")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ // Test API for updateConfig API
+ @Test
+ public void updateConfigUsingNoHeader() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ put("/updateConfig").content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updateConfigUsingErrorHeader() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ put("/updateConfig").content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID", "Error123")
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updateConfigUsingNullParameters() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ mockMvc.perform(
+ put("/updateConfig")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updateConfigUsingEmptyPolicyName() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ pep.setPolicyName("");
+ mockMvc.perform(
+ put("/updateConfig")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updateConfigUsingEmptyConfigName() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ pep.setPolicyName("test");
+ pep.setEcompName("ecomp");
+ mockMvc.perform(
+ put("/updateConfig")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updateConfigUsingEmptyPolicyScope() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ pep.setPolicyName("test");
+ pep.setEcompName("ecomp");
+ pep.setConfigName("config");
+ mockMvc.perform(
+ put("/updateConfig")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updateConfigUsingErrorPolicyScope() throws Exception {
+ PepConfigPolicyRequest pep = new PepConfigPolicyRequest();
+ pep.setPolicyName("test");
+ pep.setEcompName("ecomp");
+ pep.setConfigName("config");
+ pep.setPolicyScope("test");
+ mockMvc.perform(
+ put("/updateConfig")
+ .content(this.ObjectToJsonString(pep))
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ // Tests for createFirewallConfig API
+ @Test
+ public void createFirewallConfigUsingNoHeader() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ put("/createFirewallConfig").content(
+ this.ObjectToJsonString(pep)).contentType(
+ MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createFirewallConfigUsingErrorHeader() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ put("/createFirewallConfig")
+ .header("X-ECOMP-RequestID", "Error123")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createFirewallConfigUsingNullParameters() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ mockMvc.perform(
+ put("/createFirewallConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createFirewallConfigUsingEmptyPolicyName() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ pep.setPolicyName("");
+ mockMvc.perform(
+ put("/createFirewallConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createFirewallConfigUsingEmptyPolicyScope() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ pep.setPolicyName("test");
+ pep.setFirewallJson(VALID_JSON);
+ pep.setPolicyScope("");
+ mockMvc.perform(
+ put("/createFirewallConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createFirewallConfigUsingInValidJSON() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ pep.setPolicyName("test");
+ pep.setFirewallJson(INVALID_JSON);
+ pep.setPolicyScope("test");
+ mockMvc.perform(
+ put("/createFirewallConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void createFirewallConfigUsingValidJSON() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ pep.setPolicyName("test");
+ pep.setFirewallJson(VALID_JSON);
+ pep.setPolicyScope("test");
+ mockMvc.perform(
+ put("/createFirewallConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .header("ClientAuth", "Basic bTAzNzQyOlBvbGljeVIwY2sk")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isOk());
+ }
+
+ // Tests for updateFirewallConfig API
+ @Test
+ public void updateFirewallConfigUsingNoHeader() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ put("/updateFirewallConfig").content(
+ this.ObjectToJsonString(pep)).contentType(
+ MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updateFirewallConfigUsingErrorHeader() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ pep.setPolicyName("test");
+ mockMvc.perform(
+ put("/updateFirewallConfig")
+ .header("X-ECOMP-RequestID", "Error123")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updateFirewallConfigUsingNullParameters() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ mockMvc.perform(
+ put("/updateFirewallConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updateFirewallConfigUsingEmptyPolicyName() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ pep.setPolicyName("");
+ mockMvc.perform(
+ put("/updateFirewallConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updateFirewallConfigUsingEmptyPolicyScope() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ pep.setPolicyName("test");
+ pep.setFirewallJson(VALID_JSON);
+ pep.setPolicyScope("");
+ mockMvc.perform(
+ put("/updateFirewallConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updateFirewallConfigUsingInValidJSON() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ pep.setPolicyName("test");
+ pep.setFirewallJson(INVALID_JSON);
+ pep.setPolicyScope("test");
+ mockMvc.perform(
+ put("/updateFirewallConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isBadRequest());
+ }
+
+ @Test
+ public void updateFirewallConfigUsingValidJSON() throws Exception {
+ PepConfigFirewallPolicyRequest pep = new PepConfigFirewallPolicyRequest();
+ pep.setPolicyName("test");
+ pep.setFirewallJson(VALID_JSON);
+ pep.setPolicyScope("test");
+ mockMvc.perform(
+ put("/updateFirewallConfig")
+ .header("X-ECOMP-RequestID",
+ UUID.randomUUID().toString())
+ .header("ClientAuth", "Basic bTAzNzQyOlBvbGljeVIwY2sk")
+ .content(this.ObjectToJsonString(pep))
+ .contentType(MediaType.APPLICATION_JSON)).andExpect(
+ status().isOk());
+ }
+
+ //Health Check Tests
+ @Test
+ public void getCountTest() throws Exception {
+ mockMvc.perform(get("/count"))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ public void getPDPsTest() throws Exception {
+ mockMvc.perform(get("/pdps"))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ public void getPAPsTest() throws Exception {
+ mockMvc.perform(get("/paps"))
+ .andExpect(status().isOk());
+ }
+
+ // Helper Method to create JSONString from a given Object.
+ public String ObjectToJsonString(Object o) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ return mapper.writeValueAsString(o);
+ }
+
+}