aboutsummaryrefslogtreecommitdiffstats
path: root/ONAP-PDP-REST/src
diff options
context:
space:
mode:
Diffstat (limited to 'ONAP-PDP-REST/src')
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java42
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpLoader.java1171
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java30
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java80
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java2
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java8
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java10
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java20
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java22
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java24
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java369
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/AuthenticationService.java4
-rw-r--r--ONAP-PDP-REST/src/main/resources/logback.xml142
-rw-r--r--ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java54
-rw-r--r--ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java8
-rw-r--r--ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/GetDictionaryServiceTest.java2
-rw-r--r--ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java1
-rw-r--r--ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/AuthenticationServiceTest.java11
-rw-r--r--ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java2
-rw-r--r--ONAP-PDP-REST/src/test/resources/META-INF/drop.ddl2
-rw-r--r--ONAP-PDP-REST/src/test/resources/META-INF/persistence.xml32
-rw-r--r--ONAP-PDP-REST/src/test/resources/test.drl1113
22 files changed, 1058 insertions, 2091 deletions
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java
index 0fab3db61..237ed9334 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java
@@ -7,9 +7,9 @@
* 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.
@@ -31,7 +31,7 @@ import java.util.Objects;
import java.util.Properties;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.PeCryptoUtils;
public class PapUrlResolver {
@@ -96,12 +96,12 @@ public class PapUrlResolver {
String papUrlFailedList = failedList;
String papUrlSuccessList = succeededList;
if (papUrlLists == null) {
- papUrlLists = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS);
+ papUrlLists = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URLS);
if (papUrlLists == null) {
- papUrlLists = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+ papUrlLists = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
}
- papUrlFailedList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS);
- papUrlSuccessList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS);
+ papUrlFailedList = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS);
+ papUrlSuccessList = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS);
}
String[] urls = papUrlLists.split(",");
@@ -116,12 +116,12 @@ public class PapUrlResolver {
String userId = null;
String pass = null;
- userId = XACMLProperties.getProperty(urls[i] + "." + XACMLRestProperties.PROP_PAP_USERID);
+ userId = XACMLProperties.getProperty(urls[i] + "." + XacmlRestProperties.PROP_PAP_USERID);
pass = XACMLProperties.getProperty(urls[i] + "."
- + PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
+ + PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS)));
if (userId == null || pass == null) {
- userId = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- pass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
+ userId = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID);
+ pass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS));
}
if (userId == null || pass == null) {
userId = "";
@@ -216,9 +216,9 @@ public class PapUrlResolver {
failedPropertyString = failedPropertyString.substring(1);
succeededPropertyString = succeededPropertyString.substring(1);
urlPropertyString = urlPropertyString.substring(1);
- prop.setProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS, failedPropertyString);
- prop.setProperty(XACMLRestProperties.PROP_PAP_URLS, urlPropertyString);
- prop.setProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS, succeededPropertyString);
+ prop.setProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS, failedPropertyString);
+ prop.setProperty(XacmlRestProperties.PROP_PAP_URLS, urlPropertyString);
+ prop.setProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS, succeededPropertyString);
return prop;
}
@@ -229,12 +229,12 @@ public class PapUrlResolver {
}
Properties prop = getProperties();
- LOGGER.debug("Failed PAP Url List: " + prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS));
- LOGGER.debug("Succeeded PAP Url List: " + prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS));
- XACMLProperties.setProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS,
- prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS));
- XACMLProperties.setProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS,
- prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS));
+ LOGGER.debug("Failed PAP Url List: " + prop.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS));
+ LOGGER.debug("Succeeded PAP Url List: " + prop.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS));
+ XACMLProperties.setProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS,
+ prop.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS));
+ XACMLProperties.setProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS,
+ prop.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS));
}
// iterates to the next available PAP url, according to the priority order
@@ -333,7 +333,7 @@ public class PapUrlResolver {
// property)
private Date setHandler(Object time) {
if (time instanceof String) {
- if ("-1".equals((String) time)) {
+ if ("-1".equals(time)) {
return null;
}
try {
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpLoader.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpLoader.java
index 102d43f0c..9fd655194 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpLoader.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpLoader.java
@@ -3,13 +3,14 @@
* ONAP-PDP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -20,6 +21,22 @@
package org.onap.policy.pdp.rest;
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.api.pap.PDPStatus;
+import com.att.research.xacml.api.pap.PDPStatus.Status;
+import com.att.research.xacml.api.pdp.PDPEngine;
+import com.att.research.xacml.api.pdp.PDPEngineFactory;
+import com.att.research.xacml.api.pip.PIPEngine;
+import com.att.research.xacml.api.pip.PIPException;
+import com.att.research.xacml.api.pip.PIPFinder;
+import com.att.research.xacml.api.pip.PIPFinderFactory;
+import com.att.research.xacml.util.FactoryException;
+import com.att.research.xacml.util.XACMLProperties;
+import com.att.research.xacmlatt.pdp.policy.PolicyDef;
+import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef;
+import com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory;
+import com.google.common.base.Splitter;
+
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -39,602 +56,608 @@ import java.util.Properties;
import java.util.Set;
import org.apache.commons.io.IOUtils;
-import org.onap.policy.pdp.rest.notifications.NotificationController;
-import org.onap.policy.rest.XACMLRest;
-import org.onap.policy.rest.XACMLRestProperties;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-
+import org.onap.policy.pdp.rest.notifications.NotificationController;
+import org.onap.policy.rest.XacmlRest;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.xacml.api.XACMLErrorConstants;
-import com.att.research.xacml.api.pap.PAPException;
-import com.att.research.xacml.api.pap.PDPStatus;
-import com.att.research.xacml.api.pap.PDPStatus.Status;
-import com.att.research.xacml.api.pdp.PDPEngine;
-import com.att.research.xacml.api.pdp.PDPEngineFactory;
-import com.att.research.xacml.api.pip.PIPEngine;
-import com.att.research.xacml.api.pip.PIPException;
-import com.att.research.xacml.api.pip.PIPFinder;
-import com.att.research.xacml.api.pip.PIPFinderFactory;
import org.onap.policy.xacml.std.pap.StdPDPPIPConfig;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;
import org.onap.policy.xacml.std.pap.StdPDPStatus;
-import com.att.research.xacml.util.FactoryException;
-import com.att.research.xacml.util.XACMLProperties;
-import com.att.research.xacmlatt.pdp.policy.PolicyDef;
-import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef;
-import com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory;
-import com.google.common.base.Splitter;
/**
- * Does the work for loading policy and PIP configurations sent from the PAP
- * servlet.
- *
- *
- *
+ * Does the work for loading policy and PIP configurations sent from the PAP servlet.
*/
public class XACMLPdpLoader {
- private static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpLoader.class);
- private static NotificationController notificationController = new NotificationController();
- private static final Long notifyDelay = (long) XACMLPdpServlet.getNotificationDelay();
+ private static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpLoader.class);
+
+ // Repeated string constants.
+ private static final String DOES_NOT_EXIST = " does NOT exist.";
+ private static final String CORRUPTED_POLICY_FILE_DELETING = "Corrupted policy file, deleting: ";
+ private static final String DOT_FILE = ".file";
+
+ private static NotificationController notificationController = new NotificationController();
+ private static final Long notifyDelay = (long) XACMLPdpServlet.getNotificationDelay();
+
+ public static synchronized PDPEngine loadEngine(StdPDPStatus status, Properties policyProperties,
+ Properties pipProperties) {
+ LOGGER.info("loadEngine: " + policyProperties + " " + pipProperties);
+ //
+ // First load our policies
+ //
+ try {
+ //
+ // Were we given some properties?
+ //
+ if (policyProperties == null) {
+ //
+ // On init we have no incoming configuration, so just
+ // Load our current saved configuration
+ //
+ policyProperties = new Properties();
+ try (InputStream is = Files.newInputStream(getPDPPolicyCache())) {
+ policyProperties.load(is);
+ }
+ }
+
+ //
+ // Get our policy cache up-to-date
+ //
+ // Side effects of this include:
+ // - downloading of policies from remote locations, and
+ // - creating new "<PolicyId>.file" properties for files existing
+ // local
+ //
+ LOGGER.info("XACMLPdpLoader: cache the policies.");
+ XACMLPdpLoader.cachePolicies(policyProperties);
+ //
+ // Validate the policies
+ //
+ LOGGER.info("XACMLPdpLoader: validating the policies.");
+ XACMLPdpLoader.validatePolicies(policyProperties, status);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Status: " + status);
+ }
+ } catch (ConcurrentModificationException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e.getMessage() + e);
+ } catch (Exception e) {
+ String error = "Failed to load Policy Cache properties file: " + e.getMessage();
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + error, e);
+ status.addLoadError(error);
+ status.setStatus(PDPStatus.Status.LOAD_ERRORS);
+ }
+ //
+ // Load our PIP configuration
+ //
+ try {
+ //
+ // Were we given some properties to use?
+ //
+ if (pipProperties == null) {
+ //
+ // Load our current saved configuration
+ //
+ pipProperties = new Properties();
+ try (InputStream is = Files.newInputStream(getPIPConfig())) {
+ pipProperties.load(is);
+ }
+ }
+ //
+ // Validate our PIP configurations
+ //
+ XACMLPdpLoader.validatePipConfiguration(pipProperties, status);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Status: " + status);
+ }
+ } catch (Exception e) {
+ String error = "Failed to load/validate Pip Config properties file: " + e.getMessage();
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + error, e);
+ status.addLoadError(XACMLErrorConstants.ERROR_PROCESS_FLOW + error);
+ status.setStatus(PDPStatus.Status.LOAD_ERRORS);
+ }
+ //
+ // Were they validated?
+ //
+ if (status.getStatus() == Status.LOAD_ERRORS) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "there were load errors");
+ return null;
+ }
+ //
+ // Reset our official properties the PDP factory
+ // uses to configure the PDP engine.
+ //
+ XacmlRest.loadXacmlProperties(policyProperties, pipProperties);
+ //
+ // Dump ALL our properties that we are trying to load
+ //
+ try {
+ LOGGER.info(XACMLProperties.getProperties().toString());
+ } catch (IOException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to get XACML Properties", e);
+ }
+ //
+ // Now load the PDP engine
+ //
+ PDPEngineFactory factory = null;
+ PDPEngine engine = null;
+ try {
+ factory = PDPEngineFactory.newInstance();
+ engine = factory.newEngine();
+ LOGGER.info("Loaded new PDP engine.");
+ status.setStatus(Status.UP_TO_DATE);
+ } catch (FactoryException e) {
+ String error = "Failed to create new PDP Engine";
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + error, e);
+ status.addLoadError(error);
+ }
+ return engine;
+ }
+ private static HashMap<String, PolicyDef> policyContainer = null;
- public static synchronized PDPEngine loadEngine(StdPDPStatus status,
- Properties policyProperties, Properties pipProperties) {
- LOGGER.info("loadEngine: " + policyProperties + " " + pipProperties);
- //
- // First load our policies
- //
- try {
- //
- // Were we given some properties?
- //
- if (policyProperties == null) {
- //
- // On init we have no incoming configuration, so just
- // Load our current saved configuration
- //
- policyProperties = new Properties();
- try (InputStream is = Files.newInputStream(getPDPPolicyCache())) {
- policyProperties.load(is);
- }
- }
+ /**
+ * Thread for sending notifications.
+ */
+ public static synchronized void sendNotification() {
+ Thread notify = new Thread() {
+ @Override
+ public void run() {
+ try {
+ Thread.sleep(notifyDelay);
+ NotificationController.sendNotification();
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_UNKNOWN + e);
+ }
+ }
+ };
+ notify.start();
+ }
- //
- // Get our policy cache up-to-date
- //
- // Side effects of this include:
- // - downloading of policies from remote locations, and
- // - creating new "<PolicyId>.file" properties for files existing
- // local
- //
- LOGGER.info("XACMLPdpLoader: cache the policies.");
- XACMLPdpLoader.cachePolicies(policyProperties);
- //
- // Validate the policies
- //
- LOGGER.info("XACMLPdpLoader: validating the policies.");
- XACMLPdpLoader.validatePolicies(policyProperties, status);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Status: " + status);
- }
- } catch (ConcurrentModificationException e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e.getMessage() + e);
- } catch (Exception e) {
- String error = "Failed to load Policy Cache properties file: "
- + e.getMessage();
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + error, e);
- status.addLoadError(error);
- status.setStatus(PDPStatus.Status.LOAD_ERRORS);
- }
- //
- // Load our PIP configuration
- //
- try {
- //
- // Were we given some properties to use?
- //
- if (pipProperties == null) {
- //
- // Load our current saved configuration
- //
- pipProperties = new Properties();
- try (InputStream is = Files.newInputStream(getPIPConfig())) {
- pipProperties.load(is);
- }
- }
- //
- // Validate our PIP configurations
- //
- XACMLPdpLoader.validatePipConfiguration(pipProperties, status);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Status: " + status);
- }
- } catch (Exception e) {
- String error = "Failed to load/validate Pip Config properties file: "
- + e.getMessage();
- LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + error, e);
- status.addLoadError(XACMLErrorConstants.ERROR_PROCESS_FLOW + error);
- status.setStatus(PDPStatus.Status.LOAD_ERRORS);
- }
- //
- // Were they validated?
- //
- if (status.getStatus() == Status.LOAD_ERRORS) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"there were load errors");
- return null;
- }
- //
- // Reset our official properties the PDP factory
- // uses to configure the PDP engine.
- //
- XACMLRest.loadXacmlProperties(policyProperties, pipProperties);
- //
- // Dump ALL our properties that we are trying to load
- //
- try {
- LOGGER.info(XACMLProperties.getProperties().toString());
- } catch (IOException e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to get XACML Properties", e);
- }
- //
- // Now load the PDP engine
- //
- PDPEngineFactory factory = null;
- PDPEngine engine = null;
- try {
- factory = PDPEngineFactory.newInstance();
- engine = factory.newEngine();
- LOGGER.info("Loaded new PDP engine.");
- status.setStatus(Status.UP_TO_DATE);
- } catch (FactoryException e) {
- String error = "Failed to create new PDP Engine";
- LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +error, e);
- status.addLoadError(error);
- }
- return engine;
- }
+ /**
+ * Method to validate policies.
+ *
+ * @param properties The properties of the policies
+ * @param status the PDP status
+ * @throws PAPException on validation errors
+ */
+ public static synchronized void validatePolicies(Properties properties, StdPDPStatus status) throws PAPException {
+ Set<String> rootPolicies = XACMLProperties.getRootPolicyIDs(properties);
+ policyContainer = new HashMap<>();
- private static HashMap<String, PolicyDef> policyContainer = null;
-
- public static synchronized void sendNotification(){
- Thread notify = new Thread(){
- public void run(){
- try{
- Thread.sleep(notifyDelay);
- NotificationController.sendNotification();
- }catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_UNKNOWN + e);
- }
- }
- };
- notify.start();
- }
-
- public static synchronized void validatePolicies(Properties properties,
- StdPDPStatus status) throws PAPException {
- Set<String> rootPolicies = XACMLProperties.getRootPolicyIDs(properties);
- Set<String> refPolicies = XACMLProperties
- .getReferencedPolicyIDs(properties);
- policyContainer = new HashMap<String, PolicyDef>();
+ LOGGER.info("XACMLPdpLoader: load rootPolicies");
+ for (String id : rootPolicies) {
+ loadPolicy(properties, status, id, true);
+ }
+ // remember which policies were root policies
+ status.addAllLoadedRootPolicies(status.getLoadedPolicies());
+ LOGGER.info("XACMLPdpLoader: load referencedPolicies");
+ Set<String> refPolicies = XACMLProperties.getReferencedPolicyIDs(properties);
+ for (String id : refPolicies) {
+ loadPolicy(properties, status, id, false);
+ }
+ LOGGER.info("Loaded " + status.getLoadedPolicies().size() + " policies, failed to load "
+ + status.getFailedPolicies().size() + " policies, " + status.getLoadedRootPolicies().size()
+ + " root policies");
+ notificationController.check(status, policyContainer);
+ if (status.getLoadedRootPolicies().isEmpty()) {
+ LOGGER.warn(
+ XACMLErrorConstants.ERROR_PROCESS_FLOW + "NO ROOT POLICIES LOADED!!! Cannot serve PEP Requests.");
+ status.addLoadWarning("NO ROOT POLICIES LOADED!!! Cannot serve PEP Requests.");
+ }
+ policyContainer.clear();
+ }
- LOGGER.info("XACMLPdpLoader: load rootPolicies");
- for (String id : rootPolicies) {
- loadPolicy(properties, status, id, true);
- }
- // remember which policies were root policies
- status.addAllLoadedRootPolicies(status.getLoadedPolicies());
- LOGGER.info("XACMLPdpLoader: load referencedPolicies");
- for (String id : refPolicies) {
- loadPolicy(properties, status, id, false);
- }
- LOGGER.info("Loaded " + status.getLoadedPolicies().size()
- + " policies, failed to load "
- + status.getFailedPolicies().size() + " policies, "
- + status.getLoadedRootPolicies().size() + " root policies");
- notificationController.check(status, policyContainer);
- if (status.getLoadedRootPolicies().size() == 0) {
- LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW +"NO ROOT POLICIES LOADED!!! Cannot serve PEP Requests.");
- status.addLoadWarning("NO ROOT POLICIES LOADED!!! Cannot serve PEP Requests.");
- }
- policyContainer.clear();
- }
+ /**
+ * Load a policy.
+ *
+ * @param properties the policy properties
+ * @param status the PDP status
+ * @param id the policy ID
+ * @param isRoot indicates if operation being done as root
+ * @throws PAPException on loading errors
+ */
+ public static synchronized void loadPolicy(Properties properties, StdPDPStatus status, String id, boolean isRoot)
+ throws PAPException {
+ PolicyDef policy = null;
+ String location = null;
+ URI locationUri = null;
+ boolean isFile = false;
+ boolean rougeFile = false;
+ try {
+ location = properties.getProperty(id + DOT_FILE);
+ if (location != null) {
+ isFile = true;
+ locationUri = Paths.get(location).toUri();
+ try (InputStream is = Files.newInputStream(Paths.get(location))) {
+ policy = DOMPolicyDef.load(is);
+ } catch (Exception e) {
+ // This Happens if a any issue with the error policyFile. Lets remove it.
+ try {
+ LOGGER.error(CORRUPTED_POLICY_FILE_DELETING + location + e);
+ Files.delete(Paths.get(location));
+ properties.remove(id + DOT_FILE);
+ rougeFile = true;
+ } catch (IOException e1) {
+ LOGGER.error(e1);
+ }
+ }
+ }
+ if (location == null || rougeFile) {
+ if (rougeFile) {
+ rougeFile = false;
+ }
+ location = properties.getProperty(id + ".url");
+ if (location != null) {
+ //
+ // Construct the URL
+ //
+ int errorCount = 0;
+ boolean error = false;
+ do {
+ error = false;
+ PapUrlResolver papUrls = PapUrlResolver.getInstance();
+ while (papUrls.hasMoreUrls()) {
+ String papID = papUrls.getUserId();
+ String papPass = papUrls.getPass();
+ Base64.Encoder encoder = Base64.getEncoder();
+ locationUri = URI.create(papUrls.getUrl(PapUrlResolver.extractIdFromUrl(location)));
+ URL url = locationUri.toURL();
+ URLConnection urlConnection = null;
+ try {
+ urlConnection = url.openConnection();
+ } catch (IOException e) {
+ LOGGER.error("Exception Occured while opening connection" + e);
+ papUrls.failed();
+ papUrls.getNext();
+ break;
+ }
+ String encoding =
+ encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
+ urlConnection.setRequestProperty(XacmlRestProperties.PROP_PDP_HTTP_HEADER_ID,
+ XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_ID));
+ urlConnection.setRequestProperty("Authorization", "Basic " + encoding);
+ //
+ // Now construct the output file name
+ //
+ Path outFile = Paths.get(getPDPConfig().toAbsolutePath().toString(), id);
+ //
+ // Copy it to disk
+ //
+ try (FileOutputStream fos = new FileOutputStream(outFile.toFile())) {
+ IOUtils.copy(urlConnection.getInputStream(), fos);
+ } catch (IOException e) {
+ LOGGER.error("Exception Occured while Copying input stream" + e);
+ papUrls.failed();
+ papUrls.getNext();
+ break;
+ }
+ //
+ // Now try to load
+ //
+ isFile = true;
+ try (InputStream fis = Files.newInputStream(outFile)) {
+ policy = DOMPolicyDef.load(fis);
+ } catch (Exception e) {
+ try {
+ LOGGER.error(CORRUPTED_POLICY_FILE_DELETING + location + e);
+ Files.delete(outFile);
+ error = true;
+ errorCount++;
+ break;
+ } catch (IOException e1) {
+ LOGGER.error(e1);
+ }
+ }
+ //
+ // Save it
+ //
+ properties.setProperty(id + DOT_FILE, outFile.toAbsolutePath().toString());
+ error = false;
+ break;
+ }
+ }
+ while (error && errorCount > 2);
+ }
+ }
+ if (policy != null) {
+ status.addLoadedPolicy(new StdPDPPolicy(id, isRoot, locationUri, properties));
+ LOGGER.info(
+ "Loaded policy: " + policy.getIdentifier() + " version: " + policy.getVersion().stringValue());
+ // Sending the policy objects to the Notification Controller.
+ policyContainer.put(id, policy);
+ } else {
+ String error = "Failed to load policy " + location;
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + error);
+ status.setStatus(PDPStatus.Status.LOAD_ERRORS);
+ status.addLoadError(error);
+ status.addFailedPolicy(new StdPDPPolicy(id, isRoot));
+ }
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to load policy '" + id + "' from location '"
+ + location + "'", e);
+ status.setStatus(PDPStatus.Status.LOAD_ERRORS);
+ status.addFailedPolicy(new StdPDPPolicy(id, isRoot));
+ //
+ // Is it a file?
+ //
+ if (isFile) {
+ //
+ // Let's remove it
+ //
+ try {
+ LOGGER.error(
+ XACMLErrorConstants.ERROR_PROCESS_FLOW + CORRUPTED_POLICY_FILE_DELETING + location);
+ Files.delete(Paths.get(location));
-
- public static synchronized void loadPolicy(Properties properties,
- StdPDPStatus status, String id, boolean isRoot) throws PAPException {
- PolicyDef policy = null;
- String location = null;
- URI locationURI = null;
- boolean isFile = false;
- boolean rougeFile = false;
- try {
- location = properties.getProperty(id + ".file");
- if(location != null){
- isFile = true;
- locationURI = Paths.get(location).toUri();
- try (InputStream is = Files.newInputStream(Paths.get(location))) {
- policy = DOMPolicyDef.load(is);
- } catch (Exception e){
- // This Happens if a any issue with the error policyFile. Lets remove it.
- try {
- LOGGER.error("Corrupted policy file, deleting: " + location + e);
- Files.delete(Paths.get(location));
- properties.remove(id + ".file");
- rougeFile = true;
- } catch (IOException e1) {
- LOGGER.error(e1);
- }
- }
- }
- if(location==null || rougeFile){
- if(rougeFile){
- rougeFile = false;
- }
- location = properties.getProperty(id + ".url");
- if (location != null) {
- //
- // Construct the URL
- //
- int errorCount=0;
- boolean error= false;
- do{
- error=false;
- PapUrlResolver papUrls = PapUrlResolver.getInstance();
- while(papUrls.hasMoreUrls()){
- String papID = papUrls.getUserId();
- String papPass = papUrls.getPass();
- Base64.Encoder encoder = Base64.getEncoder();
- String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
- locationURI = URI.create(papUrls.getUrl(PapUrlResolver.extractIdFromUrl(location)));
- URL url = locationURI.toURL();
- URLConnection urlConnection = null;
- try{
- urlConnection = url.openConnection();
- } catch (IOException e){
- LOGGER.error("Exception Occured while opening connection" +e);
- papUrls.failed();
- papUrls.getNext();
- break;
- }
- urlConnection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID,
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID));
- urlConnection.setRequestProperty("Authorization", "Basic " + encoding);
- //
- // Now construct the output file name
- //
- Path outFile = Paths.get(getPDPConfig().toAbsolutePath()
- .toString(), id);
- //
- // Copy it to disk
- //
- try (FileOutputStream fos = new FileOutputStream(
- outFile.toFile())) {
- IOUtils.copy(urlConnection.getInputStream(), fos);
- } catch(IOException e){
- LOGGER.error("Exception Occured while Copying input stream" +e);
- papUrls.failed();
- papUrls.getNext();
- break;
- }
- //
- // Now try to load
- //
- isFile = true;
- try (InputStream fis = Files.newInputStream(outFile)) {
- policy = DOMPolicyDef.load(fis);
- }catch(Exception e){
- try {
- LOGGER.error("Corrupted policy file, deleting: " + location +e);
- Files.delete(outFile);
- error = true;
- errorCount++;
- break;
- } catch (IOException e1) {
- LOGGER.error(e1);
- }
- }
- //
- // Save it
- //
- properties.setProperty(id + ".file", outFile
- .toAbsolutePath().toString());
- error = false;
- break;
- }
- }while(error && errorCount>2);
- }
- }
- if (policy != null) {
- status.addLoadedPolicy(new StdPDPPolicy(id, isRoot,
- locationURI, properties));
- LOGGER.info("Loaded policy: " + policy.getIdentifier()
- + " version: " + policy.getVersion().stringValue());
- // Sending the policy objects to the Notification Controller.
- policyContainer.put(id, policy);
- } else {
- String error = "Failed to load policy " + location;
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + error);
- status.setStatus(PDPStatus.Status.LOAD_ERRORS);
- status.addLoadError(error);
- status.addFailedPolicy(new StdPDPPolicy(id, isRoot));
- }
- } catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"Failed to load policy '" + id + "' from location '"
- + location + "'", e);
- status.setStatus(PDPStatus.Status.LOAD_ERRORS);
- status.addFailedPolicy(new StdPDPPolicy(id, isRoot));
- //
- // Is it a file?
- //
- if (isFile) {
- //
- // Let's remove it
- //
- try {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Corrupted policy file, deleting: " + location);
- Files.delete(Paths.get(location));
-
- } catch (IOException e1) {
- LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e1);
- }
- }
- }
- }
+ } catch (IOException e1) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e1);
+ }
+ }
+ }
+ }
- public static synchronized void validatePipConfiguration(
- Properties properties, StdPDPStatus status) throws PAPException {
- try {
- PIPFinderFactory factory = PIPFinderFactory.newInstance(properties);
- if (factory == null) {
- throw new FactoryException(
- "Could not create PIP Finder Factory: "
- + properties
- .getProperty(XACMLProperties.PROP_PIPFINDERFACTORY));
- }
- PIPFinder finder = factory.getFinder(properties);
- //
- // Check for this, although it should always return something
- //
- if (finder == null) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "pip finder factory returned a null engine.");
- throw new PIPException("Could not create PIP Finder");
- } else {
- LOGGER.info("Loaded PIP finder");
- }
- for (PIPEngine engine : finder.getPIPEngines()) {
- LOGGER.info("Configured PIP Engine: " + engine.getName());
- StdPDPPIPConfig config = new StdPDPPIPConfig();
- config.setName(engine.getName());
- status.addLoadedPipConfig(config);
- }
- } catch (FactoryException | PIPException e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "validate PIP configuration failed: "
- + e.getLocalizedMessage());
- status.addLoadError(e.getLocalizedMessage());
- status.setStatus(Status.LOAD_ERRORS);
- throw new PAPException(e);
- }
- }
+ /**
+ * Validate PIP configuration.
+ *
+ * @param properties the properties to validate
+ * @param status the PDP status
+ * @throws PAPException on validation exceptions
+ */
+ public static synchronized void validatePipConfiguration(Properties properties, StdPDPStatus status)
+ throws PAPException {
+ try {
+ PIPFinderFactory factory = PIPFinderFactory.newInstance(properties);
+ if (factory == null) {
+ throw new FactoryException("Could not create PIP Finder Factory: "
+ + properties.getProperty(XACMLProperties.PROP_PIPFINDERFACTORY));
+ }
+ PIPFinder finder = factory.getFinder(properties);
+ //
+ // Check for this, although it should always return something
+ //
+ if (finder == null) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "pip finder factory returned a null engine.");
+ throw new PIPException("Could not create PIP Finder");
+ } else {
+ LOGGER.info("Loaded PIP finder");
+ }
+ for (PIPEngine engine : finder.getPIPEngines()) {
+ LOGGER.info("Configured PIP Engine: " + engine.getName());
+ StdPDPPIPConfig config = new StdPDPPIPConfig();
+ config.setName(engine.getName());
+ status.addLoadedPipConfig(config);
+ }
+ } catch (FactoryException | PIPException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "validate PIP configuration failed: "
+ + e.getLocalizedMessage());
+ status.addLoadError(e.getLocalizedMessage());
+ status.setStatus(Status.LOAD_ERRORS);
+ throw new PAPException(e);
+ }
+ }
- /**
- * Iterates the policies defined in the props object to ensure they are
- * loaded locally. Policies are searched for in the following order: - see
- * if the current properties has a "&lt;PolicyID&gt;.file" entry and that
- * file exists in the local directory - if not, see if the file exists in
- * the local directory; if so create a ".file" property for it. - if not,
- * get the "&lt;PolicyID&gt;.url" property and try to GET the policy from
- * that location (and set the ".file" property)
- *
- * If the ".file" property is created, then true is returned to tell the
- * caller that the props object changed.
- *
- * @param props
- * @return true/false if anything was changed in the props object
- * @throws PAPException
- */
- public static synchronized boolean cachePolicies(Properties props)
- throws PAPException {
- boolean changed = false;
- String[] lists = new String[2];
- lists[0] = props.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
- lists[1] = props.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
- for (String list : lists) {
- //
- // Check for a null or empty parameter
- //
- if (list == null || list.length() == 0) {
- continue;
- }
- Iterable<String> policies = Splitter.on(',').trimResults()
- .omitEmptyStrings().split(list);
- for (String policy : policies) {
- boolean policyExists = false;
+ /**
+ * Iterates the policies defined in the props object to ensure they are loaded locally. Policies are searched for in
+ * the following order: - see if the current properties has a "&lt;PolicyID&gt;.file" entry and that file exists in
+ * the local directory - if not, see if the file exists in the local directory; if so create a ".file" property for
+ * it. - if not, get the "&lt;PolicyID&gt;.url" property and try to GET the policy from that location (and set the
+ * ".file" property)
+ *
+ * <p>If the ".file" property is created, then true is returned to tell the caller that the props object changed.
+ *
+ * @param props the properties to cache
+ * @return true/false if anything was changed in the props object
+ * @throws PAPException on cacheing exceptions
+ */
+ public static synchronized boolean cachePolicies(Properties props) throws PAPException {
+ boolean changed = false;
+ String[] lists = new String[2];
+ lists[0] = props.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
+ lists[1] = props.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
+ for (String list : lists) {
+ //
+ // Check for a null or empty parameter
+ //
+ if (list == null || list.length() == 0) {
+ continue;
+ }
+ Iterable<String> policies = Splitter.on(',').trimResults().omitEmptyStrings().split(list);
+ for (String policy : policies) {
+ boolean policyExists = false;
- // First look for ".file" property and verify the file exists
- String propLocation = props.getProperty(policy
- + StdPolicyFinderFactory.PROP_FILE);
- if (propLocation != null) {
- //
- // Does it exist?
- //
- policyExists = Files.exists(Paths.get(propLocation));
- if (policyExists == false) {
- LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy file " + policy + " expected at "
- + propLocation + " does NOT exist.");
- }
- }
+ // First look for ".file" property and verify the file exists
+ String propLocation = props.getProperty(policy + StdPolicyFinderFactory.PROP_FILE);
+ if (propLocation != null) {
+ //
+ // Does it exist?
+ //
+ policyExists = Paths.get(propLocation).toFile().exists();
+ if (!policyExists) {
+ LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy file " + policy + " expected at "
+ + propLocation + DOES_NOT_EXIST);
+ }
+ }
- // If ".file" property does not exist, try looking for the local
- // file anyway
- // (it might exist without having a ".file" property set for it)
- if (policyExists == false) {
- //
- // Now construct the output file name
- //
- Path outFile = Paths.get(getPDPConfig().toAbsolutePath()
- .toString(), policy);
- //
- // Double check to see if we pulled it at some point
- //
- policyExists = Files.exists(outFile);
- if (policyExists) {
- //
- // Set the property so the PDP engine doesn't have
- // to pull it from the URL but rather the FILE.
- //
- LOGGER.info("Policy does exist: "
- + outFile.toAbsolutePath().toString());
- props.setProperty(policy
- + StdPolicyFinderFactory.PROP_FILE, outFile
- .toAbsolutePath().toString());
- //
- // Indicate that there were changes made to the
- // properties
- //
- changed = true;
- } else {
+ // If ".file" property does not exist, try looking for the local
+ // file anyway
+ // (it might exist without having a ".file" property set for it)
+ if (!policyExists) {
+ //
+ // Now construct the output file name
+ //
+ Path outFile = Paths.get(getPDPConfig().toAbsolutePath().toString(), policy);
+ //
+ // Double check to see if we pulled it at some point
+ //
+ policyExists = outFile.toFile().exists();
+ if (policyExists) {
+ //
+ // Set the property so the PDP engine doesn't have
+ // to pull it from the URL but rather the FILE.
+ //
+ LOGGER.info("Policy does exist: " + outFile.toAbsolutePath().toString());
+ props.setProperty(policy + StdPolicyFinderFactory.PROP_FILE,
+ outFile.toAbsolutePath().toString());
+ //
+ // Indicate that there were changes made to the
+ // properties
+ //
+ changed = true;
+ } else {
- // File does not exist locally, so we need to get it
- // from the location given in the ".url" property (which
- // MUST exist)
+ // File does not exist locally, so we need to get it
+ // from the location given in the ".url" property (which
+ // MUST exist)
- //
- // There better be a URL to retrieve it
- //
- propLocation = props.getProperty(policy
- + StdPolicyFinderFactory.PROP_URL);
- if (propLocation != null) {
- //
- // Get it
- //
- PapUrlResolver papUrls = PapUrlResolver.getInstance();
- while(papUrls.hasMoreUrls()){
- String papID = papUrls.getUserId();
- String papPass = papUrls.getPass();
- Base64.Encoder encoder = Base64.getEncoder();
- String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
- URL url = null;
- try {
- //
- // Create the URL
- //
- url = new URL(papUrls.getUrl(PapUrlResolver.extractIdFromUrl(propLocation)));
- LOGGER.info("Pulling " + url.toString());
- //
- // Open the connection
- //
- URLConnection urlConnection = url.openConnection();
- urlConnection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID,
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID));
- urlConnection.setRequestProperty("Authorization", "Basic " + encoding);
- //
- // Copy it to disk
- //
- try (InputStream is = urlConnection
- .getInputStream();
- OutputStream os = new FileOutputStream(
- outFile.toFile())) {
- IOUtils.copy(is, os);
- }
- //
- // Now save it in the properties as a .file
- //
- LOGGER.info("Pulled policy: "
- + outFile.toAbsolutePath().toString());
- props.setProperty(policy
- + StdPolicyFinderFactory.PROP_FILE,
- outFile.toAbsolutePath().toString());
- papUrls.succeeded();
- //
- // Indicate that there were changes made to the
- // properties
- //
- changed = true;
- } catch (MalformedURLException e) {
- papUrls.failed();
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy '" + policy
- + "' had bad URL in new configuration, URL='" + propLocation + "'");
- } catch (Exception e) {
- papUrls.failed();
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while retrieving policy "
- + policy + " from URL " + url + ", e=" + e);
- }
- papUrls.getNext();
- }
- } else {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy " + policy
- + " does NOT exist and does NOT have a URL");
- }
- }
- }
- }
- }
- return changed;
- }
+ //
+ // There better be a URL to retrieve it
+ //
+ propLocation = props.getProperty(policy + StdPolicyFinderFactory.PROP_URL);
+ if (propLocation != null) {
+ //
+ // Get it
+ //
+ PapUrlResolver papUrls = PapUrlResolver.getInstance();
+ while (papUrls.hasMoreUrls()) {
+ String papID = papUrls.getUserId();
+ String papPass = papUrls.getPass();
+ Base64.Encoder encoder = Base64.getEncoder();
+ String encoding = encoder
+ .encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
+ URL url = null;
+ try {
+ //
+ // Create the URL
+ //
+ url = new URL(papUrls.getUrl(PapUrlResolver.extractIdFromUrl(propLocation)));
+ LOGGER.info("Pulling " + url.toString());
+ //
+ // Open the connection
+ //
+ URLConnection urlConnection = url.openConnection();
+ urlConnection.setRequestProperty(XacmlRestProperties.PROP_PDP_HTTP_HEADER_ID,
+ XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_ID));
+ urlConnection.setRequestProperty("Authorization", "Basic " + encoding);
+ //
+ // Copy it to disk
+ //
+ try (InputStream is = urlConnection.getInputStream();
+ OutputStream os = new FileOutputStream(outFile.toFile())) {
+ IOUtils.copy(is, os);
+ }
+ //
+ // Now save it in the properties as a .file
+ //
+ LOGGER.info("Pulled policy: " + outFile.toAbsolutePath().toString());
+ props.setProperty(policy + StdPolicyFinderFactory.PROP_FILE,
+ outFile.toAbsolutePath().toString());
+ papUrls.succeeded();
+ //
+ // Indicate that there were changes made to the
+ // properties
+ //
+ changed = true;
+ } catch (MalformedURLException e) {
+ papUrls.failed();
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy '" + policy
+ + "' had bad URL in new configuration, URL='" + propLocation + "'");
+ } catch (Exception e) {
+ papUrls.failed();
+ LOGGER.error(
+ XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while retrieving policy "
+ + policy + " from URL " + url + ", e=" + e);
+ }
+ papUrls.getNext();
+ }
+ } else {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy " + policy
+ + " does NOT exist and does NOT have a URL");
+ }
+ }
+ }
+ }
+ }
+ return changed;
+ }
- public static synchronized Path getPDPPolicyCache() throws PAPException {
- Path config = getPDPConfig();
- Path policyProperties = Paths.get(config.toAbsolutePath().toString(),
- "xacml.policy.properties");
- if (Files.notExists(policyProperties)) {
- LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + policyProperties.toAbsolutePath().toString()
- + " does NOT exist.");
- //
- // Try to create the file
- //
- try {
- Files.createFile(policyProperties);
- } catch (IOException e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create policy properties file: "
- + policyProperties.toAbsolutePath().toString() +e);
- throw new PAPException(
- "Failed to create policy properties file: "
- + policyProperties.toAbsolutePath().toString());
- }
- }
- return policyProperties;
- }
+ /**
+ * Get the PDP policy cache.
+ *
+ * @return the PDP policy cache
+ * @throws PAPException on cache get errors
+ */
+ public static synchronized Path getPDPPolicyCache() throws PAPException {
+ Path config = getPDPConfig();
+ Path policyProperties = Paths.get(config.toAbsolutePath().toString(), "xacml.policy.properties");
+ if (!policyProperties.toFile().exists()) {
+ LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + policyProperties.toAbsolutePath().toString()
+ + DOES_NOT_EXIST);
+ //
+ // Try to create the file
+ //
+ try {
+ Files.createFile(policyProperties);
+ } catch (IOException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create policy properties file: "
+ + policyProperties.toAbsolutePath().toString() + e);
+ throw new PAPException(
+ "Failed to create policy properties file: " + policyProperties.toAbsolutePath().toString());
+ }
+ }
+ return policyProperties;
+ }
- public static synchronized Path getPIPConfig() throws PAPException {
- Path config = getPDPConfig();
- Path pipConfigProperties = Paths.get(
- config.toAbsolutePath().toString(), "xacml.pip.properties");
- if (Files.notExists(pipConfigProperties)) {
- LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + pipConfigProperties.toAbsolutePath().toString()
- + " does NOT exist.");
- //
- // Try to create the file
- //
- try {
- Files.createFile(pipConfigProperties);
- } catch (IOException e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create pip properties file: "
- + pipConfigProperties.toAbsolutePath().toString() +e);
- throw new PAPException("Failed to create pip properties file: "
- + pipConfigProperties.toAbsolutePath().toString());
- }
- }
- return pipConfigProperties;
- }
+ /**
+ * Get the PIP configuration.
+ *
+ * @return the PIP configuration
+ * @throws PAPException on get exceptions
+ */
+ public static synchronized Path getPIPConfig() throws PAPException {
+ Path config = getPDPConfig();
+ Path pipConfigProperties = Paths.get(config.toAbsolutePath().toString(), "xacml.pip.properties");
+ if (!pipConfigProperties.toFile().exists()) {
+ LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + pipConfigProperties.toAbsolutePath().toString()
+ + DOES_NOT_EXIST);
+ //
+ // Try to create the file
+ //
+ try {
+ Files.createFile(pipConfigProperties);
+ } catch (IOException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create pip properties file: "
+ + pipConfigProperties.toAbsolutePath().toString() + e);
+ throw new PAPException(
+ "Failed to create pip properties file: " + pipConfigProperties.toAbsolutePath().toString());
+ }
+ }
+ return pipConfigProperties;
+ }
- public static synchronized Path getPDPConfig() throws PAPException {
- Path config = Paths.get(XACMLProperties
- .getProperty(XACMLRestProperties.PROP_PDP_CONFIG));
- if (Files.notExists(config)) {
- LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + config.toAbsolutePath().toString() + " does NOT exist.");
- //
- // Try to create the directory
- //
- try {
- Files.createDirectories(config);
- } catch (IOException e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: "
- + config.toAbsolutePath().toString(), e);
- throw new PAPException("Failed to create config directory: "
- + config.toAbsolutePath().toString());
- }
- }
- return config;
- }
+ /**
+ * Get the PDP configuration.
+ *
+ * @return the PDP configuration
+ * @throws PAPException on get exceptions
+ */
+ public static synchronized Path getPDPConfig() throws PAPException {
+ Path config = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_CONFIG));
+ if (!config.toFile().exists()) {
+ LOGGER.warn(
+ XACMLErrorConstants.ERROR_PROCESS_FLOW + config.toAbsolutePath().toString() + DOES_NOT_EXIST);
+ //
+ // Try to create the directory
+ //
+ try {
+ Files.createDirectories(config);
+ } catch (IOException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: "
+ + config.toAbsolutePath().toString(), e);
+ throw new PAPException("Failed to create config directory: " + config.toAbsolutePath().toString());
+ }
+ }
+ return config;
+ }
}
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java
index b33c4bd16..56d82bd3f 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* 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.
@@ -37,25 +37,25 @@ import java.util.UUID;
import org.apache.commons.io.IOUtils;
import org.onap.policy.pdp.rest.XACMLPdpServlet.PutRequest;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import com.att.research.xacml.util.XACMLProperties;
-import org.onap.policy.common.logging.ONAPLoggingContext;
+import org.onap.policy.common.logging.OnapLoggingContext;
import org.onap.policy.common.logging.eelf.PolicyLogger;
-import org.onap.policy.common.logging.flexlogger.*;
+import org.onap.policy.common.logging.flexlogger.*;
public class XACMLPdpRegisterThread implements Runnable {
private static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpRegisterThread.class);
private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
- private ONAPLoggingContext baseLoggingContext = null;
+ private OnapLoggingContext baseLoggingContext = null;
public volatile boolean isRunning = false;
- public XACMLPdpRegisterThread(ONAPLoggingContext baseLoggingContext) {
+ public XACMLPdpRegisterThread(OnapLoggingContext baseLoggingContext) {
this.baseLoggingContext = baseLoggingContext;
}
@@ -78,7 +78,7 @@ public class XACMLPdpRegisterThread implements Runnable {
this.isRunning = true;
}
// get a new logging context for the thread
- ONAPLoggingContext loggingContext = new ONAPLoggingContext(baseLoggingContext);
+ OnapLoggingContext loggingContext = new OnapLoggingContext(baseLoggingContext);
loggingContext.setServiceName("PDP:PAP.register");
//are we registered with at least one
boolean registered = false;
@@ -86,7 +86,7 @@ public class XACMLPdpRegisterThread implements Runnable {
/*
int seconds;
try {
- seconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_SLEEP));
+ seconds = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_REGISTER_SLEEP));
} catch (NumberFormatException e) {
LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR +"REGISTER_SLEEP: ", e);
seconds = 5;
@@ -96,7 +96,7 @@ public class XACMLPdpRegisterThread implements Runnable {
}
int retries;
try {
- retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_RETRIES));
+ retries = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_REGISTER_RETRIES));
} catch (NumberFormatException e) {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +" REGISTER_SLEEP: ", e);
retries = -1;
@@ -124,13 +124,13 @@ public class XACMLPdpRegisterThread implements Runnable {
// each time through the inner loop (which handles redirects) is a
// continuation of the same transaction.
UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
+ loggingContext.setRequestId(requestID.toString());
//PolicyLogger.info("Request Id generated in XACMLPdpRegisterThread under XACML-PDP-REST");
loggingContext.transactionStarted();
//
// Get the list of PAP Servlet URLs from the property file
//
- //String papUrlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+ //String papUrlList = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
//String[] papUrls = papUrlList.split(",");
//PapUrlResolver.setPapUrls(papUrls);
URL url = new URL(papUrls.getUrl());
@@ -149,8 +149,8 @@ public class XACMLPdpRegisterThread implements Runnable {
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.setRequestProperty("Accept", "text/x-java-properties");
connection.setRequestProperty("Content-Type", "text/x-java-properties");
- connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID));
- connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_JMX_PORT));
+ connection.setRequestProperty(XacmlRestProperties.PROP_PDP_HTTP_HEADER_ID, XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_ID));
+ connection.setRequestProperty(XacmlRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT, XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_JMX_PORT));
connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
connection.setUseCaches(false);
//
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java
index c86e21c09..cae73ce29 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java
@@ -20,17 +20,6 @@
package org.onap.policy.pdp.rest;
-import com.att.research.xacml.api.Request;
-import com.att.research.xacml.api.Response;
-import com.att.research.xacml.api.pap.PDPStatus.Status;
-import com.att.research.xacml.api.pdp.PDPEngine;
-import com.att.research.xacml.api.pdp.PDPException;
-import com.att.research.xacml.std.dom.DOMRequest;
-import com.att.research.xacml.std.dom.DOMResponse;
-import com.att.research.xacml.std.json.JSONRequest;
-import com.att.research.xacml.std.json.JSONResponse;
-import com.att.research.xacml.util.XACMLProperties;
-import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -64,17 +53,28 @@ import org.onap.policy.common.im.IntegrityMonitor;
import org.onap.policy.common.im.IntegrityMonitorException;
import org.onap.policy.common.im.IntegrityMonitorProperties;
import org.onap.policy.common.im.StandbyStatusException;
-import org.onap.policy.common.logging.ONAPLoggingContext;
-import org.onap.policy.common.logging.ONAPLoggingUtils;
+import org.onap.policy.common.logging.OnapLoggingContext;
+import org.onap.policy.common.logging.OnapLoggingUtils;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.pdp.rest.jmx.PdpRestMonitor;
-import org.onap.policy.rest.XACMLRest;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRest;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.pdp.std.functions.PolicyList;
import org.onap.policy.xacml.std.pap.StdPDPStatus;
+import com.att.research.xacml.api.Request;
+import com.att.research.xacml.api.Response;
+import com.att.research.xacml.api.pap.PDPStatus.Status;
+import com.att.research.xacml.api.pdp.PDPEngine;
+import com.att.research.xacml.api.pdp.PDPException;
+import com.att.research.xacml.std.dom.DOMRequest;
+import com.att.research.xacml.std.dom.DOMResponse;
+import com.att.research.xacml.std.json.JSONRequest;
+import com.att.research.xacml.std.json.JSONResponse;
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Servlet implementation class XacmlPdpServlet
@@ -177,7 +177,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
//
private static transient Thread configThread = null;
private static volatile boolean configThreadTerminate = false;
- private transient ONAPLoggingContext baseLoggingContext = null;
+ private transient OnapLoggingContext baseLoggingContext = null;
private transient IntegrityMonitor im;
public IntegrityMonitor getIm() {
@@ -205,7 +205,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
//
// Initialize
//
- XACMLRest.xacmlInit(config);
+ XacmlRest.xacmlInit(config);
// Load the Notification Delay.
setNotificationDelay();
// Load Queue size. Not sure if we really need to have the queue bounded, we should look further into this
@@ -226,7 +226,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
//
// Logging stuff....
//
- baseLoggingContext = new ONAPLoggingContext();
+ baseLoggingContext = new OnapLoggingContext();
// fixed data that will be the same in all logging output goes here
try {
String hostname = InetAddress.getLocalHost().getCanonicalHostName();
@@ -243,7 +243,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
"Error loading properties with: XACMLProperties.getProperties()");
throw new ServletException(e.getMessage(), e.getCause());
}
- if (properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME) == null) {
+ if (properties.getProperty(XacmlRestProperties.PDP_RESOURCE_NAME) == null) {
XACMLProperties.reloadProperties();
try {
properties = XACMLProperties.getProperties();
@@ -269,7 +269,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE);
setCreateUpdatePolicyConstructor(createUpdateResourceName);
- PeCryptoUtils.initAesKey(properties.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ PeCryptoUtils.initAesKey(properties.getProperty(XacmlRestProperties.PROP_AES_KEY));
// Create an IntegrityMonitor
try {
@@ -281,7 +281,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor" + e);
throw new ServletException(e);
}
-
+
try {
System.setProperty("msToscaModel.home", properties.getProperty("msToscaModel.home"));
} catch (Exception e) {
@@ -291,12 +291,12 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
startThreads(baseLoggingContext, new Thread(this));
}
- private static void startThreads(ONAPLoggingContext baseLoggingContext, Thread thread) {
+ private static void startThreads(OnapLoggingContext baseLoggingContext, Thread thread) {
environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
//
// Kick off our thread to register with the PAP servlet.
//
- if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER))) {
+ if (Boolean.parseBoolean(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_REGISTER))) {
XACMLPdpServlet.registerRunnable = new XACMLPdpRegisterThread(baseLoggingContext);
XACMLPdpServlet.registerThread = new Thread(XACMLPdpServlet.registerRunnable);
XACMLPdpServlet.registerThread.start();
@@ -321,9 +321,9 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
}
private static void setPDPResourceName(Properties properties) throws ServletException {
- pdpResourceName = properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME);
+ pdpResourceName = properties.getProperty(XacmlRestProperties.PDP_RESOURCE_NAME);
if (pdpResourceName == null) {
- PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XACMLRestProperties.PDP_RESOURCE_NAME, "xacml.pdp");
+ PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XacmlRestProperties.PDP_RESOURCE_NAME, "xacml.pdp");
throw new ServletException("pdpResourceName is null");
}
}
@@ -335,7 +335,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
private static void setNotificationDelay() {
try {
XACMLPdpServlet.notificationDelay =
- Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY));
+ Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_DELAY));
} catch (NumberFormatException e) {
logger.error("Error in notification delay format, Taking the default value.", e);
}
@@ -426,11 +426,11 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
- ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
loggingContext.transactionStarted();
- if ((loggingContext.getRequestID() == null) || "".equals(loggingContext.getRequestID())) {
+ if ((loggingContext.getRequestId() == null) || "".equals(loggingContext.getRequestId())) {
UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
+ loggingContext.setRequestId(requestID.toString());
PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPut) so we generated one");
} else {
PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPut)");
@@ -445,7 +445,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
// Dump our request out
//
if (logger.isDebugEnabled()) {
- XACMLRest.dumpRequest(request);
+ XacmlRest.dumpRequest(request);
}
try {
@@ -509,7 +509,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
}
protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response,
- ONAPLoggingContext loggingContext) throws IOException {
+ OnapLoggingContext loggingContext) throws IOException {
try {
// prevent multiple configuration changes from stacking up
logger.info("XACMLPdpServlet: checking remainingCapacity of Queue.");
@@ -642,11 +642,11 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
- ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
loggingContext.transactionStarted();
- if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")) {
+ if ((loggingContext.getRequestId() == null) || (loggingContext.getRequestId() == "")) {
UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
+ loggingContext.setRequestId(requestID.toString());
PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doGet) so we generated one");
} else {
PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doGet)");
@@ -658,7 +658,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
loggingContext.metricEnded();
PolicyLogger.metrics("Metric example posted here - 2 of 2");
- XACMLRest.dumpRequest(request);
+ XacmlRest.dumpRequest(request);
String pathInfo = request.getRequestURI();
if (pathInfo != null && "/pdp/test".equals(pathInfo)) {
@@ -805,7 +805,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
}
if (returnHB) {
synchronized (pdpStatusLock) {
- response.addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString());
+ response.addHeader(XacmlRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString());
}
}
loggingContext.transactionEnded();
@@ -825,12 +825,12 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
- ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
+ OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext);
loggingContext.transactionStarted();
loggingContext.setServiceName("PDP.decide");
- if ((loggingContext.getRequestID() == null) || ("".equals(loggingContext.getRequestID()))) {
+ if ((loggingContext.getRequestId() == null) || ("".equals(loggingContext.getRequestId()))) {
UUID requestID = UUID.randomUUID();
- loggingContext.setRequestID(requestID.toString());
+ loggingContext.setRequestId(requestID.toString());
PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPost) so we generated one");
} else {
PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPost)");
@@ -876,7 +876,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
return;
}
- XACMLRest.dumpRequest(request);
+ XacmlRest.dumpRequest(request);
//
// Set our no-cache header
//
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java
index 44cc76478..1f0700f81 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java
@@ -158,7 +158,7 @@ public class GetDictionaryService {
case "VNFType":
jsonString = jsonString.replace("vnfTypeDictionaryDatas", "DictionaryDatas");
break;
- case "PEPOptions":
+ case "PepOptions":
jsonString = jsonString.replace("pepOptionsDictionaryDatas", "DictionaryDatas");
break;
case "Varbind":
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java
index d61b7c006..1d9e3e13f 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java
@@ -7,9 +7,9 @@
* 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.
@@ -39,7 +39,7 @@ import java.util.stream.Stream;
import org.onap.policy.api.PolicyException;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.BusPublisher;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.springframework.http.HttpStatus;
@@ -99,7 +99,7 @@ public class NotificationService {
private static void init() {
if (dmaapServers == null || aafLogin == null || aafPassword == null) {
- dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS);
+ dmaapServers = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_SERVERS);
aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN");
aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD");
interval =
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java
index 822599f13..516d873d4 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java
@@ -41,7 +41,7 @@ import org.onap.policy.api.PolicyException;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pdp.rest.restauth.AuthenticationService;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;
@@ -67,9 +67,9 @@ public class PAPServices {
environment = AuthenticationService.getEnvironment();
if (paps == null) {
synchronized (papResourceLock) {
- String urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS);
+ String urlList = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URLS);
if (urlList == null) {
- urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+ urlList = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
}
paps = Arrays.asList(urlList.split(","));
}
@@ -78,8 +78,8 @@ public class PAPServices {
private String getPAPEncoding() {
if (encoding == null) {
- String userID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- String pass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
+ String userID = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID);
+ String pass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS));
Base64.Encoder encoder = Base64.getEncoder();
encoding = encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8));
}
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java
index e61bbd3aa..9a5fc5ef2 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java
@@ -8,9 +8,9 @@
* 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.
@@ -70,7 +70,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pdp.rest.XACMLPdpServlet;
import org.onap.policy.pdp.rest.api.models.PDPResponse;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.std.Matches;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.w3c.dom.Document;
@@ -207,7 +207,7 @@ public class PDPServices {
if (uri == 1) {
configUrl = attribute.getAttributeValue().getValue().toString();
pdpConfigLocation = configUrl.replace("$URL",
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS));
+ XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_WEBAPPS));
} else {
if (!("PDP".equalsIgnoreCase(attribute.getIssuer()))) {
throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
@@ -350,7 +350,7 @@ public class PDPServices {
/**
* Process Decision Result.
- *
+ *
* @param result input from Response.
* @return pdpResposne based on result.
*/
@@ -388,7 +388,7 @@ public class PDPServices {
/**
* Check for Decision for decision based calls.
- *
+ *
* @param pdpResponseInput pdpResponse.
* @param result result.
* @return pdpResponse.
@@ -420,7 +420,7 @@ public class PDPServices {
/**
* Check if there is a configuration.
- *
+ *
* @param advice advice.
* @param configRetrieved boolean.
* @param pdpResponse pdpResposneInput.
@@ -431,7 +431,7 @@ public class PDPServices {
if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) {
String configUrl = attribute.getAttributeValue().getValue().toString();
String pdpConfigLocation =
- configUrl.replace("$URL", XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS));
+ configUrl.replace("$URL", XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_WEBAPPS));
// If there is a configuration.
try {
LOGGER.debug("processDecisionResult: Configuration Call to : " + configUrl);
@@ -615,7 +615,7 @@ public class PDPServices {
/**
* Returns the requestFormat.
- *
+ *
* @return the requestFormat.
*/
public String getRequestFormat() {
@@ -624,7 +624,7 @@ public class PDPServices {
/**
* Set the Request Format.
- *
+ *
* @param requestMode to set requestFormat.
*/
public void setRequestFormat(String requestMode) {
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java
index 9027e27a5..9c75e1e38 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java
@@ -7,9 +7,9 @@
* 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.
@@ -31,7 +31,7 @@ import java.util.UUID;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.BusConsumer;
import org.onap.policy.utils.BusPublisher;
import org.onap.policy.xacml.api.XACMLErrorConstants;
@@ -67,9 +67,9 @@ public class ManualNotificationUpdateThread implements Runnable {
}
/**
- *
+ *
* This is our thread that runs on startup if the system is configured to UEB to accept manual update requests
- *
+ *
*/
@Override
public void run() {
@@ -85,7 +85,7 @@ public class ManualNotificationUpdateThread implements Runnable {
if ("ueb".equals(propNotificationType)) {
try {
setCluster();
- String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID);
+ String url = XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_ID);
aURL = new URL(url);
topic = aURL.getHost() + aURL.getPort();
} catch (NumberFormatException e) {
@@ -129,8 +129,8 @@ public class ManualNotificationUpdateThread implements Runnable {
} else if ("dmaap".equals(propNotificationType)) {
String dmaapServers = null;
try {
- dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS);
- topic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC);
+ dmaapServers = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_SERVERS);
+ topic = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_TOPIC);
setAAFCreds();
} catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get DMaaP servers list:", e);
@@ -145,7 +145,7 @@ public class ManualNotificationUpdateThread implements Runnable {
dmaapServers = dmaapServers.trim();
topic = topic.trim();
- String consumerTopic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC).trim();
+ String consumerTopic = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_TOPIC).trim();
sendMessage(consumerTopic, "Starting-Topic");
dmaapList = new ArrayList<>();
for (String u : dmaapServers.split(",")) {
@@ -189,14 +189,14 @@ public class ManualNotificationUpdateThread implements Runnable {
}
private static void setCluster() {
- clusterList = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS);
+ clusterList = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_SERVERS);
if (clusterList != null) {
clusterList = clusterList.trim();
}
}
private static void setPropNotification() {
- propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE);
+ propNotificationType = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_TYPE);
}
private void sendMessage(String topic, String message) {
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java
index c62872fbd..974ca5c01 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java
@@ -7,9 +7,9 @@
* 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.
@@ -44,7 +44,7 @@ import org.onap.policy.api.UpdateType;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pdp.rest.PapUrlResolver;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import com.att.research.xacml.api.pap.PDPPolicy;
@@ -61,7 +61,7 @@ import com.fasterxml.jackson.databind.ObjectWriter;
/**
* NotificationController Checks for the Updated and Removed policies. It notifies the Server to send Notifications to
* the Client.
- *
+ *
* @version 0.2
*
*/
@@ -81,7 +81,7 @@ public class NotificationController {
private static Boolean notificationFlag = false;
public void check(PDPStatus newStatus, Map<String, PolicyDef> policyContainer) {
-
+
LOGGER.info("NotificationController: checking for updated and removed policies.");
boolean isUpdated = false;
boolean isRemoved = false;
@@ -101,7 +101,7 @@ public class NotificationController {
LOGGER.info("There is an Update to the PDP");
LOGGER.debug(oldStatus.getLoadedPolicies());
LOGGER.debug(newStatus.getLoadedPolicies());
-
+
// Check if there is an Update/additions in the policy.
LOGGER.info("NotificationController: check for updated or new policies");
for (PDPPolicy newPolicy : newStatus.getLoadedPolicies()) {
@@ -191,8 +191,8 @@ public class NotificationController {
}
private static void setPropNotification() {
- propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE);
- pdpURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID);
+ propNotificationType = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_TYPE);
+ pdpURL = XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_ID);
}
public static void sendNotification() {
@@ -382,7 +382,7 @@ public class NotificationController {
private void removeFile(PDPPolicy oldPolicy) {
try {
- Path removedPolicyFile = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_CONFIG)
+ Path removedPolicyFile = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_CONFIG)
+ File.separator + oldPolicy.getId());
Files.deleteIfExists(removedPolicyFile);
boolean delete = false;
@@ -390,11 +390,11 @@ public class NotificationController {
if (oldPolicy.getName().contains(".Config_")) {
delete = true;
dir = new File(
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS) + File.separator + "Config");
+ XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_WEBAPPS) + File.separator + "Config");
} else if (oldPolicy.getName().contains(".Action_")) {
delete = true;
dir = new File(
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS) + File.separator + "Action");
+ XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_WEBAPPS) + File.separator + "Action");
}
if (delete) {
FileFilter fileFilter = new WildcardFileFilter(
@@ -412,7 +412,7 @@ public class NotificationController {
private void callPap(String urlString, String type) {
Path configLocation = Paths
- .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS) + File.separator + type);
+ .get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_WEBAPPS) + File.separator + type);
if (Files.notExists(configLocation)) {
try {
Files.createDirectories(configLocation);
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java
index 4c2d1ef57..5c1162a7d 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java
@@ -3,13 +3,14 @@
* ONAP-PDP-REST
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
@@ -20,6 +21,10 @@
package org.onap.policy.pdp.rest.notifications;
+import com.att.nsa.cambria.client.CambriaBatchingPublisher;
+import com.att.nsa.cambria.client.CambriaClientBuilders;
+import com.att.research.xacml.util.XACMLProperties;
+
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
@@ -44,184 +49,204 @@ import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pdp.rest.api.services.NotificationService;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.BusPublisher;
import org.onap.policy.xacml.api.XACMLErrorConstants;
-import com.att.nsa.cambria.client.CambriaBatchingPublisher;
-import com.att.nsa.cambria.client.CambriaClientBuilders;
-import com.att.research.xacml.util.XACMLProperties;
-
/**
- * The NotificationServer sends the Server Notifications to the Clients once there is any Event.
- * WebSockets is being used as a medium for sending Notifications.
- * UEB is being used as a medium for sending Notifications.
- * DMAAP is being used as a medium for sending Notifications.
- *
+ * The NotificationServer sends the Server Notifications to the Clients once there is any Event. WebSockets is being
+ * used as a medium for sending Notifications. UEB is being used as a medium for sending Notifications. DMAAP is being
+ * used as a medium for sending Notifications.
+ *
* @version 0.2
*
**/
@ServerEndpoint(value = "/notifications")
public class NotificationServer {
- private static final Logger LOGGER = FlexLogger.getLogger(NotificationServer.class);
- private static Queue<Session> queue = new ConcurrentLinkedQueue<>();
- 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_PROCESS_FLOW + "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);
- session.close();
- } catch (IOException e) {
- LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage() + e);
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending Message update");
- }
- }
- }
-
- public static void sendNotification(String notification, String propNotificationType, String pdpURL) throws PolicyEngineException, IOException, InterruptedException {
-
- LOGGER.debug("Notification set to " + propNotificationType);
- if (propNotificationType.equals("ueb")){
-
- String topic = null;
- try {
- URL aURL = new URL(pdpURL);
- topic = aURL.getHost() + aURL.getPort();
- } catch (MalformedURLException e1) {
- pdpURL = pdpURL.replace("/", "");
- topic = pdpURL.replace(":", "");
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in parsing out pdpURL for UEB notfication ");
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e1, "Error in parsing out pdpURL for UEB notfication ");
- }
- String hosts = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS);
- String apiKey = XACMLProperties.getProperty(XACMLRestProperties.PROP_UEB_API_KEY);
- String apiSecret = XACMLProperties.getProperty(XACMLRestProperties.PROP_UEB_API_SECRET);
-
- LOGGER.debug("Creating Publisher for host: " + hosts + " with topic: " + topic);
- CambriaBatchingPublisher pub = null;
- try {
- if(hosts==null || topic==null || apiKey==null || apiSecret==null){
- LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
- throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
- }
-
- hosts = hosts.trim();
- topic = topic.trim();
- apiKey = apiKey.trim();
- apiSecret = apiSecret.trim();
- pub = new CambriaClientBuilders.PublisherBuilder ()
- .usingHosts ( hosts )
- .onTopic ( topic )
- .authenticatedBy ( apiKey, apiSecret )
- .build ()
- ;
-
- } catch (MalformedURLException e1) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error creating the UEB publisher" + e1.getMessage());
- } catch (GeneralSecurityException e1) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error creating the UEB publisher" + e1.getMessage() +e1);
- }
- if(pub != null){
- try {
- pub.send( "MyPartitionKey", notification );
- } catch (IOException e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update" + e.getMessage() + e);
- }
- // close the publisher. The batching publisher does not send events
- // immediately, so you MUST use close to send any remaining messages.
- // You provide the amount of time you're willing to wait for the sends
- // to succeed before giving up. If any messages are unsent after that time,
- // they're returned to your app. You could, for example, persist to disk
- // and try again later.
- final List<?> stuck = pub.close ( 20, TimeUnit.SECONDS );
-
- if (!stuck.isEmpty()){
- LOGGER.error( stuck.size() + " messages unsent" );
- }else{
- LOGGER.info( "Clean exit; all messages sent: " + notification );
- }
- }
- } else if (propNotificationType.equals("dmaap")) {
-
- // Setting up the Publisher for DMaaP MR
- String dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS);
- String topic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC);
- String aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN");
- String aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD");
-
- try {
- if(dmaapServers==null || topic==null){
- LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
- throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
- }
-
- dmaapServers= dmaapServers.trim();
- topic= topic.trim();
- aafLogin= aafLogin.trim();
- aafPassword= aafPassword.trim();
-
- List<String> dmaapList = null;
- if(dmaapServers.contains(",")) {
- dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*")));
- } else {
- dmaapList = new ArrayList<>();
- dmaapList.add(dmaapServers);
- }
-
- BusPublisher publisher =
- new BusPublisher.DmaapPublisherWrapper(dmaapList,
- topic,
- aafLogin,
- aafPassword);
-
- // Sending notification through DMaaP Message Router
- publisher.send( "MyPartitionKey", notification);
- LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + topic);
- publisher.close();
-
- } catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update" + e.getMessage() + e);
- }
- }
-
- for(Session session: queue) {
- try {
- LOGGER.info("\n Sending Notification: " + notification + " for client session id: " + session.getId() + "\n "
- + "PDPUrl is " + pdpURL);
- LOGGER.info("NotificationServer: sending text message");
- session.getBasicRemote().sendText(notification);
- } catch (IOException e) {
- LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage() + e);
- }
- }
-
- NotificationService.sendNotification(notification);
- }
-
- public static void setUpdate(String update) {
- NotificationServer.update = update;
- }
-
+ private static final Logger LOGGER = FlexLogger.getLogger(NotificationServer.class);
+ private static Queue<Session> queue = new ConcurrentLinkedQueue<>();
+ 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);
+ }
+
+ /**
+ * Error callback method.
+ * @param session The session on which the error occurs
+ * @param throwable exception thrown on the error callback
+ */
+ @OnError
+ public void error(Session session, Throwable throwable) {
+ queue.remove(session);
+ LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Session Error for : " + session.getId() + " Error: "
+ + throwable.getMessage());
+ }
+
+ /**
+ * Message callback method.
+ * @param message the message on the callback
+ * @param session The session on which the error occurs
+ */
+ @OnMessage
+ public void message(String message, Session session) {
+
+ if (message.equalsIgnoreCase("Manual")) {
+ try {
+ session.getBasicRemote().sendText(update);
+ session.close();
+ } catch (IOException e) {
+ LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "
+ + e.getMessage() + e);
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending Message update");
+ }
+ }
+ }
+
+ /**
+ * Send a notification.
+ * @param notification The notification type
+ * @param propNotificationType Notification type properties
+ * @param pdpUrl URL of the PDP
+ * @throws PolicyEngineException on errors from the policy engine
+ * @throws IOException exceptions on IO errors
+ * @throws InterruptedException interrupts
+ */
+ public static void sendNotification(String notification, String propNotificationType, String pdpUrl)
+ throws PolicyEngineException, IOException, InterruptedException {
+
+ LOGGER.debug("Notification set to " + propNotificationType);
+ if (propNotificationType.equals("ueb")) {
+
+ String topic = null;
+ try {
+ URL notificationUrl = new URL(pdpUrl);
+ topic = notificationUrl.getHost() + notificationUrl.getPort();
+ } catch (MalformedURLException e1) {
+ pdpUrl = pdpUrl.replace("/", "");
+ topic = pdpUrl.replace(":", "");
+ LOGGER.error(
+ XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in parsing out pdpURL for UEB notfication ");
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e1,
+ "Error in parsing out pdpURL for UEB notfication ");
+ }
+ String hosts = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_SERVERS);
+ String apiKey = XACMLProperties.getProperty(XacmlRestProperties.PROP_UEB_API_KEY);
+ String apiSecret = XACMLProperties.getProperty(XacmlRestProperties.PROP_UEB_API_SECRET);
+
+ LOGGER.debug("Creating Publisher for host: " + hosts + " with topic: " + topic);
+ CambriaBatchingPublisher pub = null;
+ try {
+ if (hosts == null || topic == null || apiKey == null || apiSecret == null) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "UEB properties are missing from the property file ");
+ throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "UEB properties are missing from the property file ");
+ }
+
+ hosts = hosts.trim();
+ topic = topic.trim();
+ apiKey = apiKey.trim();
+ apiSecret = apiSecret.trim();
+ pub = new CambriaClientBuilders.PublisherBuilder().usingHosts(hosts).onTopic(topic)
+ .authenticatedBy(apiKey, apiSecret).build();
+
+ } catch (MalformedURLException e1) {
+ LOGGER.error(
+ XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error creating the UEB publisher" + e1.getMessage());
+ } catch (GeneralSecurityException e1) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error creating the UEB publisher"
+ + e1.getMessage() + e1);
+ }
+ if (pub != null) {
+ try {
+ pub.send("MyPartitionKey", notification);
+ } catch (IOException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update"
+ + e.getMessage() + e);
+ }
+ // close the publisher. The batching publisher does not send events
+ // immediately, so you MUST use close to send any remaining messages.
+ // You provide the amount of time you're willing to wait for the sends
+ // to succeed before giving up. If any messages are unsent after that time,
+ // they're returned to your app. You could, for example, persist to disk
+ // and try again later.
+ final List<?> stuck = pub.close(20, TimeUnit.SECONDS);
+
+ if (!stuck.isEmpty()) {
+ LOGGER.error(stuck.size() + " messages unsent");
+ } else {
+ LOGGER.info("Clean exit; all messages sent: " + notification);
+ }
+ }
+ } else if (propNotificationType.equals("dmaap")) {
+
+ // Setting up the Publisher for DMaaP MR
+ String dmaapServers = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_SERVERS);
+ String topic = XACMLProperties.getProperty(XacmlRestProperties.PROP_NOTIFICATION_TOPIC);
+ String aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN");
+ String aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD");
+
+ try {
+ if (dmaapServers == null || topic == null) {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "DMaaP properties are missing from the property file ");
+ throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "DMaaP properties are missing from the property file ");
+ }
+
+ dmaapServers = dmaapServers.trim();
+ topic = topic.trim();
+ aafLogin = aafLogin.trim();
+ aafPassword = aafPassword.trim();
+
+ List<String> dmaapList = null;
+ if (dmaapServers.contains(",")) {
+ dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*")));
+ } else {
+ dmaapList = new ArrayList<>();
+ dmaapList.add(dmaapServers);
+ }
+
+ BusPublisher publisher =
+ new BusPublisher.DmaapPublisherWrapper(dmaapList, topic, aafLogin, aafPassword);
+
+ // Sending notification through DMaaP Message Router
+ publisher.send("MyPartitionKey", notification);
+ LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + topic);
+ publisher.close();
+
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update"
+ + e.getMessage() + e);
+ }
+ }
+
+ for (Session session : queue) {
+ try {
+ LOGGER.info("\n Sending Notification: " + notification + " for client session id: " + session.getId()
+ + "\n " + "PDPUrl is " + pdpUrl);
+ LOGGER.info("NotificationServer: sending text message");
+ session.getBasicRemote().sendText(notification);
+ } catch (IOException e) {
+ LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "
+ + e.getMessage() + e);
+ }
+ }
+
+ NotificationService.sendNotification(notification);
+ }
+
+ public static void setUpdate(String update) {
+ NotificationServer.update = update;
+ }
+
}
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/AuthenticationService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/AuthenticationService.java
index 87a46aa23..54a5151c4 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/AuthenticationService.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restauth/AuthenticationService.java
@@ -42,7 +42,7 @@ import org.onap.policy.api.PolicyEngineException;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.AAFPolicyClient;
import org.onap.policy.utils.AAFPolicyException;
import org.onap.policy.utils.PeCryptoUtils;
@@ -66,7 +66,7 @@ public class AuthenticationService {
*/
private static void setProperty() {
environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
- String clientFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PEP_IDFILE);
+ String clientFile = XACMLProperties.getProperty(XacmlRestProperties.PROP_PEP_IDFILE);
if (clientFile != null) {
clientPath = Paths.get(clientFile);
}
diff --git a/ONAP-PDP-REST/src/main/resources/logback.xml b/ONAP-PDP-REST/src/main/resources/logback.xml
index 23f870d37..ef1e38dac 100644
--- a/ONAP-PDP-REST/src/main/resources/logback.xml
+++ b/ONAP-PDP-REST/src/main/resources/logback.xml
@@ -2,14 +2,14 @@
============LICENSE_START=======================================================
ONAP-PDP-REST
================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 2017-2019 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.
@@ -22,73 +22,73 @@
<!--<jmxConfigurator /> -->
<!-- directory path for all other type logs -->
<property name="logDir" value="${POLICY_LOGS}" />
-
+
<!-- directory path for debugging type logs -->
<property name="debugDir" value="${POLICY_LOGS}" />
-
- <!-- specify the component name
+
+ <!-- specify the component name
<ONAP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" -->
<property name="componentName" value="policy"></property>
<property name="subComponentName" value="pdpx"></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" />
+
+ <!-- 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{Severity}|%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{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" />
+
+
+
+ <!-- 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{Severity}|%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="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{Severity}|%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{Severity}|%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="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{Severity}|%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{Severity}|%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{yyyy-MM-dd'T'HH:mm:ss.SSSXXX, 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="${logDir}/${componentName}/${subComponentName}" />
<property name="debugLogDirectory" value="${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>
@@ -100,28 +100,28 @@
<!-- EELF Appenders -->
<!-- ============================================================================ -->
- <!-- The EELFAppender is used to record events to the general application
+ <!-- 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
+
+ <!-- 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.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${auditLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
-
+
<encoder>
<pattern>${defaultAuditPattern}</pattern>
</encoder>
@@ -141,18 +141,18 @@
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${metricsLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
-
+
<encoder>
<pattern>${defaultMetricPattern}</pattern>
</encoder>
</appender>
-
+
<appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
<appender-ref ref="EELFMetrics"/>
@@ -160,15 +160,15 @@
-
+
<appender name="EELFError"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${errorLogName}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logDirectory}/${errorLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
@@ -180,22 +180,22 @@
<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.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${debugLogDirectory}/${debugLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
-
- <!-- keep 30 days' worth of history capped at 3GB total size -->
+
+ <!-- keep 30 days' worth of history capped at 3GB total size -->
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
@@ -203,41 +203,41 @@
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
-
+
<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" />
diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java
index cf3ddb3b2..841fad641 100644
--- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java
+++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -28,7 +28,7 @@ import java.util.Date;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
public class PapUrlResolverTest {
@@ -41,7 +41,7 @@ public class PapUrlResolverTest {
String failed = "-1,-1,-1,-1";
String succeeded = "-1,-1,-1,-1";
PapUrlResolver rs = PapUrlResolver.getInstance(urls, failed, succeeded);
- Assert.assertEquals(rs.getProperties().getProperty(XACMLRestProperties.PROP_PAP_URLS),
+ Assert.assertEquals(rs.getProperties().getProperty(XacmlRestProperties.PROP_PAP_URLS),
urls);
rs.failed();
@@ -51,14 +51,17 @@ public class PapUrlResolverTest {
Assert.assertFalse(rs.hasMoreUrls());
Properties prop = rs.getProperties();
Assert.assertEquals(df.format(new Date()) + ",-1,-1,-1",
- prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS));
+ prop.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS));
Assert.assertEquals("-1," + df.format(new Date()) + ",-1,-1",
- prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS));
+ prop.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS));
- failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS);
- succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS);
+ failed = prop.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS);
+ succeeded = prop.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS);
rs = PapUrlResolver.getInstance(urls, failed, succeeded);
Assert.assertTrue(rs.hasMoreUrls());
+ Assert.assertEquals("http://one.localhost.com", rs.getUrl());
+ rs.getNext();
+ Assert.assertTrue(rs.hasMoreUrls());
Assert.assertEquals("http://two.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
@@ -66,18 +69,15 @@ public class PapUrlResolverTest {
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
Assert.assertEquals("http://four.localhost.com", rs.getUrl());
- rs.getNext();
- Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://one.localhost.com", rs.getUrl());
rs.succeeded();
rs.getNext();
Assert.assertFalse(rs.hasMoreUrls());
prop = rs.getProperties();
Assert.assertEquals("-1,-1,-1,-1",
- prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS));
+ prop.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS));
- failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS);
- succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS);
+ failed = prop.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS);
+ succeeded = prop.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS);
rs = PapUrlResolver.getInstance(urls, failed, succeeded);
Assert.assertTrue(rs.hasMoreUrls());
Assert.assertEquals("http://one.localhost.com", rs.getUrl());
@@ -85,8 +85,8 @@ public class PapUrlResolverTest {
rs.getNext();
Assert.assertFalse(rs.hasMoreUrls());
prop = rs.getProperties();
- failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS);
- succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS);
+ failed = prop.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS);
+ succeeded = prop.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS);
rs = PapUrlResolver.getInstance(urls, failed, succeeded);
Assert.assertTrue(rs.hasMoreUrls());
Assert.assertEquals("http://one.localhost.com", rs.getUrl());
@@ -94,8 +94,8 @@ public class PapUrlResolverTest {
rs.getNext();
Assert.assertFalse(rs.hasMoreUrls());
prop = rs.getProperties();
- failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS);
- succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS);
+ failed = prop.getProperty(XacmlRestProperties.PROP_PAP_FAILED_URLS);
+ succeeded = prop.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS);
rs = PapUrlResolver.getInstance(urls, failed, succeeded);
Assert.assertTrue(rs.hasMoreUrls());
Assert.assertEquals("http://one.localhost.com", rs.getUrl());
@@ -104,7 +104,7 @@ public class PapUrlResolverTest {
Assert.assertFalse(rs.hasMoreUrls());
prop = rs.getProperties();
- succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS);
+ succeeded = prop.getProperty(XacmlRestProperties.PROP_PAP_SUCCEEDED_URLS);
}
@SuppressWarnings("unused")
@@ -128,13 +128,13 @@ public class PapUrlResolverTest {
String succeeded = "-1,8/13/15 5:41 PM,8/13/15 4:41 PM,-1";
PapUrlResolver rs = PapUrlResolver.getInstance(urls, failed, succeeded);
Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://two.localhost.com", rs.getUrl());
+ Assert.assertEquals("http://one.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://three.localhost.com", rs.getUrl());
+ Assert.assertEquals("http://two.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://one.localhost.com", rs.getUrl());
+ Assert.assertEquals("http://three.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
Assert.assertEquals("http://four.localhost.com", rs.getUrl());
@@ -186,13 +186,13 @@ public class PapUrlResolverTest {
succeeded = "-1,-1,-1,-1";
rs = PapUrlResolver.getInstance(urls, failed, succeeded);
Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://two.localhost.com", rs.getUrl());
+ Assert.assertEquals("http://one.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://three.localhost.com", rs.getUrl());
+ Assert.assertEquals("http://two.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://one.localhost.com", rs.getUrl());
+ Assert.assertEquals("http://three.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
Assert.assertEquals("http://four.localhost.com", rs.getUrl());
@@ -204,6 +204,9 @@ public class PapUrlResolverTest {
succeeded = "-1,-1,-1,-1";
rs = PapUrlResolver.getInstance(urls, failed, succeeded);
Assert.assertTrue(rs.hasMoreUrls());
+ Assert.assertEquals("http://one.localhost.com", rs.getUrl());
+ rs.getNext();
+ Assert.assertTrue(rs.hasMoreUrls());
Assert.assertEquals("http://two.localhost.com", rs.getUrl());
rs.getNext();
Assert.assertTrue(rs.hasMoreUrls());
@@ -212,9 +215,6 @@ public class PapUrlResolverTest {
Assert.assertTrue(rs.hasMoreUrls());
Assert.assertEquals("http://four.localhost.com", rs.getUrl());
rs.getNext();
- Assert.assertTrue(rs.hasMoreUrls());
- Assert.assertEquals("http://one.localhost.com", rs.getUrl());
- rs.getNext();
Assert.assertFalse(rs.hasMoreUrls());
urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com";
diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java
index 14c231aed..eb6910ca7 100644
--- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java
+++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Modifications Copyright (C) 2019 Samsung
* ================================================================================
@@ -41,12 +41,13 @@ import org.mockito.Mockito;
import org.onap.policy.common.ia.IntegrityAuditProperties;
import org.onap.policy.common.im.IntegrityMonitor;
import org.onap.policy.common.im.IntegrityMonitorException;
-import org.onap.policy.common.logging.ONAPLoggingContext;
+import org.onap.policy.common.logging.OnapLoggingContext;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;
import org.onap.policy.xacml.std.pap.StdPDPStatus;
import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -56,6 +57,7 @@ import com.mockrunner.mock.web.MockServletInputStream;
import junit.framework.TestCase;
@RunWith(PowerMockRunner.class)
+@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "org.w3c.dom.*"})
@PrepareForTest({IntegrityMonitor.class})
public class XACMLPdpServletTest extends TestCase {
private static Logger LOGGER = FlexLogger.getLogger(XACMLPdpServletTest.class);
@@ -223,7 +225,7 @@ public class XACMLPdpServletTest extends TestCase {
public void testXACMLPdpRegisterThread() {
LOGGER.info("XACMLPdpServletTest - testXACMLPdpRegisterThread");
try {
- ONAPLoggingContext baseLoggingContext = new ONAPLoggingContext();
+ OnapLoggingContext baseLoggingContext = new OnapLoggingContext();
baseLoggingContext.setServer("localhost");
XACMLPdpRegisterThread regThread = new XACMLPdpRegisterThread(baseLoggingContext);
regThread.run();
diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/GetDictionaryServiceTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/GetDictionaryServiceTest.java
index 4544b6b1c..1904b4bf0 100644
--- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/GetDictionaryServiceTest.java
+++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/GetDictionaryServiceTest.java
@@ -76,7 +76,7 @@ public class GetDictionaryServiceTest {
result = (String) formatDictionary.invoke(gds, input);
assertNotNull(result);
//
- dp.setDictionary("PEPOptions");
+ dp.setDictionary("PepOptions");
gds = new GetDictionaryService(dp, null);
result = (String) formatDictionary.invoke(gds, input);
assertNotNull(result);
diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java
index d1da554d9..d09059978 100644
--- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java
+++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java
@@ -28,7 +28,6 @@ import static org.junit.Assert.assertTrue;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
-import org.json.JSONObject;
import org.junit.Test;
import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils;
diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/AuthenticationServiceTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/AuthenticationServiceTest.java
index 0795526fc..4f03221b7 100644
--- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/AuthenticationServiceTest.java
+++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/AuthenticationServiceTest.java
@@ -24,11 +24,15 @@ package org.onap.policy.pdp.rest.auth.test;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
+
+import com.att.research.xacml.util.XACMLProperties;
+
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import javax.servlet.ServletRequest;
import org.junit.Test;
import org.onap.policy.pdp.rest.restauth.AuthenticationService;
+import org.onap.policy.rest.XacmlRestProperties;
public class AuthenticationServiceTest {
private final String testCred = "python:test";
@@ -40,10 +44,13 @@ public class AuthenticationServiceTest {
String systemKey = "xacml.properties";
// Set the system property temporarily
- String oldProperty = System.getProperty(systemKey);
+ final String oldProperty = System.getProperty(systemKey);
System.setProperty(systemKey, "xacml.pdp.properties");
- ServletRequest request = mock(ServletRequest.class);
+ XACMLProperties.setProperty("enable_aaf", "false");
+ XACMLProperties.setProperty(XacmlRestProperties.PROP_PEP_IDFILE, "client.properties");
+ ServletRequest request = mock(ServletRequest.class);
+ AuthenticationService.getEnvironment();
assertTrue(AuthenticationService.checkPermissions(null, basicCred, "getConfig", "DEVL", request));
// Restore the original system property
diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java
index 261226527..190f93aa7 100644
--- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java
+++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java
@@ -23,8 +23,6 @@ package org.onap.policy.pdp.rest.notifications.test;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.onap.policy.api.NotificationType;
diff --git a/ONAP-PDP-REST/src/test/resources/META-INF/drop.ddl b/ONAP-PDP-REST/src/test/resources/META-INF/drop.ddl
index 062169345..d28a00dde 100644
--- a/ONAP-PDP-REST/src/test/resources/META-INF/drop.ddl
+++ b/ONAP-PDP-REST/src/test/resources/META-INF/drop.ddl
@@ -20,7 +20,7 @@
DROP TABLE IF EXISTS ConfigurationDataEntity
DROP TABLE IF EXISTS PolicyEntity
-DROP TABLE IF EXISTS PolicyDBDaoEntity
+DROP TABLE IF EXISTS PolicyDbDaoEntity
DROP TABLE IF EXISTS ActionBodyEntity
DROP SEQUENCE IF EXISTS seqPolicy
DROP SEQUENCE IF EXISTS seqConfig
diff --git a/ONAP-PDP-REST/src/test/resources/META-INF/persistence.xml b/ONAP-PDP-REST/src/test/resources/META-INF/persistence.xml
index b44841c9d..01ea8dc2e 100644
--- a/ONAP-PDP-REST/src/test/resources/META-INF/persistence.xml
+++ b/ONAP-PDP-REST/src/test/resources/META-INF/persistence.xml
@@ -22,7 +22,7 @@
<persistence-unit name="XACML-PAP-REST">
<class>org.onap.policy.rest.jpa.PolicyEntity</class>
<class>org.onap.policy.rest.jpa.ConfigurationDataEntity</class>
- <class>org.onap.policy.rest.jpa.PolicyDBDaoEntity</class>
+ <class>org.onap.policy.rest.jpa.PolicyDbDaoEntity</class>
<class>org.onap.policy.rest.jpa.GroupEntity</class>
<class>org.onap.policy.rest.jpa.PdpEntity</class>
<class>org.onap.policy.rest.jpa.ActionBodyEntity</class>
@@ -40,7 +40,7 @@
<class>org.onap.policy.rest.jpa.ActionPolicyDict</class>
<class>org.onap.policy.rest.jpa.DecisionSettings</class>
<class>org.onap.policy.rest.jpa.MicroServiceModels</class>
- <class>org.onap.policy.rest.jpa.BRMSParamTemplate</class>
+ <class>org.onap.policy.rest.jpa.BrmsParamTemplate</class>
<class>org.onap.policy.rest.jpa.PolicyEditorScopes</class>
<!-- unique to PolicyEngineUtils - will be audited from PAP -->
<class>org.onap.policy.jpa.BackUpMonitorEntity</class>
@@ -109,7 +109,7 @@
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.onap.policy.rest.jpa.PolicyEntity</class>
<class>org.onap.policy.rest.jpa.ConfigurationDataEntity</class>
- <class>org.onap.policy.rest.jpa.PolicyDBDaoEntity</class>
+ <class>org.onap.policy.rest.jpa.PolicyDbDaoEntity</class>
<class>org.onap.policy.rest.jpa.GroupEntity</class>
<class>org.onap.policy.rest.jpa.PdpEntity</class>
<class>org.onap.policy.rest.jpa.ActionBodyEntity</class>
@@ -131,11 +131,11 @@
<class>org.onap.policy.rest.jpa.ActionList</class>
<class>org.onap.policy.rest.jpa.AddressGroup</class>
<class>org.onap.policy.rest.jpa.AttributeAssignment</class>
- <class>org.onap.policy.rest.jpa.BRMSParamTemplate</class>
+ <class>org.onap.policy.rest.jpa.BrmsParamTemplate</class>
<class>org.onap.policy.rest.jpa.ClosedLoopD2Services</class>
<class>org.onap.policy.rest.jpa.ClosedLoopSite</class>
- <class>org.onap.policy.rest.jpa.DCAEUsers</class>
- <class>org.onap.policy.rest.jpa.DCAEuuid</class>
+ <class>org.onap.policy.rest.jpa.DcaeUsers</class>
+ <class>org.onap.policy.rest.jpa.Dcaeuuid</class>
<class>org.onap.policy.rest.jpa.DescriptiveScope</class>
<class>org.onap.policy.rest.jpa.OnapName</class>
<class>org.onap.policy.rest.jpa.EnforcingType</class>
@@ -146,12 +146,12 @@
<class>org.onap.policy.rest.jpa.MicroServiceLocation</class>
<class>org.onap.policy.rest.jpa.Obadvice</class>
<class>org.onap.policy.rest.jpa.ObadviceExpression</class>
- <class>org.onap.policy.rest.jpa.PEPOptions</class>
- <class>org.onap.policy.rest.jpa.PIPConfigParam</class>
- <class>org.onap.policy.rest.jpa.PIPConfiguration</class>
- <class>org.onap.policy.rest.jpa.PIPResolver</class>
- <class>org.onap.policy.rest.jpa.PIPResolverParam</class>
- <class>org.onap.policy.rest.jpa.PIPType</class>
+ <class>org.onap.policy.rest.jpa.PepOptions</class>
+ <class>org.onap.policy.rest.jpa.PipConfigParam</class>
+ <class>org.onap.policy.rest.jpa.PipConfiguration</class>
+ <class>org.onap.policy.rest.jpa.PipResolver</class>
+ <class>org.onap.policy.rest.jpa.PipResolverParam</class>
+ <class>org.onap.policy.rest.jpa.PipType</class>
<class>org.onap.policy.rest.jpa.PolicyAlgorithms</class>
<class>org.onap.policy.rest.jpa.PolicyManagement</class>
<class>org.onap.policy.rest.jpa.PolicyScopeService</class>
@@ -166,12 +166,12 @@
<class>org.onap.policy.rest.jpa.RuleAlgorithms</class>
<class>org.onap.policy.rest.jpa.SecurityZone</class>
<class>org.onap.policy.rest.jpa.ServiceList</class>
- <class>org.onap.policy.rest.jpa.SystemLogDB</class>
+ <class>org.onap.policy.rest.jpa.SystemLogDb</class>
<class>org.onap.policy.rest.jpa.TermList</class>
<class>org.onap.policy.rest.jpa.VarbindDictionary</class>
- <class>org.onap.policy.rest.jpa.VMType</class>
- <class>org.onap.policy.rest.jpa.VNFType</class>
- <class>org.onap.policy.rest.jpa.VSCLAction</class>
+ <class>org.onap.policy.rest.jpa.VmType</class>
+ <class>org.onap.policy.rest.jpa.VnfType</class>
+ <class>org.onap.policy.rest.jpa.VsclAction</class>
<class>org.onap.policy.rest.jpa.Zone</class>
<!-- unique to PolicyEngineUtils -->
<class>org.onap.policy.jpa.BackUpMonitorEntity</class>
diff --git a/ONAP-PDP-REST/src/test/resources/test.drl b/ONAP-PDP-REST/src/test/resources/test.drl
index 7accc63ae..bb709575d 100644
--- a/ONAP-PDP-REST/src/test/resources/test.drl
+++ b/ONAP-PDP-REST/src/test/resources/test.drl
@@ -1,15 +1,14 @@
/*-
* ============LICENSE_START=======================================================
- * archetype-closed-loop-demo-rules
- * ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Bell Canada.
* ================================================================================
* 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.
@@ -20,1102 +19,16 @@
package org.onap.policy.controlloop;
-import java.util.List;
-import java.util.LinkedList;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.UUID;
-
-import org.onap.policy.controlloop.VirtualControlLoopEvent;
-import org.onap.policy.controlloop.ControlLoopEventStatus;
-import org.onap.policy.controlloop.VirtualControlLoopNotification;
-import org.onap.policy.controlloop.ControlLoopNotificationType;
-import org.onap.policy.controlloop.ControlLoopOperation;
-import org.onap.policy.controlloop.ControlLoopOperationWrapper;
-import org.onap.policy.template.demo.ControlLoopException;
-
-import org.onap.policy.aai.AAINQF199.AAINQF199CloudRegion;
-import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperties;
-import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperty;
-import org.onap.policy.aai.AAINQF199.AAINQF199GenericVNF;
-import org.onap.policy.aai.AAINQF199.AAINQF199InstanceFilters;
-import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItem;
-import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItems;
-import org.onap.policy.aai.AAINQF199.AAINQF199Manager;
-import org.onap.policy.aai.AAINQF199.AAINQF199NamedQuery;
-import org.onap.policy.aai.AAINQF199.AAINQF199QueryParameters;
-import org.onap.policy.aai.AAINQF199.AAINQF199Request;
-import org.onap.policy.aai.AAINQF199.AAINQF199RequestWrapper;
-import org.onap.policy.aai.AAINQF199.AAINQF199Response;
-import org.onap.policy.aai.AAINQF199.AAINQF199ResponseWrapper;
-import org.onap.policy.aai.AAINQF199.AAINQF199ServiceInstance;
-import org.onap.policy.aai.AAINQF199.AAINQF199Tenant;
-import org.onap.policy.aai.AAINQF199.AAINQF199VfModule;
-import org.onap.policy.aai.AAINQF199.AAINQF199VServer;
-import org.onap.policy.aai.util.Serialization;
-
-import org.onap.policy.appc.CommonHeader;
-import org.onap.policy.appc.Request;
-import org.onap.policy.appc.Response;
-import org.onap.policy.appc.ResponseCode;
-import org.onap.policy.appc.ResponseStatus;
-import org.onap.policy.appc.ResponseValue;
-
-import org.onap.policy.template.demo.EventManager;
-import org.onap.policy.vnf.trafficgenerator.PGRequest;
-import org.onap.policy.vnf.trafficgenerator.PGStream;
-import org.onap.policy.vnf.trafficgenerator.PGStreams;
-
-import org.onap.policy.mso.MSOManager;
-import org.onap.policy.mso.MSORequest;
-import org.onap.policy.mso.MSORequestStatus;
-import org.onap.policy.mso.MSORequestDetails;
-import org.onap.policy.mso.MSOModelInfo;
-import org.onap.policy.mso.MSOCloudConfiguration;
-import org.onap.policy.mso.MSORequestInfo;
-import org.onap.policy.mso.MSORequestParameters;
-import org.onap.policy.mso.MSORelatedInstanceListElement;
-import org.onap.policy.mso.MSORelatedInstance;
-import org.onap.policy.mso.MSOResponse;
-
-import org.onap.policy.drools.system.PolicyEngine;
-
-//
-// These parameters are required to build the runtime policy
-//
-declare Params
- closedLoopControlName : String
- actor : String
- aaiURL : String
- aaiUsername : String
- aaiPassword : String
- msoURL : String
- msoUsername : String
- msoPassword : String
- aaiNamedQueryUUID : String
- aaiPatternMatch : int
- notificationTopic : String
- appcTopic : String
-end
-
-/*
-*
-* Called once and only once to insert the parameters into working memory for this Closed Loop policy.
-* (Comment SETUP rule out for the first ONAP opensource release since policy BRMS_GW already puts a Params fact in there)
-*
-*
-*rule "${policyName}.SETUP"
-* when
-* then
-* System.out.println("rule SETUP is triggered.");
-* Params params = new Params();
-* params.setClosedLoopControlName("${closedLoopControlName}");
-* params.setActor("${actor}");
-* params.setAaiURL("${aaiURL}");
-* params.setAaiUsername("${aaiUsername}");
-* params.setAaiPassword("${aaiPassword}");
-* params.setMsoURL("${msoURL}");
-* params.setMsoUsername("${msoUsername}");
-* params.setMsoPassword("${msoPassword}");
-* params.setAaiNamedQueryUUID("${aaiNamedQueryUUID}");
-* params.setAaiPatternMatch(${aaiPatternMatch});
-* params.setNotificationTopic("${notificationTopic}");
-* params.setAppcTopic("${appcTopic}");
-* //
-* // This stays in memory as long as the rule is alive and running
-* //
-* insert(params);
-*end
-*/
-/*
-*
-* This rule responds to DCAE Events
-*
-*/
-rule "${policyName}.EVENT"
- when
- $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
- $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
- not ( EventManager( closedLoopControlName == $event.closedLoopControlName ))
- then
- System.out.println("rule EVENT is triggered.");
- try {
- //
- // Check the requestID in the event to make sure it is not null before we create the EventManager.
- // The EventManager will do extra syntax checking as well check if the closed loop is disabled/
- //
- if ($event.requestID == null) {
- VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
- notification.notification = ControlLoopNotificationType.REJECTED;
- notification.from = "policy";
- notification.message = "Missing requestID from DCAE event";
- notification.policyName = drools.getRule().getName();
- notification.policyScope = "${policyScope}";
- notification.policyVersion = "${policyVersion}";
- //
- // Let interested parties know
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("Can't deliver notification: " + notification);
- }
- //
- // Retract it from memory
- //
- retract($event);
- System.out.println("Event with requestID=null has been retracted.");
- } else {
- //
- // Create an EventManager
- //
- EventManager manager = new EventManager($params.getClosedLoopControlName(), $event.requestID, $event.target);
- //
- // Determine if EventManager can actively process the event (i.e. syntax)
- //
- VirtualControlLoopNotification notification = manager.activate($event);
- notification.from = "policy";
- notification.policyName = drools.getRule().getName();
- notification.policyScope = "${policyScope}";
- notification.policyVersion = "${policyVersion}";
- //
- // Are we actively pursuing this event?
- //
- if (notification.notification == ControlLoopNotificationType.ACTIVE) {
- //
- // Insert Event Manager into memory, this will now kick off processing.
- //
- insert(manager);
- //
- // Let interested parties know
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("Can't deliver notification: " + notification);
- }
- } else {
- //
- // Let interested parties know
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("Can't deliver notification: " + notification);
- }
- //
- // Retract it from memory
- //
- retract($event);
- }
- //
- // Now that the manager is inserted into Drools working memory, we'll wait for
- // another rule to fire in order to continue processing. This way we can also
- // then screen for additional ONSET and ABATED events for this same RequestIDs
- // and for different RequestIDs but with the same closedLoopControlName and target.
- //
- }
- //
- } catch (Exception e) {
- e.printStackTrace();
- VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
- notification.notification = ControlLoopNotificationType.REJECTED;
- notification.message = "Exception occurred " + e.getMessage();
- notification.policyName = drools.getRule().getName();
- notification.policyScope = "${policyScope}";
- notification.policyVersion = "${policyVersion}";
- //
- //
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e1) {
- System.out.println("Can't deliver notification: " + notification);
- e1.printStackTrace();
- }
- //
- // Retract the event
- //
- retract($event);
- }
-end
-
-/*
-*
-* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager
-* is created. We can start the operations for this closed loop.
-*
-*/
-rule "${policyName}.EVENT.MANAGER"
- when
- $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
- $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
- $manager : EventManager( closedLoopControlName == $event.closedLoopControlName, controlLoopResult == null)
- then
- System.out.println("rule EVENT.MANAGER is triggered.");
- //
- // Check which event this is.
- //
- EventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event);
- //
- // We only want the initial ONSET event in memory,
- // all the other events need to be retracted to support
- // cleanup and avoid the other rules being fired for this event.
- //
- if (eventStatus != EventManager.NEW_EVENT_STATUS.FIRST_ONSET) {
- System.out.println("Retracting "+eventStatus+" Event.");
- retract($event);
- return;
- }
- //
- // Now the event in memory is first onset event
- //
- try {
- //
- // Pull the known AAI field from the Event
- //
- // generic-vnf is needed for vFirewall case
- // vserver-name is needed for vLoadBalancer case
- //
- String genericVNF = $event.AAI.get("generic-vnf.vnf-id");
- String vserver = $event.AAI.get("vserver.vserver-name");
- //
- // Check if we are implementing a simple pattern match.
- //
- if ($params.getAaiPatternMatch() == 1) {
- //
- // Yes
- //
- //Basic naming characteristics:
- //VF Name (9 char)+VM name (13 char total)+VFC (19 char total)
- //Example:
- //VF Name (9 characters): cscf0001v
- //VM Name(13 characters): cscf0001vm001
- //VFC name(19 characters): cscf0001vm001cfg001
- //
- // zdfw1fwl01fwl02 or zdfw1fwl01fwl01
- // replaced with
- // zdfw1fwl01pgn02 or zdfw1fwl01pgn01
- //
- int index = genericVNF.lastIndexOf("fwl");
- if (index == -1) {
- System.err.println("The generic-vnf.vnf-id from DCAE Event is not valid.");
- } else {
- genericVNF = genericVNF.substring(0, index) + "pgn" + genericVNF.substring(index+"fwl".length());
- }
- //
- // Construct an APPC request
- //
- ControlLoopOperation operation = new ControlLoopOperation();
- operation.actor = $params.getActor();
- operation.operation = "ModifyConfig";
- operation.target = $event.target;
- //
- // Create operationWrapper
- //
- ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);
- //
- // insert operationWrapper into memory
- //
- insert(operationWrapper);
- //
- Request request = new Request();
- request.CommonHeader = new CommonHeader();
- request.CommonHeader.RequestID = $event.requestID;
- request.Action = operation.operation;
- request.Payload = new HashMap<String, Object>();
- //
- // Fill in the payload
- //
- request.Payload.put("generic-vnf.vnf-id", genericVNF);
- //
- PGRequest pgRequest = new PGRequest();
- pgRequest.pgStreams = new PGStreams();
-
- PGStream pgStream;
- for(int i = 0; i < 5; i++){
- pgStream = new PGStream();
- pgStream.streamId = "fw_udp"+(i+1);
- pgStream.isEnabled = "true";
- pgRequest.pgStreams.pgStream.add(pgStream);
- }
- request.Payload.put("pg-streams", pgRequest.pgStreams);
-
- if (request != null) {
- //
- // Insert request into memory
- //
- insert(request);
- //
- // Tell interested parties we are performing this Operation
- //
- VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
- notification.notification = ControlLoopNotificationType.OPERATION;
- // message and history ??
- notification.from = "policy";
- notification.policyName = drools.getRule().getName();
- notification.policyScope = "${policyScope}";
- notification.policyVersion = "${policyVersion}";
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
- //
- // Now send the operation request
- //
- if (request instanceof Request) {
- try {
- System.out.println("APPC request sent:");
- System.out.println(Serialization.gsonPretty.toJson(request));
- PolicyEngine.manager.deliver($params.getAppcTopic(), request);
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("Can't deliver request: " + request);
- }
- }
- } else {
- //
- // what happens if it is null
- //
- }
- //
- } else {
- //
- // create AAI named-query request with UUID started with "F199"
- //
- AAINQF199Request aainqf199request = new AAINQF199Request();
- AAINQF199QueryParameters aainqf199queryparam = new AAINQF199QueryParameters();
- AAINQF199NamedQuery aainqf199namedquery = new AAINQF199NamedQuery();
- AAINQF199InstanceFilters aainqf199instancefilter = new AAINQF199InstanceFilters();
- //
- // queryParameters
- //
- aainqf199namedquery.namedQueryUUID = UUID.fromString($params.getAaiNamedQueryUUID());
- aainqf199queryparam.namedQuery = aainqf199namedquery;
- aainqf199request.queryParameters = aainqf199queryparam;
- //
- // instanceFilters
- //
- Map aainqf199instancefiltermap = new HashMap();
- Map aainqf199instancefiltermapitem = new HashMap();
- aainqf199instancefiltermapitem.put("vserver-name", vserver);
- aainqf199instancefiltermap.put("vserver", aainqf199instancefiltermapitem);
- aainqf199instancefilter.instanceFilter.add(aainqf199instancefiltermap);
- aainqf199request.instanceFilters = aainqf199instancefilter;
- //
- // print aainqf199request for debug
- //
- System.out.println("AAI Request sent:");
- System.out.println(Serialization.gsonPretty.toJson(aainqf199request));
- //
- // Create AAINQF199RequestWrapper
- //
- AAINQF199RequestWrapper aainqf199RequestWrapper = new AAINQF199RequestWrapper($event.requestID, aainqf199request);
- //
- // insert aainqf199request into memory
- //
- insert(aainqf199RequestWrapper);
- }
- //
- } catch (Exception e) {
- e.printStackTrace();
- }
-end
-
-/*
-*
-* This rule happens when we got a valid ONSET, closed loop is enabled, an Event Manager
-* is created, AAI Manager and AAI Request are ready in memory. We can start sending query to AAI and then wait for response.
-*
-*/
-rule "${policyName}.EVENT.MANAGER.AAINQF199REQUEST"
- when
- $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
- $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
- $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )
- $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID)
- then
- System.out.println("rule EVENT.MANAGER.AAINQF199REQUEST is triggered.");
- //
- // send the request
- //
- AAINQF199Response aainqf199response = AAINQF199Manager.postQuery($params.getAaiURL(), $params.getAaiUsername(), $params.getAaiPassword(),
- $aainqf199RequestWrapper.aainqf199request, $event.requestID);
- //
- // Check AAI response
- //
- if (aainqf199response == null) {
- System.err.println("Failed to get AAI response");
- //
- // Fail and retract everything
- //
- retract($event);
- retract($manager);
- retract($aainqf199RequestWrapper);
- } else {
- //
- // Create AAINQF199ResponseWrapper
- //
- AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper($event.requestID, aainqf199response);
- //
- // insert aainqf199ResponseWrapper to memeory
- //
- insert(aainqf199ResponseWrapper);
- }
+rule "INIT"
+when
+then
+ insert("This is a test");
end
-/*
-*
-* This rule happens when we got a valid AAI response. We can start sending request to APPC or MSO now.
-*
-*/
-rule "${policyName}.EVENT.MANAGER.AAINQF199RESPONSE"
- when
- $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
- $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
- $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )
- $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID)
- $aainqf199ResponseWrapper : AAINQF199ResponseWrapper(requestID == $event.requestID)
- then
- System.out.println("rule EVENT.MANAGER.AAINQF199RESPONSE is triggered.");
- //
- // Extract related fields out of AAINQF199RESPONSE
- //
- String vnfItemVnfId, vnfItemVnfType, vnfItemPersonaModelId, vnfItemPersonaModelVersion, vnfItemModelName,
- vnfItemModelVersion, vnfItemModelNameVersionId, serviceItemServiceInstanceId, serviceItemPersonaModelId,
- serviceItemModelName, serviceItemModelType, serviceItemModelVersion, serviceItemModelNameVersionId,
- vfModuleItemVfModuleName, vfModuleItemPersonaModelId, vfModuleItemPersonaModelVersion, vfModuleItemModelName,
- vfModuleItemModelNameVersionId, tenantItemTenantId, cloudRegionItemCloudRegionId;
- try {
- //
- // vnfItem
- //
- vnfItemVnfId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID;
- vnfItemVnfType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType;
- vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf("/")+1);
- vnfItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId;
- vnfItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion;
- vnfItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue;
- vnfItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(2).propertyValue;
- vnfItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue;
- //
- // serviceItem
- //
- serviceItemServiceInstanceId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID;
- serviceItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId;
- serviceItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue;
- serviceItemModelType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(1).propertyValue;
- serviceItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion;
- serviceItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue;
- //
- // Find the index for base vf module and non-base vf module
- //
- int baseIndex = -1;
- int nonBaseIndex = -1;
- List<AAINQF199InventoryResponseItem> inventoryItems = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems;
- for (AAINQF199InventoryResponseItem m : inventoryItems) {
- if (m.vfModule != null && m.vfModule.isBaseVfModule == true) {
- baseIndex = inventoryItems.indexOf(m);
- } else if (m.vfModule != null && m.vfModule.isBaseVfModule == false && m.vfModule.orchestrationStatus == null) {
- nonBaseIndex = inventoryItems.indexOf(m);
- }
- //
- if (baseIndex != -1 && nonBaseIndex != -1) {
- break;
- }
- }
- //
- // Report the error if either base vf module or non-base vf module is not found
- //
- if (baseIndex == -1 || nonBaseIndex == -1) {
- System.err.println("Either base or non-base vf module is not found from AAI response.");
- retract($aainqf199RequestWrapper);
- retract($aainqf199ResponseWrapper);
- retract($manager);
- retract($event);
- return;
- }
- //
- // This comes from the base module
- //
- vfModuleItemVfModuleName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(baseIndex).vfModule.vfModuleName;
- vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace("Vfmodule", "vDNS");
- //
- // vfModuleItem - NOT the base module
- //
- vfModuleItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelId;
- vfModuleItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelVersion;
- vfModuleItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(0).propertyValue;
- vfModuleItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(4).propertyValue;
- //
- // tenantItem
- //
- tenantItemTenantId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId;
- //
- // cloudRegionItem
- //
- cloudRegionItemCloudRegionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId;
- //
- } catch (Exception e) {
- e.printStackTrace();
- VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
- notification.notification = ControlLoopNotificationType.REJECTED;
- notification.message = "Exception occurred " + e.getMessage();
- notification.policyName = drools.getRule().getName();
- notification.policyScope = "${policyScope}";
- notification.policyVersion = "${policyVersion}";
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e1) {
- System.out.println("Can't deliver notification: " + notification);
- e1.printStackTrace();
- }
- //
- notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
- notification.message = "Invalid named-query response from AAI";
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e1) {
- System.out.println("Can't deliver notification: " + notification);
- e1.printStackTrace();
- }
- //
- // Retract everything
- //
- retract($aainqf199RequestWrapper);
- retract($aainqf199ResponseWrapper);
- retract($manager);
- retract($event);
- return;
- }
- //
- // Extracted fields should not be null
- //
- if ((vnfItemVnfId == null) || (vnfItemVnfType == null) ||
- (vnfItemPersonaModelId == null) || (vnfItemModelName == null) ||
- (vnfItemModelVersion == null) || (vnfItemModelNameVersionId == null) ||
- (serviceItemServiceInstanceId == null) || (serviceItemModelName == null) ||
- (serviceItemModelType == null) || (serviceItemModelVersion == null) ||
- (serviceItemModelNameVersionId == null) || (vfModuleItemVfModuleName == null) ||
- (vfModuleItemPersonaModelId == null) || (vfModuleItemPersonaModelVersion == null) ||
- (vfModuleItemModelName == null) || (vfModuleItemModelNameVersionId == null) ||
- (tenantItemTenantId == null) || (cloudRegionItemCloudRegionId == null)) {
- //
- System.err.println("some fields are missing from AAI response.");
- //
- // Fail and retract everything
- //
- retract($aainqf199RequestWrapper);
- retract($aainqf199ResponseWrapper);
- retract($manager);
- retract($event);
- return;
- }
- //
- // We don't need them any more
- //
- retract($aainqf199ResponseWrapper);
- retract($aainqf199RequestWrapper);
- //
- // check the actor of this closed loop
- //
- switch ($params.getActor()) {
- case "APPC":
- {
- //
- // Construct an APPC request
- //
- ControlLoopOperation operation = new ControlLoopOperation();
- operation.actor = $params.getActor();
- operation.operation = "ModifyConfig";
- operation.target = $event.target;
- //
- // Create operationWrapper
- //
- ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);
- //
- // insert operationWrapper into memory
- //
- insert(operationWrapper);
- //
- Request request = new Request();
- request.CommonHeader = new CommonHeader();
- request.CommonHeader.RequestID = $event.requestID;
- request.Action = operation.operation;
- request.Payload = new HashMap<String, Object>();
- //
- // Fill in the payload
- // Hardcode genericVNF for now since AAI has not been ready for vFirewall demo case
- //
- String genericVNF = "zdfw1fwl01pgn02";
- request.Payload.put("generic-vnf.vnf-id", genericVNF);
- //
- PGRequest pgRequest = new PGRequest();
- pgRequest.pgStreams = new PGStreams();
-
- PGStream pgStream;
- for(int i = 0; i < 5; i++){
- pgStream = new PGStream();
- pgStream.streamId = "fw_udp"+(i+1);
- pgStream.isEnabled = "true";
- pgRequest.pgStreams.pgStream.add(pgStream);
- }
- request.Payload.put("pg-streams", pgRequest.pgStreams);
-
- if (request != null) {
- //
- // Insert request into memory
- //
- insert(request);
- //
- // Tell interested parties we are performing this Operation
- //
- VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
- notification.notification = ControlLoopNotificationType.OPERATION;
- // message and history ??
- notification.from = "policy";
- notification.policyName = drools.getRule().getName();
- notification.policyScope = "${policyScope}";
- notification.policyVersion = "${policyVersion}";
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
- //
- // Now send the operation request
- //
- if (request instanceof Request) {
- try {
- System.out.println("APPC request sent:");
- System.out.println(Serialization.gsonPretty.toJson(request));
- PolicyEngine.manager.deliver($params.getAppcTopic(), request);
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("Can't deliver request: " + request);
- }
- }
- } else {
- //
- // what happens if it is null
- //
- }
- }
- break;
- case "MSO":
- {
- //
- // Construct an operation
- //
- ControlLoopOperation operation = new ControlLoopOperation();
- operation.actor = $params.getActor();
- operation.operation = "createModuleInstance";
- operation.target = $event.target;
- //
- // Create operationWrapper
- //
- ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);
- //
- // Construct an MSO request
- //
- MSORequest request = new MSORequest();
- request.requestDetails = new MSORequestDetails();
- request.requestDetails.modelInfo = new MSOModelInfo();
- request.requestDetails.cloudConfiguration = new MSOCloudConfiguration();
- request.requestDetails.requestInfo = new MSORequestInfo();
- request.requestDetails.requestParameters = new MSORequestParameters();
- request.requestDetails.requestParameters.userParams = null;
- //
- // cloudConfiguration
- //
- request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId;
- request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId;
- //
- // modelInfo
- //
- request.requestDetails.modelInfo.modelType = "vfModule";
- request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId;
- request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId;
- request.requestDetails.modelInfo.modelName = vfModuleItemModelName;
- request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion;
- //
- // requestInfo
- //
- request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName;
- request.requestDetails.requestInfo.source = "POLICY";
- request.requestDetails.requestInfo.suppressRollback = false;
- //
- // relatedInstanceList
- //
- MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement();
- MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement();
- relatedInstanceListElement1.relatedInstance = new MSORelatedInstance();
- relatedInstanceListElement2.relatedInstance = new MSORelatedInstance();
- //
- relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId;
- relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo();
- relatedInstanceListElement1.relatedInstance.modelInfo.modelType = "service";
- relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId;
- relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId;
- relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName;
- relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion;
- //
- relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId;
- relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo();
- relatedInstanceListElement2.relatedInstance.modelInfo.modelType = "vnf";
- relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId;
- relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId;
- relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName;
- relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemModelVersion;
- relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType;
- //
- request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1);
- request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2);
- //
- // print MSO request for debug
- //
- System.out.println("MSO request sent:");
- System.out.println(Serialization.gsonPretty.toJson(request));
- //
- //
- //
- if (request != null) {
- //
- // Tell interested parties we are performing this Operation
- //
- VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
- notification.notification = ControlLoopNotificationType.OPERATION;
- notification.from = "policy";
- notification.policyName = drools.getRule().getName();
- notification.policyScope = "${policyScope}";
- notification.policyVersion = "${policyVersion}";
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
- //
- // Concatenate serviceItemServiceInstanceId and vnfItemVnfId to msoURL
- //
- String MSOUrl = $params.getMsoURL() + "/serviceInstances/v2/" + serviceItemServiceInstanceId + "/vnfs/" + vnfItemVnfId + "/vfModules";
- //
- // Call MSO
- //
- MSOResponse response = MSOManager.createModuleInstance(MSOUrl, $params.getMsoURL(), $params.getMsoUsername(), $params.getMsoPassword(), request);
- //
- if (response != null) {
- //
- // Assign requestId
- //
- request.requestId = $event.requestID.toString();
- response.request.requestId = $event.requestID.toString();
- //
- // Insert facts
- //
- insert(operationWrapper);
- insert(request);
- insert(response);
- } else {
- //
- // MSO request not even accepted
- //
- notification.message = operationWrapper.operation.toMessage();
- operationWrapper.operation.message = operationWrapper.operation.toMessage();
- operationWrapper.operation.outcome = "FAILURE_EXCEPTION";
- $manager.setControlLoopResult("FAILURE_EXCEPTION");
- notification.history.add(operationWrapper.operation);
- notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
- //
- // Let interested parties know
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
- notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
- //
- // Retract everything
- //
- retract($event);
- retract($manager);
- }
- } else {
- System.err.println("constructed MSO request is invalid.");
- }
- }
- break;
- }
+rule "PRINT_MSG"
+when
+ $o : Object();
+then
+ System.out.println("MSG: " + $o);
+ retract($o);
end
-
-/*
-*
-* This rule responds to APPC Response Events
-*
-*/
-rule "${policyName}.APPC.RESPONSE"
- when
- $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
- $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
- $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )
- $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID )
- $request : Request( getCommonHeader().RequestID == $event.requestID )
- $response : Response( getCommonHeader().RequestID == $event.requestID )
- then
- System.out.println("rule APPC.RESPONSE is triggered.");
- if ($response.Status == null) {
- $operationWrapper.operation.outcome = "FAILURE_EXCEPTION";
- $manager.setControlLoopResult("FAILURE_EXCEPTION");
- }
- //
- // Get the Response Code
- //
- ResponseCode code = ResponseCode.toResponseCode($response.Status.Code);
- if (code == null) {
- $operationWrapper.operation.outcome = "FAILURE_EXCEPTION";
- $manager.setControlLoopResult("FAILURE_EXCEPTION");
- }
- //
- // Construct notification
- //
- VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
- notification.from = "policy";
- notification.policyName = drools.getRule().getName();
- notification.policyScope = "${policyScope}";
- notification.policyVersion = "${policyVersion}";
- notification.message = $operationWrapper.operation.toMessage();
- $operationWrapper.operation.message = $operationWrapper.operation.toMessage();
- //
- // Ok, let's figure out what APP-C's response is
- //
- switch (code) {
- case ACCEPT:
- $operationWrapper.operation.outcome = "PROCESSING";
- break;
- case ERROR:
- case REJECT:
- $operationWrapper.operation.outcome = "FAILURE_EXCEPTION";
- $manager.setControlLoopResult("FAILURE_EXCEPTION");
- break;
- case SUCCESS:
- $operationWrapper.operation.outcome = "SUCCESS";
- $manager.setControlLoopResult("SUCCESS");
- break;
- case FAILURE:
- $operationWrapper.operation.outcome = "FAILURE";
- $manager.setControlLoopResult("FAILURE");
- break;
- }
- if ($operationWrapper.operation.outcome.equals("SUCCESS")) {
- notification.history.add($operationWrapper.operation);
- notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
- //
- // Let interested parties know
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
- notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
-
- //
- // We are going to retract these objects from memory
- //
- System.out.println("Retracting everything");
- retract($operationWrapper);
- retract($request);
- retract($response);
- retract($event);
- retract($manager);
- } else if ($operationWrapper.operation.outcome.equals("PROCESSING")) {
- retract($response);
- } else {
- notification.history.add($operationWrapper.operation);
- notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
- //
- // Let interested parties know
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
- notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
- //
- // Let interested parties know
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
- //
- // We are going to retract these objects from memory
- //
- System.out.println("Retracting everything");
- retract($operationWrapper);
- retract($request);
- retract($response);
- retract($event);
- retract($manager);
- }
-
-end
-
-/*
-*
-* This rule is used to clean up APPC response
-*
-*/
-rule "${policyName}.APPC.RESPONSE.CLEANUP"
- when
- $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
- $response : Response($id : getCommonHeader().RequestID )
- not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) )
- then
- System.out.println("rule APPC.RESPONSE.CLEANUP is triggered.");
- retract($response);
-end
-
-/*
-*
-* This rule responds to MSO Response Events
-*
-*/
-rule "${policyName}.MSO.RESPONSE"
- when
- $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
- $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
- $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )
- $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID )
- $request : MSORequest( requestId == $event.requestID.toString() )
- $response : MSOResponse( request.requestId == $event.requestID.toString() )
- then
- System.out.println("rule MSO.RESPONSE is triggered.");
- //
- // Construct notification
- //
- VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
- notification.from = "policy";
- notification.policyName = drools.getRule().getName();
- notification.policyScope = "${policyScope}";
- notification.policyVersion = "${policyVersion}";
- notification.message = $operationWrapper.operation.toMessage();
- $operationWrapper.operation.message = $operationWrapper.operation.toMessage();
- //
- // The operation can either be succeeded or failed
- //
- if($response.request.requestStatus.requestState.equals("Completed")) {
- $operationWrapper.operation.outcome = "SUCCESS";
- $manager.setControlLoopResult("SUCCESS");
- notification.history.add($operationWrapper.operation);
- notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
- //
- // Let interested parties know
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
- notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;
- //
- // Let interested parties know
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
- //
- // We are going to retract these objects from memory
- //
- System.out.println("Retracting everything");
- retract($operationWrapper);
- retract($request);
- retract($response);
- retract($event);
- retract($manager);
- } else {
- $operationWrapper.operation.outcome = "FAILURE";
- $manager.setControlLoopResult("FAILURE");
- notification.history.add($operationWrapper.operation);
- notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
- //
- // Let interested parties know
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
- notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
- //
- // Let interested parties know
- //
- try {
- System.out.println(Serialization.gsonPretty.toJson(notification));
- PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
- } catch (Exception e) {
- System.out.println("Can't deliver notification: " + notification);
- e.printStackTrace();
- }
- //
- // We are going to retract these objects from memory
- //
- System.out.println("Retracting everything");
- retract($operationWrapper);
- retract($request);
- retract($response);
- retract($event);
- retract($manager);
- }
-
-end