summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java457
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java123
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRest.java339
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Category.java333
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java7
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java106
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java1
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java15
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java1283
-rw-r--r--PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndDMAAP.java186
-rw-r--r--PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndUEB.java221
-rw-r--r--PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java198
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/std/NotificationStore.java370
13 files changed, 1832 insertions, 1807 deletions
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 49400d615..b33c4bd16 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
@@ -3,6 +3,7 @@
* ONAP-PDP-REST
* ================================================================================
* Copyright (C) 2017 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.
@@ -46,240 +47,240 @@ import org.onap.policy.common.logging.eelf.PolicyLogger;
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 static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpRegisterThread.class);
+ private static final Logger auditLogger = FlexLogger.getLogger("auditLogger");
+ private ONAPLoggingContext baseLoggingContext = null;
- public volatile boolean isRunning = false;
-
- public XACMLPdpRegisterThread(ONAPLoggingContext baseLoggingContext) {
- this.baseLoggingContext = baseLoggingContext;
- }
- public synchronized boolean isRunning() {
- return this.isRunning;
- }
-
- public synchronized void terminate() {
- this.isRunning = false;
- }
-
- /**
- *
- * This is our thread that runs on startup to tell the PAP server we are up-and-running.
- *
- */
- @Override
- public void run() {
- synchronized(this) {
- this.isRunning = true;
- }
- // get a new logging context for the thread
- ONAPLoggingContext loggingContext = new ONAPLoggingContext(baseLoggingContext);
- loggingContext.setServiceName("PDP:PAP.register");
- //are we registered with at least one
- boolean registered = false;
- boolean interrupted = false;
- /*
- int seconds;
- try {
- seconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_SLEEP));
- } catch (NumberFormatException e) {
- LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR +"REGISTER_SLEEP: ", e);
- seconds = 5;
- }
- if (seconds < 5) {
- seconds = 5;
- }
- int retries;
- try {
- retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_RETRIES));
- } catch (NumberFormatException e) {
- LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +" REGISTER_SLEEP: ", e);
- retries = -1;
- }
- */
- PapUrlResolver papUrls = PapUrlResolver.getInstance();
- //while (! registered && ! interrupted && this.isRunning()) {
- String tempRootPoliciesProperty = XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
- String tempReferencedPoliciesProperty = XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
- Properties tempPipConfigProperties = new Properties();
- try(InputStream pipFile = Files.newInputStream(XACMLPdpLoader.getPIPConfig())){
- tempPipConfigProperties.load(pipFile);
- } catch(Exception e){
- LOGGER.error("Failed to open PIP property file", e);
- }
- 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));
- HttpURLConnection connection = null;
- try {
- // get a new transaction (request) ID and update the logging context.
- // each time through the outer loop is considered a new transaction.
- // each time through the inner loop (which handles redirects) is a
- // continuation of the same transaction.
- UUID requestID = UUID.randomUUID();
- 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[] papUrls = papUrlList.split(",");
- //PapUrlResolver.setPapUrls(papUrls);
- URL url = new URL(papUrls.getUrl());
- LOGGER.info("Registering with " + url.toString());
- //PolicyLogger.info("new transaction (request) ID and update to logging context in XACMLPdpRegisterThread");
- boolean finished = false;
- while (! finished) {
- //
- // Open up the connection
- //
- connection = (HttpURLConnection)url.openConnection();
- //
- // Setup our method and headers
- //
- connection.setRequestMethod("POST");
- 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("X-ECOMP-RequestID", requestID.toString());
- connection.setUseCaches(false);
- //
- // Adding this in. It seems the HttpUrlConnection class does NOT
- // properly forward our headers for POST re-direction. It does so
- // for a GET re-direction.
- //
- // So we need to handle this ourselves.
- //
- connection.setInstanceFollowRedirects(false);
- connection.setDoOutput(true);
- connection.setDoInput(true);
- try {
- //
- // Send our current policy configuration
- //
- String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + tempRootPoliciesProperty;
- lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + tempReferencedPoliciesProperty + "\n";
- try (InputStream listsInputStream = new ByteArrayInputStream(lists.getBytes());
- OutputStream os = connection.getOutputStream()) {
- IOUtils.copy(listsInputStream, os);
+ public volatile boolean isRunning = false;
- //
- // Send our current PIP configuration
- //
- //IOUtils.copy(pipInputStream, os);
- tempPipConfigProperties.store(os, "");
- }
- } catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Failed to send property file", e);
- }
- //
- // Do the connect
- //
- connection.connect();
- if (connection.getResponseCode() == 204) {
- LOGGER.info("Success. We are configured correctly.");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Success. We are configured correctly.");
- papUrls.registered();
- finished = true;
- registered = true;
- } else if (connection.getResponseCode() == 200) {
- LOGGER.info("Success. We have a new configuration.");
- loggingContext.transactionEnded();
- PolicyLogger.audit("Success. We have a new configuration.");
- papUrls.registered();
- Properties properties = new Properties();
- properties.load(connection.getInputStream());
- LOGGER.info("New properties: " + properties.toString());
- //
- // Queue it
- //
- // The incoming properties does NOT include urls
- Properties returnedPolicyProperties = XACMLProperties.getPolicyProperties(properties, false);
- tempRootPoliciesProperty = new String(returnedPolicyProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES));
- tempReferencedPoliciesProperty = new String(returnedPolicyProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES));
- Properties returnedPipProperties = XACMLProperties.getPipProperties(properties);
- Properties threadSafeReturnedPipProperties = new Properties();
- ByteArrayOutputStream threadSafeReturnedPipPropertiesOs = new ByteArrayOutputStream();
- returnedPipProperties.store(threadSafeReturnedPipPropertiesOs, "");
- InputStream threadSafeReturnedPipPropertiesIs = new ByteArrayInputStream(threadSafeReturnedPipPropertiesOs.toByteArray());
- threadSafeReturnedPipProperties.load(threadSafeReturnedPipPropertiesIs);
- tempPipConfigProperties = threadSafeReturnedPipProperties;
+ public XACMLPdpRegisterThread(ONAPLoggingContext baseLoggingContext) {
+ this.baseLoggingContext = baseLoggingContext;
+ }
- PutRequest req = new PutRequest(returnedPolicyProperties,returnedPipProperties);
- XACMLPdpServlet.queue.offer(req);
- //
- // We are now registered
- //
- finished = true;
- registered=true;
- } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
- //
- // Re-direction
- //
- String newLocation = connection.getHeaderField("Location");
- if (newLocation == null || newLocation.isEmpty()) {
- LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location");
- loggingContext.transactionEnded();
- auditLogger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location");
- PolicyLogger.audit("Transaction Failed - See Error.log");
- finished = true;
- } else {
- LOGGER.info("New Location: " + newLocation);
- url = new URL(newLocation);
- }
- } else {
- LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
- loggingContext.transactionEnded();
- auditLogger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
- PolicyLogger.audit("Transaction Failed - See Error.log");
- finished = true;
- papUrls.failed();
- }
- }
- } catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
- loggingContext.transactionEnded();
- PolicyLogger.audit("Transaction Failed - See Error.log");
- papUrls.failed();
- } finally {
- // cleanup the connection
- if (connection != null) {
- try {
- // For some reason trying to get the inputStream from the connection
- // throws an exception rather than returning null when the InputStream does not exist.
- InputStream is = null;
- try {
- is = connection.getInputStream();
- } catch (Exception e1) {
- LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to get Input Stream: " + e1);
- }
- if (is != null) {
- is.close();
- }
+ public synchronized boolean isRunning() {
+ return this.isRunning;
+ }
- } catch (IOException ex) {
- LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to close connection: " + ex, ex);
- }
- connection.disconnect();
- }
- }
+ public synchronized void terminate() {
+ this.isRunning = false;
+ }
- papUrls.getNext();
- }
- synchronized(this) {
- this.isRunning = false;
- }
- LOGGER.info("Thread exiting...(registered=" + registered + ", interrupted=" + interrupted + ", isRunning=" + this.isRunning() + ", retries=" + "0" + ")");
- }
+ /**
+ *
+ * This is our thread that runs on startup to tell the PAP server we are up-and-running.
+ *
+ */
+ @Override
+ public void run() {
+ synchronized(this) {
+ this.isRunning = true;
+ }
+ // get a new logging context for the thread
+ ONAPLoggingContext loggingContext = new ONAPLoggingContext(baseLoggingContext);
+ loggingContext.setServiceName("PDP:PAP.register");
+ //are we registered with at least one
+ boolean registered = false;
+ boolean interrupted = false;
+ /*
+ int seconds;
+ try {
+ seconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_SLEEP));
+ } catch (NumberFormatException e) {
+ LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR +"REGISTER_SLEEP: ", e);
+ seconds = 5;
+ }
+ if (seconds < 5) {
+ seconds = 5;
+ }
+ int retries;
+ try {
+ retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_RETRIES));
+ } catch (NumberFormatException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +" REGISTER_SLEEP: ", e);
+ retries = -1;
+ }
+ */
+ PapUrlResolver papUrls = PapUrlResolver.getInstance();
+ //while (! registered && ! interrupted && this.isRunning()) {
+ String tempRootPoliciesProperty = XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
+ String tempReferencedPoliciesProperty = XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
+ Properties tempPipConfigProperties = new Properties();
+ try(InputStream pipFile = Files.newInputStream(XACMLPdpLoader.getPIPConfig())){
+ tempPipConfigProperties.load(pipFile);
+ } catch(Exception e){
+ LOGGER.error("Failed to open PIP property file", e);
+ }
+ 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));
+ HttpURLConnection connection = null;
+ try {
+ // get a new transaction (request) ID and update the logging context.
+ // each time through the outer loop is considered a new transaction.
+ // each time through the inner loop (which handles redirects) is a
+ // continuation of the same transaction.
+ UUID requestID = UUID.randomUUID();
+ 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[] papUrls = papUrlList.split(",");
+ //PapUrlResolver.setPapUrls(papUrls);
+ URL url = new URL(papUrls.getUrl());
+ LOGGER.info("Registering with " + url.toString());
+ //PolicyLogger.info("new transaction (request) ID and update to logging context in XACMLPdpRegisterThread");
+ boolean finished = false;
+ while (! finished) {
+ //
+ // Open up the connection
+ //
+ connection = (HttpURLConnection)url.openConnection();
+ //
+ // Setup our method and headers
+ //
+ connection.setRequestMethod("POST");
+ 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("X-ECOMP-RequestID", requestID.toString());
+ connection.setUseCaches(false);
+ //
+ // Adding this in. It seems the HttpUrlConnection class does NOT
+ // properly forward our headers for POST re-direction. It does so
+ // for a GET re-direction.
+ //
+ // So we need to handle this ourselves.
+ //
+ connection.setInstanceFollowRedirects(false);
+ connection.setDoOutput(true);
+ connection.setDoInput(true);
+ try {
+ //
+ // Send our current policy configuration
+ //
+ String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + tempRootPoliciesProperty;
+ lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + tempReferencedPoliciesProperty + "\n";
+ try (InputStream listsInputStream = new ByteArrayInputStream(lists.getBytes());
+ OutputStream os = connection.getOutputStream()) {
+ IOUtils.copy(listsInputStream, os);
+
+ //
+ // Send our current PIP configuration
+ //
+ //IOUtils.copy(pipInputStream, os);
+ tempPipConfigProperties.store(os, "");
+ }
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Failed to send property file", e);
+ }
+ //
+ // Do the connect
+ //
+ connection.connect();
+ if (connection.getResponseCode() == 204) {
+ LOGGER.info("Success. We are configured correctly.");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Success. We are configured correctly.");
+ papUrls.registered();
+ finished = true;
+ registered = true;
+ } else if (connection.getResponseCode() == 200) {
+ LOGGER.info("Success. We have a new configuration.");
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Success. We have a new configuration.");
+ papUrls.registered();
+ Properties properties = new Properties();
+ properties.load(connection.getInputStream());
+ LOGGER.info("New properties: " + properties.toString());
+ //
+ // Queue it
+ //
+ // The incoming properties does NOT include urls
+ Properties returnedPolicyProperties = XACMLProperties.getPolicyProperties(properties, false);
+ tempRootPoliciesProperty = returnedPolicyProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
+ tempReferencedPoliciesProperty = returnedPolicyProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
+ Properties returnedPipProperties = XACMLProperties.getPipProperties(properties);
+ Properties threadSafeReturnedPipProperties = new Properties();
+ ByteArrayOutputStream threadSafeReturnedPipPropertiesOs = new ByteArrayOutputStream();
+ returnedPipProperties.store(threadSafeReturnedPipPropertiesOs, "");
+ InputStream threadSafeReturnedPipPropertiesIs = new ByteArrayInputStream(threadSafeReturnedPipPropertiesOs.toByteArray());
+ threadSafeReturnedPipProperties.load(threadSafeReturnedPipPropertiesIs);
+ tempPipConfigProperties = threadSafeReturnedPipProperties;
+
+ PutRequest req = new PutRequest(returnedPolicyProperties,returnedPipProperties);
+ XACMLPdpServlet.queue.offer(req);
+ //
+ // We are now registered
+ //
+ finished = true;
+ registered=true;
+ } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
+ //
+ // Re-direction
+ //
+ String newLocation = connection.getHeaderField("Location");
+ if (newLocation == null || newLocation.isEmpty()) {
+ LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location");
+ loggingContext.transactionEnded();
+ auditLogger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location");
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ finished = true;
+ } else {
+ LOGGER.info("New Location: " + newLocation);
+ url = new URL(newLocation);
+ }
+ } else {
+ LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
+ loggingContext.transactionEnded();
+ auditLogger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ finished = true;
+ papUrls.failed();
+ }
+ }
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
+ loggingContext.transactionEnded();
+ PolicyLogger.audit("Transaction Failed - See Error.log");
+ papUrls.failed();
+ } finally {
+ // cleanup the connection
+ if (connection != null) {
+ try {
+ // For some reason trying to get the inputStream from the connection
+ // throws an exception rather than returning null when the InputStream does not exist.
+ InputStream is = null;
+ try {
+ is = connection.getInputStream();
+ } catch (Exception e1) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to get Input Stream: " + e1);
+ }
+ if (is != null) {
+ is.close();
+ }
+
+ } catch (IOException ex) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to close connection: " + ex, ex);
+ }
+ connection.disconnect();
+ }
+ }
+
+ papUrls.getNext();
+ }
+ synchronized(this) {
+ this.isRunning = false;
+ }
+ LOGGER.info("Thread exiting...(registered=" + registered + ", interrupted=" + interrupted + ", isRunning=" + this.isRunning() + ", retries=" + "0" + ")");
+ }
}
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 936e497f4..6dae064a7 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
@@ -341,83 +341,66 @@ public class PDPServices {
if(pdpConfigLocation.contains("/")){
pdpConfigLocation = pdpConfigLocation.replace("/", File.separator);
}
- InputStream inputStream = null;
- JsonReader jsonReader = null;
- try {
- inputStream = new FileInputStream(new File(pdpConfigLocation));
- try {
- if (pdpConfigLocation.endsWith("json")) {
- pdpResponse.setType(PolicyType.JSON);
- jsonReader = Json.createReader(inputStream);
+
+ try(InputStream inputStream = new FileInputStream(new File(pdpConfigLocation))) {
+ if (pdpConfigLocation.endsWith("json")) {
+ pdpResponse.setType(PolicyType.JSON);
+ try(JsonReader jsonReader = Json.createReader(inputStream);) {
pdpResponse.setConfig(jsonReader.readObject().toString());
- jsonReader.close();
- } else if (pdpConfigLocation.endsWith("xml")) {
- pdpResponse.setType(PolicyType.XML);
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
- DocumentBuilder db = null;
- try {
- db = dbf.newDocumentBuilder();
- Document document = db.parse(inputStream);
- DOMSource domSource = new DOMSource(document);
- StringWriter writer = new StringWriter();
- StreamResult result = new StreamResult(writer);
- TransformerFactory tf = TransformerFactory.newInstance();
- Transformer transformer;
- transformer = tf.newTransformer();
- transformer.transform(domSource, result);
- pdpResponse.setConfig(writer.toString());
- } catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ e);
- throw new PDPException(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the XML config", e);
- }
- } else if (pdpConfigLocation.endsWith("properties")) {
- pdpResponse.setType(PolicyType.PROPERTIES);
- Properties configProp = new Properties();
- configProp.load(inputStream);
- Map<String, String> propVal = new HashMap<>();
- for(String name: configProp.stringPropertyNames()) {
- propVal.put(name, configProp.getProperty(name));
- }
- pdpResponse.setProperty(propVal);
- } else if (pdpConfigLocation.endsWith("txt")) {
- pdpResponse.setType(PolicyType.OTHER);
- String other = IOUtils.toString(inputStream);
- IOUtils.closeQuietly(inputStream);
- pdpResponse.setConfig(other);
- } else {
- LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config Not Found");
- pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
- pdpResponse.setPolicyConfigMessage("Illegal form of Configuration Type Found.");
- inputStream.close();
- return pdpResponse;
}
- LOGGER.info("config Retrieved " + pdpConfigLocation);
- pdpResponse.setStatus("Config Retrieved! ",
- PolicyResponseStatus.NO_ACTION_REQUIRED,
- PolicyConfigStatus.CONFIG_RETRIEVED);
- return pdpResponse;
- } catch (IOException | ParserConfigurationException e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
- throw new PDPException(XACMLErrorConstants.ERROR_PROCESS_FLOW +
- "Cannot open a connection to the configURL", e);
- } finally {
- if(jsonReader != null) {
- try {
- jsonReader.close();
- } catch (Exception e) {
- LOGGER.error("Exception Occured while closing the JsonReader"+e);
- }
+ } else if (pdpConfigLocation.endsWith("xml")) {
+ pdpResponse.setType(PolicyType.XML);
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ DocumentBuilder db = null;
+ try {
+ db = dbf.newDocumentBuilder();
+ Document document = db.parse(inputStream);
+ DOMSource domSource = new DOMSource(document);
+ StringWriter writer = new StringWriter();
+ StreamResult result = new StreamResult(writer);
+ TransformerFactory tf = TransformerFactory.newInstance();
+ Transformer transformer;
+ transformer = tf.newTransformer();
+ transformer.transform(domSource, result);
+ pdpResponse.setConfig(writer.toString());
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ e);
+ throw new PDPException(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the XML config", e);
}
+ } else if (pdpConfigLocation.endsWith("properties")) {
+ pdpResponse.setType(PolicyType.PROPERTIES);
+ Properties configProp = new Properties();
+ configProp.load(inputStream);
+ Map<String, String> propVal = new HashMap<>();
+ for(String name: configProp.stringPropertyNames()) {
+ propVal.put(name, configProp.getProperty(name));
+ }
+ pdpResponse.setProperty(propVal);
+ } else if (pdpConfigLocation.endsWith("txt")) {
+ pdpResponse.setType(PolicyType.OTHER);
+ String other = IOUtils.toString(inputStream);
+ IOUtils.closeQuietly(inputStream);
+ pdpResponse.setConfig(other);
+ } else {
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config Not Found");
+ pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
+ pdpResponse.setPolicyConfigMessage("Illegal form of Configuration Type Found.");
+ return pdpResponse;
}
+ LOGGER.info("config Retrieved " + pdpConfigLocation);
+ pdpResponse.setStatus("Config Retrieved! ",
+ PolicyResponseStatus.NO_ACTION_REQUIRED,
+ PolicyConfigStatus.CONFIG_RETRIEVED);
+ return pdpResponse;
} catch (FileNotFoundException e) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
throw new PDPException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in ConfigURL", e);
- }finally{
- if(inputStream != null){
- inputStream.close();
- }
+ } catch (IOException | ParserConfigurationException e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
+ throw new PDPException(XACMLErrorConstants.ERROR_PROCESS_FLOW +
+ "Cannot open a connection to the configURL", e);
}
}
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRest.java b/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRest.java
index 0912515e0..7cced5667 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRest.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRest.java
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 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.
@@ -44,174 +45,176 @@ import com.att.research.xacml.util.XACMLProperties;
*
*/
public class XACMLRest {
- private static final Log logger = LogFactory.getLog(XACMLRest.class);
- private static Properties restProperties = new Properties();
+ private static final Log logger = LogFactory.getLog(XACMLRest.class);
+ private static Properties restProperties = new Properties();
- private XACMLRest(){
- // Empty constructor
+ private XACMLRest(){
+ // Empty constructor
+ }
+ /**
+ * This must be called during servlet initialization. It sets up the xacml.?.properties
+ * file as a system property. If the System property is already set, then it does not
+ * do anything. This allows the developer to specify their own xacml.properties file to be
+ * used. They can 1) modify the default properties that comes with the project, or 2) change
+ * the WebInitParam annotation, or 3) specify an alternative path in the web.xml, or 4) set
+ * the Java System property to point to their xacml.properties file.
+ *
+ * The recommended way of overriding the default xacml.properties file is using a Java System
+ * property:
+ *
+ * -Dxacml.properties=/opt/app/xacml/etc/xacml.admin.properties
+ *
+ * This way one does not change any actual code or files in the project and can leave the
+ * defaults alone.
+ *
+ * @param config - The servlet config file passed from the javax servlet init() function
+ */
+ public static void xacmlInit(ServletConfig config) {
+ //
+ // Get the XACML Properties File parameter first
+ //
+ String propFile = config.getInitParameter("XACML_PROPERTIES_NAME");
+ if (propFile != null) {
+ //
+ // Look for system override
+ //
+ String xacmlPropertiesName = System.getProperty(XACMLProperties.XACML_PROPERTIES_NAME);
+ logger.info("\n\n" + xacmlPropertiesName + "\n" + XACMLProperties.XACML_PROPERTIES_NAME);
+ if (xacmlPropertiesName == null) {
+ //
+ // Set it to our servlet default
+ //
+ if (logger.isDebugEnabled()) {
+ logger.debug("Using Servlet Config Property for XACML_PROPERTIES_NAME:" + propFile);
+ }
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, propFile);
+ } else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Using System Property for XACML_PROPERTIES_NAME:" + xacmlPropertiesName);
+ }
+ }
+ }
+ //
+ // Setup the remaining properties
+ //
+ Enumeration<String> params = config.getInitParameterNames();
+ while (params.hasMoreElements()) {
+ String param = params.nextElement();
+ if (! "XACML_PROPERTIES_NAME".equals(param)) {
+ String value = config.getInitParameter(param);
+ PolicyLogger.info(param + "=" + config.getInitParameter(param));
+ restProperties.setProperty(param, value);
+ }
+ }
+ }
+
+ /**
+ * Reset's the XACMLProperties internal properties object so we start
+ * in a fresh environment. Then adds back in our Servlet init properties that were
+ * passed in the javax Servlet init() call.
+ *
+ * This function is primarily used when a new configuration is passed in and the
+ * PDP servlet needs to load a new PDP engine instance.
+ *
+ * @param pipProperties - PIP configuration properties
+ * @param policyProperties - Policy configuration properties
+ */
+ public static void loadXacmlProperties(Properties policyProperties, Properties pipProperties) {
+ try {
+ //
+ // Start fresh
+ //
+ XACMLProperties.reloadProperties();
+ //
+ // Now load our init properties
+ //
+ XACMLProperties.getProperties().putAll(XACMLRest.restProperties);
+ //
+ // Load our policy properties
+ //
+ if (policyProperties != null) {
+ XACMLProperties.getProperties().putAll(policyProperties);
+ }
+ //
+ // Load our pip config properties
+ //
+ if (pipProperties != null) {
+ XACMLProperties.getProperties().putAll(pipProperties);
+ }
+ } catch (IOException e) {
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Failed to put init properties into Xacml properties");
+ }
+ //
+ // Dump them
+ //
+ if (logger.isDebugEnabled()) {
+ try {
+ logger.debug(XACMLProperties.getProperties().toString());
+ } catch (IOException e) {
+ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Cannot dump properties");
+ }
+ }
+ }
+
+ /**
+ * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging.
+ *
+ * @param request - Servlet request (from a POST/GET/PUT/etc.)
+ */
+ public static void dumpRequest(HttpServletRequest request) {
+ if (!logger.isDebugEnabled()) {
+ return;
+ }
+
+ // special-case for receiving heartbeat - don't need to repeatedly output all of the information in multiple lines
+ if ("GET".equals(request.getMethod()) && "hb".equals(request.getParameter("type")) ) {
+ PolicyLogger.debug("GET type=hb : heartbeat received");
+ return;
+ }
+ logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " " + request.getRemotePort());
+ logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort());
+ Enumeration<String> en = request.getHeaderNames();
+ logger.debug("Headers:");
+ while (en.hasMoreElements()) {
+ String element = en.nextElement();
+ Enumeration<String> values = request.getHeaders(element);
+ while (values.hasMoreElements()) {
+ String value = values.nextElement();
+ logger.debug(element + ":" + value);
+ }
+ }
+ logger.debug("Attributes:");
+ en = request.getAttributeNames();
+ while (en.hasMoreElements()) {
+ String element = en.nextElement();
+ logger.debug(element + ":" + request.getAttribute(element));
+ }
+ logger.debug("ContextPath: " + request.getContextPath());
+ if ("PUT".equals(request.getMethod()) || "POST".equals(request.getMethod())) {
+ // POST and PUT are allowed to have parameters in the content, but in our usage the parameters are always in the Query string.
+ // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g. it might contain a Policy file).
+ // Unfortunately the request.getParameterMap method reads the content to see if there are any parameters,
+ // and once the content is read it cannot be read again.
+ // Thus for PUT and POST we must avoid reading the content here so that the main code can read it.
+ logger.debug("Query String:" + request.getQueryString());
+ try {
+ if (request.getInputStream() == null) {
+ logger.debug("Content: No content inputStream");
+ } else {
+ logger.debug("Content available: " + request.getInputStream().available());
+ }
+ } catch (Exception e) {
+ logger.debug("Content: inputStream exception: " + e.getMessage() + "; (May not be relevant)" +e);
+ }
+ } else {
+ logger.debug("Parameters:");
+ Map<String, String[]> params = request.getParameterMap();
+ Set<String> keys = params.keySet();
+ for (String key : keys) {
+ String[] values = params.get(key);
+ logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : ""));
+ }
+ }
+ logger.debug("Request URL:" + request.getRequestURL());
}
- /**
- * This must be called during servlet initialization. It sets up the xacml.?.properties
- * file as a system property. If the System property is already set, then it does not
- * do anything. This allows the developer to specify their own xacml.properties file to be
- * used. They can 1) modify the default properties that comes with the project, or 2) change
- * the WebInitParam annotation, or 3) specify an alternative path in the web.xml, or 4) set
- * the Java System property to point to their xacml.properties file.
- *
- * The recommended way of overriding the default xacml.properties file is using a Java System
- * property:
- *
- * -Dxacml.properties=/opt/app/xacml/etc/xacml.admin.properties
- *
- * This way one does not change any actual code or files in the project and can leave the
- * defaults alone.
- *
- * @param config - The servlet config file passed from the javax servlet init() function
- */
- public static void xacmlInit(ServletConfig config) {
- //
- // Get the XACML Properties File parameter first
- //
- String propFile = config.getInitParameter("XACML_PROPERTIES_NAME");
- if (propFile != null) {
- //
- // Look for system override
- //
- String xacmlPropertiesName = System.getProperty(XACMLProperties.XACML_PROPERTIES_NAME);
- logger.info("\n\n" + xacmlPropertiesName + "\n" + XACMLProperties.XACML_PROPERTIES_NAME);
- if (xacmlPropertiesName == null) {
- //
- // Set it to our servlet default
- //
- if (logger.isDebugEnabled()) {
- logger.debug("Using Servlet Config Property for XACML_PROPERTIES_NAME:" + propFile);
- }
- System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, propFile);
- } else {
- if (logger.isDebugEnabled()) {
- logger.debug("Using System Property for XACML_PROPERTIES_NAME:" + xacmlPropertiesName);
- }
- }
- }
- //
- // Setup the remaining properties
- //
- Enumeration<String> params = config.getInitParameterNames();
- while (params.hasMoreElements()) {
- String param = params.nextElement();
- if (! "XACML_PROPERTIES_NAME".equals(param)) {
- String value = config.getInitParameter(param);
- PolicyLogger.info(param + "=" + config.getInitParameter(param));
- restProperties.setProperty(param, value);
- }
- }
- }
-
- /**
- * Reset's the XACMLProperties internal properties object so we start
- * in a fresh environment. Then adds back in our Servlet init properties that were
- * passed in the javax Servlet init() call.
- *
- * This function is primarily used when a new configuration is passed in and the
- * PDP servlet needs to load a new PDP engine instance.
- *
- * @param pipProperties - PIP configuration properties
- * @param policyProperties - Policy configuration properties
- */
- public static void loadXacmlProperties(Properties policyProperties, Properties pipProperties) {
- try {
- //
- // Start fresh
- //
- XACMLProperties.reloadProperties();
- //
- // Now load our init properties
- //
- XACMLProperties.getProperties().putAll(XACMLRest.restProperties);
- //
- // Load our policy properties
- //
- if (policyProperties != null) {
- XACMLProperties.getProperties().putAll(policyProperties);
- }
- //
- // Load our pip config properties
- //
- if (pipProperties != null) {
- XACMLProperties.getProperties().putAll(pipProperties);
- }
- } catch (IOException e) {
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Failed to put init properties into Xacml properties");
- }
- //
- // Dump them
- //
- if (logger.isDebugEnabled()) {
- try {
- logger.debug(XACMLProperties.getProperties().toString());
- } catch (IOException e) {
- PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Cannot dump properties");
- }
- }
- }
-
- /**
- * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging.
- *
- * @param request - Servlet request (from a POST/GET/PUT/etc.)
- */
- public static void dumpRequest(HttpServletRequest request) {
- if (logger.isDebugEnabled()) {
- // special-case for receiving heartbeat - don't need to repeatedly output all of the information in multiple lines
- if ("GET".equals(request.getMethod()) && "hb".equals(request.getParameter("type")) ) {
- PolicyLogger.debug("GET type=hb : heartbeat received");
- return;
- }
- logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " " + request.getRemotePort());
- logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort());
- Enumeration<String> en = request.getHeaderNames();
- logger.debug("Headers:");
- while (en.hasMoreElements()) {
- String element = en.nextElement();
- Enumeration<String> values = request.getHeaders(element);
- while (values.hasMoreElements()) {
- String value = values.nextElement();
- logger.debug(element + ":" + value);
- }
- }
- logger.debug("Attributes:");
- en = request.getAttributeNames();
- while (en.hasMoreElements()) {
- String element = en.nextElement();
- logger.debug(element + ":" + request.getAttribute(element));
- }
- logger.debug("ContextPath: " + request.getContextPath());
- if ("PUT".equals(request.getMethod()) || "POST".equals(request.getMethod())) {
- // POST and PUT are allowed to have parameters in the content, but in our usage the parameters are always in the Query string.
- // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g. it might contain a Policy file).
- // Unfortunately the request.getParameterMap method reads the content to see if there are any parameters,
- // and once the content is read it cannot be read again.
- // Thus for PUT and POST we must avoid reading the content here so that the main code can read it.
- logger.debug("Query String:" + request.getQueryString());
- try {
- if (request.getInputStream() == null) {
- logger.debug("Content: No content inputStream");
- } else {
- logger.debug("Content available: " + request.getInputStream().available());
- }
- } catch (Exception e) {
- logger.debug("Content: inputStream exception: " + e.getMessage() + "; (May not be relevant)" +e);
- }
- } else {
- logger.debug("Parameters:");
- Map<String, String[]> params = request.getParameterMap();
- Set<String> keys = params.keySet();
- for (String key : keys) {
- String[] values = params.get(key);
- logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : ""));
- }
- }
- logger.debug("Request URL:" + request.getRequestURL());
- }
- }
}
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Category.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Category.java
index 275b03e5a..f3874a480 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Category.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Category.java
@@ -3,6 +3,7 @@
* ONAP-REST
* ================================================================================
* Copyright (C) 2017 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.
@@ -48,171 +49,171 @@ import com.fasterxml.jackson.annotation.JsonBackReference;
@Table(name="Category")
@NamedQuery(name="Category.findAll", query="SELECT c FROM Category c")
public class Category implements Serializable {
- private static final long serialVersionUID = 1L;
-
- public static final char STANDARD = 'S';
- public static final char CUSTOM = 'C';
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name="id")
- private int id;
-
- @Column(name="grouping", nullable=false, length=64)
- private String grouping;
-
- @Column(name="is_standard", nullable=false)
- private char isStandard;
-
- @Column(name="xacml_id", nullable=false, unique=true, length=255)
- private String xacmlId;
-
- @Column(name="short_name", nullable=false, length=64)
- private String shortName;
-
- //bi-directional many-to-one association to Attribute
- @OneToMany(mappedBy="categoryBean")
- @JsonBackReference
- private Set<Attribute> attributes = new HashSet<>();
-
- public Category() {
- this.xacmlId = XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue();
- this.grouping = "subject";
- this.isStandard = Category.STANDARD;
- this.shortName = "subject";
- }
-
- public Category(Identifier cat, String grouping, char isStandard) {
- if (cat != null) {
- this.xacmlId = cat.stringValue();
- }
- this.isStandard = isStandard;
- if (grouping != null) {
- this.grouping = grouping;
- } else {
- this.grouping = Category.extractGrouping(this.xacmlId);
- }
- }
-
- public Category(Identifier cat, String grouping) {
- this(cat, grouping, Category.STANDARD);
- }
-
- public Category(Identifier cat, char standard) {
- this(cat, null, standard);
- }
-
- public Category(Identifier cat) {
- this(cat, Category.STANDARD);
- }
-
- public int getId() {
- return this.id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getGrouping() {
- return this.grouping;
- }
-
- public void setGrouping(String grouping) {
- this.grouping = grouping;
- }
-
- public char getIsStandard() {
- return this.isStandard;
- }
-
- public void setIsStandard(char isStandard) {
- this.isStandard = isStandard;
- }
-
- public String getXacmlId() {
- return this.xacmlId;
- }
-
- public void setXacmlId(String xacmlId) {
- this.xacmlId = xacmlId;
- }
-
- public String getShortName() {
- return this.shortName;
- }
-
- public void setShortName(String shortName) {
- this.shortName = shortName;
- }
-
- public Set<Attribute> getAttributes() {
- return this.attributes;
- }
-
- public void setAttributes(Set<Attribute> attributes) {
- this.attributes = attributes;
- }
-
- public Attribute addAttribute(Attribute attribute) {
- getAttributes().add(attribute);
- attribute.setCategoryBean(this);
-
- return attribute;
- }
-
- public Attribute removeAttribute(Attribute attribute) {
- getAttributes().remove(attribute);
- attribute.setCategoryBean(null);
-
- return attribute;
- }
-
- @Transient
- public boolean isStandard() {
- return this.isStandard == Category.STANDARD;
- }
-
- @Transient
- public boolean isCustom() {
- return this.isStandard == Category.CUSTOM;
- }
-
- @Transient
- public static String extractGrouping(String xacmlId) {
- if (xacmlId == null) {
- return null;
- }
- if (xacmlId.matches(".*:attribute\\-category:.*")) {
- String[] parts = xacmlId.split("[:]");
- if (parts != null && parts.length > 0) {
- return parts[parts.length - 1];
- }
- } else if (xacmlId.matches(".*:[a-zA-Z]+[\\-]category:.*")) {
- String[] parts = xacmlId.split("[:]");
- if (parts != null && parts.length > 0) {
- for (String part : parts) {
- int index = part.indexOf("-category");
- if (index > 0) {
- return part.substring(0, index);
- }
- }
- }
- }
- return null;
- }
-
- @Transient
- public Identifier getIdentifer() {
- return new IdentifierImpl(this.xacmlId);
- }
-
- @Transient
- @Override
- public String toString() {
- return "Category [id=" + id + ", grouping=" + grouping
- + ", isStandard=" + isStandard + ", xacmlId=" + xacmlId
- + ", attributes=" + attributes + "]";
- }
+ private static final long serialVersionUID = 1L;
+
+ public static final char STANDARD = 'S';
+ public static final char CUSTOM = 'C';
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @Column(name="id")
+ private int id;
+
+ @Column(name="grouping", nullable=false, length=64)
+ private String grouping;
+
+ @Column(name="is_standard", nullable=false)
+ private char isStandard;
+
+ @Column(name="xacml_id", nullable=false, unique=true, length=255)
+ private String xacmlId;
+
+ @Column(name="short_name", nullable=false, length=64)
+ private String shortName;
+
+ //bi-directional many-to-one association to Attribute
+ @OneToMany(mappedBy="categoryBean")
+ @JsonBackReference
+ private Set<Attribute> attributes = new HashSet<>();
+
+ public Category() {
+ this.xacmlId = XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue();
+ this.grouping = "subject";
+ this.isStandard = Category.STANDARD;
+ this.shortName = "subject";
+ }
+
+ public Category(Identifier cat, String grouping, char isStandard) {
+ if (cat != null) {
+ this.xacmlId = cat.stringValue();
+ }
+ this.isStandard = isStandard;
+ if (grouping != null) {
+ this.grouping = grouping;
+ } else {
+ this.grouping = Category.extractGrouping(this.xacmlId);
+ }
+ }
+
+ public Category(Identifier cat, String grouping) {
+ this(cat, grouping, Category.STANDARD);
+ }
+
+ public Category(Identifier cat, char standard) {
+ this(cat, null, standard);
+ }
+
+ public Category(Identifier cat) {
+ this(cat, Category.STANDARD);
+ }
+
+ public int getId() {
+ return this.id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getGrouping() {
+ return this.grouping;
+ }
+
+ public void setGrouping(String grouping) {
+ this.grouping = grouping;
+ }
+
+ public char getIsStandard() {
+ return this.isStandard;
+ }
+
+ public void setIsStandard(char isStandard) {
+ this.isStandard = isStandard;
+ }
+
+ public String getXacmlId() {
+ return this.xacmlId;
+ }
+
+ public void setXacmlId(String xacmlId) {
+ this.xacmlId = xacmlId;
+ }
+
+ public String getShortName() {
+ return this.shortName;
+ }
+
+ public void setShortName(String shortName) {
+ this.shortName = shortName;
+ }
+
+ public Set<Attribute> getAttributes() {
+ return this.attributes;
+ }
+
+ public void setAttributes(Set<Attribute> attributes) {
+ this.attributes = attributes;
+ }
+
+ public Attribute addAttribute(Attribute attribute) {
+ getAttributes().add(attribute);
+ attribute.setCategoryBean(this);
+
+ return attribute;
+ }
+
+ public Attribute removeAttribute(Attribute attribute) {
+ getAttributes().remove(attribute);
+ attribute.setCategoryBean(null);
+
+ return attribute;
+ }
+
+ @Transient
+ public boolean isStandard() {
+ return this.isStandard == Category.STANDARD;
+ }
+
+ @Transient
+ public boolean isCustom() {
+ return this.isStandard == Category.CUSTOM;
+ }
+
+ @Transient
+ public static String extractGrouping(String xacmlId) {
+ if (xacmlId == null) {
+ return null;
+ }
+ String[] parts = xacmlId.split("[:]");
+ if (xacmlId.matches(".*:attribute\\-category:.*")) {
+ if (parts.length > 0) {
+ return parts[parts.length - 1];
+ }
+ } else if (xacmlId.matches(".*:[a-zA-Z]+[\\-]category:.*")) {
+ if (parts.length <= 0) {
+ return null;
+ }
+ for (String part : parts) {
+ int index = part.indexOf("-category");
+ if (index > 0) {
+ return part.substring(0, index);
+ }
+ }
+ }
+ return null;
+ }
+
+ @Transient
+ public Identifier getIdentifer() {
+ return new IdentifierImpl(this.xacmlId);
+ }
+
+ @Transient
+ @Override
+ public String toString() {
+ return "Category [id=" + id + ", grouping=" + grouping
+ + ", isStandard=" + isStandard + ", xacmlId=" + xacmlId
+ + ", attributes=" + attributes + "]";
+ }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
index 8a3d27890..be660c803 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
@@ -43,9 +43,6 @@ public class PolicyAdapter {
private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class);
public void configure(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- if(extendedOptions(policyAdapter, entity)){
- return;
- }
String policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
String configPolicyName = getConfigPolicyName(policyAdapter);
policyAdapter.setPolicyType(policyNameValue);
@@ -116,10 +113,6 @@ public class PolicyAdapter {
}
}
- private boolean extendedOptions(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- return false;
- }
-
public static PolicyAdapter getInstance() {
try {
Class<?> policyAdapter = Class.forName(XACMLProperties.getProperty("policyAdapter.impl.className", PolicyAdapter.class.getName()));
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
index d94274242..de83b045b 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
@@ -93,6 +93,13 @@ import com.fasterxml.jackson.databind.ObjectMapper;
public class PolicyManagerServlet extends HttpServlet {
private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
private static final long serialVersionUID = -8453502699403909016L;
+ private static final String VERSION = "version";;
+ private static final String NAME = "name";
+ private static final String DATE = "date";
+ private static final String SIZE = "size";
+ private static final String TYPE = "type";
+ private static final String CREATED_BY = "createdBy";
+ private static final String MODIFIED_BY = "modifiedBy";
private enum Mode {
LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
@@ -207,7 +214,6 @@ public class PolicyManagerServlet extends HttpServlet {
//Policy Import Functionality
private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
- String newFile;
Map<String, InputStream> files = new HashMap<>();
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
@@ -385,13 +391,13 @@ public class PolicyManagerServlet extends HttpServlet {
for(int i =0; i < policyData.size(); i++){
PolicyVersion policy = (PolicyVersion) policyData.get(i);
JSONObject el = new JSONObject();
- el.put("name", policy.getPolicyName().replace(File.separator, "/"));
- el.put("date", policy.getModifiedDate());
- el.put("version", policy.getActiveVersion());
- el.put("size", "");
- el.put("type", "file");
- el.put("createdBy", getUserName(policy.getCreatedBy()));
- el.put("modifiedBy", getUserName(policy.getModifiedBy()));
+ el.put(NAME, policy.getPolicyName().replace(File.separator, "/"));
+ el.put(DATE, policy.getModifiedDate());
+ el.put(VERSION, policy.getActiveVersion());
+ el.put(SIZE, "");
+ el.put(TYPE, "file");
+ el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
+ el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
resultList.add(el);
}
}
@@ -403,18 +409,18 @@ public class PolicyManagerServlet extends HttpServlet {
String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
SimpleBindings pvParams = new SimpleBindings();
pvParams.put("policyName", policyName);
- pvParams.put("version", version);
+ pvParams.put(VERSION, version);
List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
if(!activeData.isEmpty()){
PolicyVersion policy = (PolicyVersion) activeData.get(0);
JSONObject el = new JSONObject();
- el.put("name", policy.getPolicyName().replace(File.separator, "/"));
- el.put("date", policy.getModifiedDate());
- el.put("version", policy.getActiveVersion());
- el.put("size", "");
- el.put("type", "file");
- el.put("createdBy", getUserName(policy.getCreatedBy()));
- el.put("modifiedBy", getUserName(policy.getModifiedBy()));
+ el.put(NAME, policy.getPolicyName().replace(File.separator, "/"));
+ el.put(DATE, policy.getModifiedDate());
+ el.put(VERSION, policy.getActiveVersion());
+ el.put(SIZE, "");
+ el.put(TYPE, "file");
+ el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
+ el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
resultList.add(el);
}
}
@@ -602,12 +608,12 @@ public class PolicyManagerServlet extends HttpServlet {
PolicyEditorScopes scope = (PolicyEditorScopes) list;
if(!(scope.getScopeName().contains(File.separator))){
JSONObject el = new JSONObject();
- el.put("name", scope.getScopeName());
- el.put("date", scope.getModifiedDate());
- el.put("size", "");
- el.put("type", "dir");
- el.put("createdBy", scope.getUserCreatedBy().getUserName());
- el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
+ el.put(NAME, scope.getScopeName());
+ el.put(DATE, scope.getModifiedDate());
+ el.put(SIZE, "");
+ el.put(TYPE, "dir");
+ el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
+ el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
resultList.add(el);
}
}
@@ -617,12 +623,12 @@ public class PolicyManagerServlet extends HttpServlet {
List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
if(!scopesList.isEmpty()){
PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
- el.put("name", scopeById.getScopeName());
- el.put("date", scopeById.getModifiedDate());
- el.put("size", "");
- el.put("type", "dir");
- el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
- el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
+ el.put(NAME, scopeById.getScopeName());
+ el.put(DATE, scopeById.getModifiedDate());
+ el.put(SIZE, "");
+ el.put(TYPE, "dir");
+ el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
+ el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
resultList.add(el);
}
}
@@ -703,12 +709,12 @@ public class PolicyManagerServlet extends HttpServlet {
}
if(scopeName.equalsIgnoreCase(checkScope)){
JSONObject el = new JSONObject();
- el.put("name", scope);
- el.put("date", scopeById.getModifiedDate());
- el.put("size", "");
- el.put("type", "dir");
- el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
- el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
+ el.put(NAME, scope);
+ el.put(DATE, scopeById.getModifiedDate());
+ el.put(SIZE, "");
+ el.put(TYPE, "dir");
+ el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
+ el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
resultList.add(el);
}
}
@@ -725,24 +731,24 @@ public class PolicyManagerServlet extends HttpServlet {
}
if(scopeNameValue.equals(scopeNameCheck)){
JSONObject el = new JSONObject();
- el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
- el.put("date", policy.getModifiedDate());
- el.put("version", policy.getActiveVersion());
- el.put("size", "");
- el.put("type", "file");
- el.put("createdBy", getUserName(policy.getCreatedBy()));
- el.put("modifiedBy", getUserName(policy.getModifiedBy()));
+ el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
+ el.put(DATE, policy.getModifiedDate());
+ el.put(VERSION, policy.getActiveVersion());
+ el.put(SIZE, "");
+ el.put(TYPE, "file");
+ el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
+ el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
resultList.add(el);
}
}else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
JSONObject el = new JSONObject();
- el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
- el.put("date", policy.getModifiedDate());
- el.put("version", policy.getActiveVersion());
- el.put("size", "");
- el.put("type", "file");
- el.put("createdBy", getUserName(policy.getCreatedBy()));
- el.put("modifiedBy", getUserName(policy.getModifiedBy()));
+ el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
+ el.put(DATE, policy.getModifiedDate());
+ el.put(VERSION, policy.getActiveVersion());
+ el.put(SIZE, "");
+ el.put(TYPE, "file");
+ el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
+ el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
resultList.add(el);
}
}
@@ -1496,10 +1502,10 @@ public class PolicyManagerServlet extends HttpServlet {
name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
}
}else{
- name = params.getString("name");
+ name = params.getString(NAME);
}
}catch(Exception e){
- name = params.getString("name");
+ name = params.getString(NAME);
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
}
String validateName;
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java
index d2c5a3ba7..c791910ad 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java
@@ -3,6 +3,7 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017 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.
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
index b908c75d9..2a52335e5 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
@@ -298,15 +298,12 @@ public class PolicyRestController extends RestrictedBaseController{
Object obj = mapper1.treeToValue(root, Object.class);
String json = mapper1.writeValueAsString(obj);
- Object content = new ByteArrayInputStream(json.getBytes());
-
- if (content instanceof InputStream) {
- // send current configuration
- try (OutputStream os = connection.getOutputStream()) {
- int count = IOUtils.copy((InputStream) content, os);
- if (policyLogger.isDebugEnabled()) {
- policyLogger.debug("copied to output, bytes=" + count);
- }
+ // send current configuration
+ try(InputStream content = new ByteArrayInputStream(json.getBytes());
+ OutputStream os = connection.getOutputStream()) {
+ int count = IOUtils.copy(content, os);
+ if (policyLogger.isDebugEnabled()) {
+ policyLogger.debug("copied to output, bytes=" + count);
}
}
}else{
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
index ae473f34f..2200eae99 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
@@ -3,6 +3,7 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017-2018 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.
@@ -71,663 +72,659 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
@RequestMapping("/")
public class PolicyController extends RestrictedBaseController {
- private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class);
-
- private static CommonClassDao commonClassDao;
- //
- // The PAP Engine
- //
- private static PAPPolicyEngine papEngine;
-
- private static String logTableLimit;
- private static String systemAlertTableLimit;
- protected static Map<String, String> dropDownMap = new HashMap<>();
- public static Map<String, String> getDropDownMap() {
- return dropDownMap;
- }
-
- public static void setDropDownMap(Map<String, String> dropDownMap) {
- PolicyController.dropDownMap = dropDownMap;
- }
-
- public static String getDomain() {
- return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
- }
-
- private static final Object mapAccess = new Object();
- private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
- private static Map<String, FunctionDefinition> mapID2Function = null;
-
- //Constant variables used across Policy-sdk
- private static final String policyData = "policyData";
- private static final String characterEncoding = "UTF-8";
- private static final String contentType = "application/json";
- private static final String file = "file";
-
- //Smtp Java Mail Properties
- private static String smtpHost = null;
- private static String smtpPort = null;
- private static String smtpUsername = null;
- private static String smtpPassword = null;
- private static String smtpApplicationName = null;
- private static String smtpEmailExtension = null;
- //log db Properties
- private static String logdbDriver = null;
- private static String logdbUrl = null;
- private static String logdbUserName = null;
- private static String logdbPassword = null;
- private static String logdbDialect = null;
- //Xacml db properties
- private static String xacmldbUrl = null;
- private static String xacmldbUserName = null;
- private static String xacmldbPassword = null;
-
- //AutoPush feature.
- private static String autoPushAvailable;
- private static String autoPushDSClosedLoop;
- private static String autoPushDSFirewall;
- private static String autoPushDSMicroservice;
- private static String autoPushPDPGroup;
-
- //papURL
- private static String papUrl;
-
- //MicroService Model Properties
- private static String msOnapName;
- private static String msPolicyName;
-
- //WebApp directories
- private static String configHome;
- private static String actionHome;
-
- //File upload size
- private static long fileSizeLimit;
-
- private static boolean jUnit = false;
-
-
- public static boolean isjUnit() {
- return jUnit;
- }
-
- public static void setjUnit(boolean jUnit) {
- PolicyController.jUnit = jUnit;
- }
-
- @Autowired
- private PolicyController(CommonClassDao commonClassDao){
- PolicyController.commonClassDao = commonClassDao;
- }
-
- public PolicyController() {
- // Empty constructor
- }
-
- @PostConstruct
- public void init(){
- Properties prop = new Properties();
- InputStream input = null;
- try {
- if(jUnit){
- File file = new File(new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "JSONConfig.json");
- input = new FileInputStream(file);
- }else{
- input = new FileInputStream("xacml.admin.properties");
- }
- // load a properties file
- prop.load(input);
- //file upload size limit property
- setFileSizeLimit(prop.getProperty("file.size.limit"));
- //pap url
- setPapUrl(prop.getProperty("xacml.rest.pap.url"));
- // get the property values
- setSmtpHost(prop.getProperty("onap.smtp.host"));
- setSmtpPort(prop.getProperty("onap.smtp.port"));
- setSmtpUsername(prop.getProperty("onap.smtp.userName"));
- setSmtpPassword(prop.getProperty("onap.smtp.password"));
- setSmtpApplicationName(prop.getProperty("onap.application.name"));
- setSmtpEmailExtension(prop.getProperty("onap.smtp.emailExtension"));
- //Log Database Properties
- setLogdbDriver(prop.getProperty("xacml.log.db.driver"));
- setLogdbUrl(prop.getProperty("xacml.log.db.url"));
- setLogdbUserName(prop.getProperty("xacml.log.db.user"));
- setLogdbPassword(prop.getProperty("xacml.log.db.password"));
- setLogdbDialect(prop.getProperty("onap.dialect"));
- //Xacml Database Properties
- setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url"));
- setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user"));
- setXacmldbPassword(prop.getProperty("javax.persistence.jdbc.password"));
- //AutoPuh
- setAutoPushAvailable(prop.getProperty("xacml.automatic.push"));
- setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop"));
- setAutoPushDSFirewall(prop.getProperty("xacml.autopush.firewall"));
- setAutoPushDSMicroservice(prop.getProperty("xacml.autopush.microservice"));
- setAutoPushPDPGroup(prop.getProperty("xacml.autopush.pdpGroup"));
- //Micro Service Properties
- setMsOnapName(prop.getProperty("xacml.policy.msOnapName"));
- if(getMsOnapName() == null){
- setMsOnapName(prop.getProperty("xacml.policy.msEcompName"));
- }
- policyLogger.info("getMsOnapName => " + getMsOnapName());
- setMsPolicyName(prop.getProperty("xacml.policy.msPolicyName"));
- policyLogger.info("setMsPolicyName => " + getMsPolicyName());
- //WebApp directories
- setConfigHome(prop.getProperty("xacml.rest.config.webapps") + "Config");
- setActionHome(prop.getProperty("xacml.rest.config.webapps") + "Action");
- //Get the Property Values for Dashboard tab Limit
- try{
- setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit"));
- setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
- }catch(Exception e){
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e);
- setLogTableLimit("5000");
- setSystemAlertTableLimit("2000");
- }
- System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
- } catch (IOException ex) {
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex);
- } finally {
- if (input != null) {
- try {
- input.close();
- } catch (IOException e) {
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e);
- }
- }
- }
-
- //Initialize the FunctionDefinition table at Server Start up
- Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
- for ( Entry<Datatype, List<FunctionDefinition>> entry : functionMap.entrySet()) {
- List<FunctionDefinition> functionDefinations = entry.getValue();
- for (FunctionDefinition functionDef : functionDefinations) {
- dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
- }
- }
-
- }
-
- public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() {
- synchronized(mapAccess) {
- if (mapDatatype2Function == null) {
- buildFunctionMaps();
- }
- }
- return mapDatatype2Function;
- }
-
- public static Map<String, FunctionDefinition> getFunctionIDMap() {
- synchronized(mapAccess) {
- if (mapID2Function == null) {
- buildFunctionMaps();
- }
- }
- return mapID2Function;
- }
-
- private static void buildFunctionMaps() {
- mapDatatype2Function = new HashMap<>();
- mapID2Function = new HashMap<>();
- List<Object> functiondefinitions = commonClassDao.getData(FunctionDefinition.class);
- for (int i = 0; i < functiondefinitions.size(); i ++) {
- FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
- mapID2Function.put(value.getXacmlid(), value);
- if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) {
- mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
- }
- mapDatatype2Function.get(value.getDatatypeBean()).add(value);
- }
- }
-
- @RequestMapping(value={"/get_FunctionDefinitionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response){
- try{
- Map<String, Object> model = new HashMap<>();
- ObjectMapper mapper = new ObjectMapper();
- model.put("functionDefinitionDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- }
- catch (Exception e){
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e);
- }
- }
-
- public PolicyEntity getPolicyEntityData(String scope, String policyName){
- String key = scope + ":" + policyName;
- List<Object> data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key);
- return (PolicyEntity) data.get(0);
- }
-
- public static Map<String, Roles> getUserRoles(String userId) {
- Map<String, Roles> scopes = new HashMap<>();
- List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
- if (roles != null && !roles.isEmpty()) {
- for (Object role : roles) {
- scopes.put(((Roles) role).getScope(), (Roles) role);
- }
- }
- return scopes;
- }
-
- public List<String> getRolesOfUser(String userId) {
- List<String> rolesList = new ArrayList<>();
- List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
- for (Object role: roles) {
- rolesList.add(((Roles) role).getRole());
- }
- return rolesList;
- }
-
- public List<Object> getRoles(String userId) {
- return commonClassDao.getDataById(Roles.class, "loginId", userId);
- }
-
- //Get List of User Roles
- @RequestMapping(value={"/get_UserRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response){
- try{
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- Map<String, Object> model = new HashMap<>();
- ObjectMapper mapper = new ObjectMapper();
- model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- }
- catch (Exception e){
- policyLogger.error("Exception Occured"+e);
- }
- }
-
- //Policy tabs Model and View
+ private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class);
+
+ private static CommonClassDao commonClassDao;
+ //
+ // The PAP Engine
+ //
+ private static PAPPolicyEngine papEngine;
+
+ private static String logTableLimit;
+ private static String systemAlertTableLimit;
+ protected static Map<String, String> dropDownMap = new HashMap<>();
+ public static Map<String, String> getDropDownMap() {
+ return dropDownMap;
+ }
+
+ public static void setDropDownMap(Map<String, String> dropDownMap) {
+ PolicyController.dropDownMap = dropDownMap;
+ }
+
+ public static String getDomain() {
+ return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
+ }
+
+ private static final Object mapAccess = new Object();
+ private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
+ private static Map<String, FunctionDefinition> mapID2Function = null;
+
+ //Constant variables used across Policy-sdk
+ private static final String policyData = "policyData";
+ private static final String characterEncoding = "UTF-8";
+ private static final String contentType = "application/json";
+ private static final String file = "file";
+
+ //Smtp Java Mail Properties
+ private static String smtpHost = null;
+ private static String smtpPort = null;
+ private static String smtpUsername = null;
+ private static String smtpPassword = null;
+ private static String smtpApplicationName = null;
+ private static String smtpEmailExtension = null;
+ //log db Properties
+ private static String logdbDriver = null;
+ private static String logdbUrl = null;
+ private static String logdbUserName = null;
+ private static String logdbPassword = null;
+ private static String logdbDialect = null;
+ //Xacml db properties
+ private static String xacmldbUrl = null;
+ private static String xacmldbUserName = null;
+ private static String xacmldbPassword = null;
+
+ //AutoPush feature.
+ private static String autoPushAvailable;
+ private static String autoPushDSClosedLoop;
+ private static String autoPushDSFirewall;
+ private static String autoPushDSMicroservice;
+ private static String autoPushPDPGroup;
+
+ //papURL
+ private static String papUrl;
+
+ //MicroService Model Properties
+ private static String msOnapName;
+ private static String msPolicyName;
+
+ //WebApp directories
+ private static String configHome;
+ private static String actionHome;
+
+ //File upload size
+ private static long fileSizeLimit;
+
+ private static boolean jUnit = false;
+
+
+ public static boolean isjUnit() {
+ return jUnit;
+ }
+
+ public static void setjUnit(boolean jUnit) {
+ PolicyController.jUnit = jUnit;
+ }
+
+ @Autowired
+ private PolicyController(CommonClassDao commonClassDao){
+ PolicyController.commonClassDao = commonClassDao;
+ }
+
+ public PolicyController() {
+ // Empty constructor
+ }
+
+ @PostConstruct
+ public void init(){
+ Properties prop = new Properties();
+
+ try {
+ String fileName;
+ if(jUnit){
+ fileName = new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "JSONConfig.json";
+ } else {
+ fileName = "xacml.admin.properties";
+ }
+
+ try(InputStream input = new FileInputStream(fileName)) {
+ // load a properties file
+ prop.load(input);
+ }
+
+ //file upload size limit property
+ setFileSizeLimit(prop.getProperty("file.size.limit"));
+ //pap url
+ setPapUrl(prop.getProperty("xacml.rest.pap.url"));
+ // get the property values
+ setSmtpHost(prop.getProperty("onap.smtp.host"));
+ setSmtpPort(prop.getProperty("onap.smtp.port"));
+ setSmtpUsername(prop.getProperty("onap.smtp.userName"));
+ setSmtpPassword(prop.getProperty("onap.smtp.password"));
+ setSmtpApplicationName(prop.getProperty("onap.application.name"));
+ setSmtpEmailExtension(prop.getProperty("onap.smtp.emailExtension"));
+ //Log Database Properties
+ setLogdbDriver(prop.getProperty("xacml.log.db.driver"));
+ setLogdbUrl(prop.getProperty("xacml.log.db.url"));
+ setLogdbUserName(prop.getProperty("xacml.log.db.user"));
+ setLogdbPassword(prop.getProperty("xacml.log.db.password"));
+ setLogdbDialect(prop.getProperty("onap.dialect"));
+ //Xacml Database Properties
+ setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url"));
+ setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user"));
+ setXacmldbPassword(prop.getProperty("javax.persistence.jdbc.password"));
+ //AutoPuh
+ setAutoPushAvailable(prop.getProperty("xacml.automatic.push"));
+ setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop"));
+ setAutoPushDSFirewall(prop.getProperty("xacml.autopush.firewall"));
+ setAutoPushDSMicroservice(prop.getProperty("xacml.autopush.microservice"));
+ setAutoPushPDPGroup(prop.getProperty("xacml.autopush.pdpGroup"));
+ //Micro Service Properties
+ setMsOnapName(prop.getProperty("xacml.policy.msOnapName"));
+ if(getMsOnapName() == null){
+ setMsOnapName(prop.getProperty("xacml.policy.msEcompName"));
+ }
+ policyLogger.info("getMsOnapName => " + getMsOnapName());
+ setMsPolicyName(prop.getProperty("xacml.policy.msPolicyName"));
+ policyLogger.info("setMsPolicyName => " + getMsPolicyName());
+ //WebApp directories
+ setConfigHome(prop.getProperty("xacml.rest.config.webapps") + "Config");
+ setActionHome(prop.getProperty("xacml.rest.config.webapps") + "Action");
+ //Get the Property Values for Dashboard tab Limit
+ try{
+ setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit"));
+ setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
+ }catch(Exception e){
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e);
+ setLogTableLimit("5000");
+ setSystemAlertTableLimit("2000");
+ }
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
+ } catch (IOException ex) {
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex);
+ }
+
+ //Initialize the FunctionDefinition table at Server Start up
+ Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
+ for ( Entry<Datatype, List<FunctionDefinition>> entry : functionMap.entrySet()) {
+ List<FunctionDefinition> functionDefinations = entry.getValue();
+ for (FunctionDefinition functionDef : functionDefinations) {
+ dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
+ }
+ }
+
+ }
+
+ public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() {
+ synchronized(mapAccess) {
+ if (mapDatatype2Function == null) {
+ buildFunctionMaps();
+ }
+ }
+ return mapDatatype2Function;
+ }
+
+ public static Map<String, FunctionDefinition> getFunctionIDMap() {
+ synchronized(mapAccess) {
+ if (mapID2Function == null) {
+ buildFunctionMaps();
+ }
+ }
+ return mapID2Function;
+ }
+
+ private static void buildFunctionMaps() {
+ mapDatatype2Function = new HashMap<>();
+ mapID2Function = new HashMap<>();
+ List<Object> functiondefinitions = commonClassDao.getData(FunctionDefinition.class);
+ for (int i = 0; i < functiondefinitions.size(); i ++) {
+ FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
+ mapID2Function.put(value.getXacmlid(), value);
+ if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) {
+ mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
+ }
+ mapDatatype2Function.get(value.getDatatypeBean()).add(value);
+ }
+ }
+
+ @RequestMapping(value={"/get_FunctionDefinitionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ Map<String, Object> model = new HashMap<>();
+ ObjectMapper mapper = new ObjectMapper();
+ model.put("functionDefinitionDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e);
+ }
+ }
+
+ public PolicyEntity getPolicyEntityData(String scope, String policyName){
+ String key = scope + ":" + policyName;
+ List<Object> data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key);
+ return (PolicyEntity) data.get(0);
+ }
+
+ public static Map<String, Roles> getUserRoles(String userId) {
+ Map<String, Roles> scopes = new HashMap<>();
+ List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
+ if (roles != null && !roles.isEmpty()) {
+ for (Object role : roles) {
+ scopes.put(((Roles) role).getScope(), (Roles) role);
+ }
+ }
+ return scopes;
+ }
+
+ public List<String> getRolesOfUser(String userId) {
+ List<String> rolesList = new ArrayList<>();
+ List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
+ for (Object role: roles) {
+ rolesList.add(((Roles) role).getRole());
+ }
+ return rolesList;
+ }
+
+ public List<Object> getRoles(String userId) {
+ return commonClassDao.getDataById(Roles.class, "loginId", userId);
+ }
+
+ //Get List of User Roles
+ @RequestMapping(value={"/get_UserRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
+ public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response){
+ try{
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ Map<String, Object> model = new HashMap<>();
+ ObjectMapper mapper = new ObjectMapper();
+ model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ }
+ catch (Exception e){
+ policyLogger.error("Exception Occured"+e);
+ }
+ }
+
+ //Policy tabs Model and View
@RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET)
- public ModelAndView view(HttpServletRequest request){
- String myRequestURL = request.getRequestURL().toString();
- try {
- //
- // Set the URL for the RESTful PAP Engine
- //
- setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
- new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
- } catch (Exception e) {
- policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e);
- }
- Map<String, Object> model = new HashMap<>();
- return new ModelAndView("policy_Editor","model", model);
- }
-
- public PAPPolicyEngine getPapEngine() {
- return papEngine;
- }
-
- public static void setPapEngine(PAPPolicyEngine papEngine) {
- PolicyController.papEngine = papEngine;
- }
-
- public String getUserName(String createdBy) {
- String loginId = createdBy;
- List<Object> data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId);
- return data.get(0).toString();
- }
-
- public static boolean getActivePolicy(String query) {
- if(!commonClassDao.getDataByQuery(query, new SimpleBindings()).isEmpty()){
- return true;
- }else{
- return false;
- }
- }
-
- public void executeQuery(String query) {
- commonClassDao.updateQuery(query);
- }
-
- public void saveData(Object cloneEntity) {
- commonClassDao.save(cloneEntity);
- }
-
- public void updateData(Object entity) {
- commonClassDao.update(entity);
- }
-
- public void deleteData(Object entity) {
- commonClassDao.delete(entity);
- }
-
- public List<Object> getData(@SuppressWarnings("rawtypes") Class className){
- return commonClassDao.getData(className);
- }
-
- public PolicyVersion getPolicyEntityFromPolicyVersion(String query){
- return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
- }
-
- public List<Object> getDataByQuery(String query, SimpleBindings params){
- return commonClassDao.getDataByQuery(query, params);
- }
-
-
- @SuppressWarnings("rawtypes")
- public Object getEntityItem(Class className, String columname, String key){
- return commonClassDao.getEntityItem(className, columname, key);
- }
-
-
- public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){
- PolicyNotificationMail email = new PolicyNotificationMail();
- try {
- email.sendMail(entity, policyName, mode, commonClassDao);
- } catch (MessagingException e) {
- policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
- }
- }
-
- //Switch Version
- public JSONObject switchVersionPolicyContent(String policyName) {
- String dbCheckName = policyName.replace("/", ".");
- if(dbCheckName.contains("Config_")){
- dbCheckName = dbCheckName.replace(".Config_", ":Config_");
- }else if(dbCheckName.contains("Action_")){
- dbCheckName = dbCheckName.replace(".Action_", ":Action_");
- }else if(dbCheckName.contains("Decision_")){
- dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
- }
- String[] splitDBCheckName = dbCheckName.split(":");
- String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
- SimpleBindings params = new SimpleBindings();
- params.put("splitDBCheckName1", splitDBCheckName[1] + "%");
- params.put("splitDBCheckName0", splitDBCheckName[0]);
- List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
- List<String> av = new ArrayList<>();
- for(Object entity : policyEntity){
- PolicyEntity pEntity = (PolicyEntity) entity;
- String removeExtension = pEntity.getPolicyName().replace(".xml", "");
- String version = removeExtension.substring(removeExtension.lastIndexOf('.')+1);
- av.add(version);
- }
- if(policyName.contains("/")){
- policyName = policyName.replace("/", File.separator);
- }
- PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName);
- JSONObject el = new JSONObject();
- el.put("activeVersion", entity.getActiveVersion());
- el.put("availableVersions", av);
- el.put("highestVersion", entity.getHigherVersion());
- return el;
- }
-
- public static String getLogTableLimit() {
- return logTableLimit;
- }
-
- public static void setLogTableLimit(String logTableLimit) {
- PolicyController.logTableLimit = logTableLimit;
- }
-
- public static String getSystemAlertTableLimit() {
- return systemAlertTableLimit;
- }
-
- public static void setSystemAlertTableLimit(String systemAlertTableLimit) {
- PolicyController.systemAlertTableLimit = systemAlertTableLimit;
- }
-
- public static CommonClassDao getCommonClassDao() {
- return commonClassDao;
- }
-
- public static void setCommonClassDao(CommonClassDao commonClassDao) {
- PolicyController.commonClassDao = commonClassDao;
- }
-
- public static Map<Datatype, List<FunctionDefinition>> getMapDatatype2Function() {
- return mapDatatype2Function;
- }
-
- public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
- PolicyController.mapDatatype2Function = mapDatatype2Function;
- }
-
- public static Map<String, FunctionDefinition> getMapID2Function() {
- return mapID2Function;
- }
-
- public static void setMapID2Function(Map<String, FunctionDefinition> mapID2Function) {
- PolicyController.mapID2Function = mapID2Function;
- }
-
- public static String getSmtpHost() {
- return smtpHost;
- }
-
- public static void setSmtpHost(String smtpHost) {
- PolicyController.smtpHost = smtpHost;
- }
-
- public static String getSmtpPort() {
- return smtpPort;
- }
-
- public static void setSmtpPort(String smtpPort) {
- PolicyController.smtpPort = smtpPort;
- }
-
- public static String getSmtpUsername() {
- return smtpUsername;
- }
-
- public static void setSmtpUsername(String smtpUsername) {
- PolicyController.smtpUsername = smtpUsername;
- }
-
- public static String getSmtpPassword() {
- return smtpPassword;
- }
-
- public static void setSmtpPassword(String smtpPassword) {
- PolicyController.smtpPassword = smtpPassword;
- }
-
- public static String getSmtpApplicationName() {
- return smtpApplicationName;
- }
-
- public static void setSmtpApplicationName(String smtpApplicationName) {
- PolicyController.smtpApplicationName = smtpApplicationName;
- }
-
- public static String getSmtpEmailExtension() {
- return smtpEmailExtension;
- }
-
- public static void setSmtpEmailExtension(String smtpEmailExtension) {
- PolicyController.smtpEmailExtension = smtpEmailExtension;
- }
-
- public static String getLogdbDriver() {
- return logdbDriver;
- }
-
- public static void setLogdbDriver(String logdbDriver) {
- PolicyController.logdbDriver = logdbDriver;
- }
+ public ModelAndView view(HttpServletRequest request){
+ String myRequestURL = request.getRequestURL().toString();
+ try {
+ //
+ // Set the URL for the RESTful PAP Engine
+ //
+ setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
+ new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e);
+ }
+ Map<String, Object> model = new HashMap<>();
+ return new ModelAndView("policy_Editor","model", model);
+ }
+
+ public PAPPolicyEngine getPapEngine() {
+ return papEngine;
+ }
+
+ public static void setPapEngine(PAPPolicyEngine papEngine) {
+ PolicyController.papEngine = papEngine;
+ }
+
+ public String getUserName(String createdBy) {
+ String loginId = createdBy;
+ List<Object> data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId);
+ return data.get(0).toString();
+ }
+
+ public static boolean getActivePolicy(String query) {
+ if(!commonClassDao.getDataByQuery(query, new SimpleBindings()).isEmpty()){
+ return true;
+ }else{
+ return false;
+ }
+ }
+
+ public void executeQuery(String query) {
+ commonClassDao.updateQuery(query);
+ }
+
+ public void saveData(Object cloneEntity) {
+ commonClassDao.save(cloneEntity);
+ }
+
+ public void updateData(Object entity) {
+ commonClassDao.update(entity);
+ }
+
+ public void deleteData(Object entity) {
+ commonClassDao.delete(entity);
+ }
+
+ public List<Object> getData(@SuppressWarnings("rawtypes") Class className){
+ return commonClassDao.getData(className);
+ }
+
+ public PolicyVersion getPolicyEntityFromPolicyVersion(String query){
+ return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
+ }
+
+ public List<Object> getDataByQuery(String query, SimpleBindings params){
+ return commonClassDao.getDataByQuery(query, params);
+ }
+
+
+ @SuppressWarnings("rawtypes")
+ public Object getEntityItem(Class className, String columname, String key){
+ return commonClassDao.getEntityItem(className, columname, key);
+ }
+
+
+ public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){
+ PolicyNotificationMail email = new PolicyNotificationMail();
+ try {
+ email.sendMail(entity, policyName, mode, commonClassDao);
+ } catch (MessagingException e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
+ }
+ }
+
+ //Switch Version
+ public JSONObject switchVersionPolicyContent(String policyName) {
+ String dbCheckName = policyName.replace("/", ".");
+ if(dbCheckName.contains("Config_")){
+ dbCheckName = dbCheckName.replace(".Config_", ":Config_");
+ }else if(dbCheckName.contains("Action_")){
+ dbCheckName = dbCheckName.replace(".Action_", ":Action_");
+ }else if(dbCheckName.contains("Decision_")){
+ dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
+ }
+ String[] splitDBCheckName = dbCheckName.split(":");
+ String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
+ SimpleBindings params = new SimpleBindings();
+ params.put("splitDBCheckName1", splitDBCheckName[1] + "%");
+ params.put("splitDBCheckName0", splitDBCheckName[0]);
+ List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
+ List<String> av = new ArrayList<>();
+ for(Object entity : policyEntity){
+ PolicyEntity pEntity = (PolicyEntity) entity;
+ String removeExtension = pEntity.getPolicyName().replace(".xml", "");
+ String version = removeExtension.substring(removeExtension.lastIndexOf('.')+1);
+ av.add(version);
+ }
+ if(policyName.contains("/")){
+ policyName = policyName.replace("/", File.separator);
+ }
+ PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName);
+ JSONObject el = new JSONObject();
+ el.put("activeVersion", entity.getActiveVersion());
+ el.put("availableVersions", av);
+ el.put("highestVersion", entity.getHigherVersion());
+ return el;
+ }
+
+ public static String getLogTableLimit() {
+ return logTableLimit;
+ }
+
+ public static void setLogTableLimit(String logTableLimit) {
+ PolicyController.logTableLimit = logTableLimit;
+ }
+
+ public static String getSystemAlertTableLimit() {
+ return systemAlertTableLimit;
+ }
+
+ public static void setSystemAlertTableLimit(String systemAlertTableLimit) {
+ PolicyController.systemAlertTableLimit = systemAlertTableLimit;
+ }
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ PolicyController.commonClassDao = commonClassDao;
+ }
+
+ public static Map<Datatype, List<FunctionDefinition>> getMapDatatype2Function() {
+ return mapDatatype2Function;
+ }
+
+ public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
+ PolicyController.mapDatatype2Function = mapDatatype2Function;
+ }
+
+ public static Map<String, FunctionDefinition> getMapID2Function() {
+ return mapID2Function;
+ }
+
+ public static void setMapID2Function(Map<String, FunctionDefinition> mapID2Function) {
+ PolicyController.mapID2Function = mapID2Function;
+ }
+
+ public static String getSmtpHost() {
+ return smtpHost;
+ }
+
+ public static void setSmtpHost(String smtpHost) {
+ PolicyController.smtpHost = smtpHost;
+ }
+
+ public static String getSmtpPort() {
+ return smtpPort;
+ }
+
+ public static void setSmtpPort(String smtpPort) {
+ PolicyController.smtpPort = smtpPort;
+ }
+
+ public static String getSmtpUsername() {
+ return smtpUsername;
+ }
+
+ public static void setSmtpUsername(String smtpUsername) {
+ PolicyController.smtpUsername = smtpUsername;
+ }
+
+ public static String getSmtpPassword() {
+ return smtpPassword;
+ }
+
+ public static void setSmtpPassword(String smtpPassword) {
+ PolicyController.smtpPassword = smtpPassword;
+ }
+
+ public static String getSmtpApplicationName() {
+ return smtpApplicationName;
+ }
+
+ public static void setSmtpApplicationName(String smtpApplicationName) {
+ PolicyController.smtpApplicationName = smtpApplicationName;
+ }
+
+ public static String getSmtpEmailExtension() {
+ return smtpEmailExtension;
+ }
+
+ public static void setSmtpEmailExtension(String smtpEmailExtension) {
+ PolicyController.smtpEmailExtension = smtpEmailExtension;
+ }
+
+ public static String getLogdbDriver() {
+ return logdbDriver;
+ }
+
+ public static void setLogdbDriver(String logdbDriver) {
+ PolicyController.logdbDriver = logdbDriver;
+ }
- public static String getLogdbUrl() {
- return logdbUrl;
- }
+ public static String getLogdbUrl() {
+ return logdbUrl;
+ }
- public static void setLogdbUrl(String logdbUrl) {
- PolicyController.logdbUrl = logdbUrl;
- }
+ public static void setLogdbUrl(String logdbUrl) {
+ PolicyController.logdbUrl = logdbUrl;
+ }
- public static String getLogdbUserName() {
- return logdbUserName;
- }
+ public static String getLogdbUserName() {
+ return logdbUserName;
+ }
- public static void setLogdbUserName(String logdbUserName) {
- PolicyController.logdbUserName = logdbUserName;
- }
+ public static void setLogdbUserName(String logdbUserName) {
+ PolicyController.logdbUserName = logdbUserName;
+ }
- public static String getLogdbPassword() {
- return logdbPassword;
- }
+ public static String getLogdbPassword() {
+ return logdbPassword;
+ }
- public static void setLogdbPassword(String logdbPassword) {
- PolicyController.logdbPassword = logdbPassword;
- }
+ public static void setLogdbPassword(String logdbPassword) {
+ PolicyController.logdbPassword = logdbPassword;
+ }
- public static String getLogdbDialect() {
- return logdbDialect;
- }
+ public static String getLogdbDialect() {
+ return logdbDialect;
+ }
- public static void setLogdbDialect(String logdbDialect) {
- PolicyController.logdbDialect = logdbDialect;
- }
+ public static void setLogdbDialect(String logdbDialect) {
+ PolicyController.logdbDialect = logdbDialect;
+ }
- public static String getXacmldbUrl() {
- return xacmldbUrl;
- }
+ public static String getXacmldbUrl() {
+ return xacmldbUrl;
+ }
- public static void setXacmldbUrl(String xacmldbUrl) {
- PolicyController.xacmldbUrl = xacmldbUrl;
- }
+ public static void setXacmldbUrl(String xacmldbUrl) {
+ PolicyController.xacmldbUrl = xacmldbUrl;
+ }
- public static String getXacmldbUserName() {
- return xacmldbUserName;
- }
+ public static String getXacmldbUserName() {
+ return xacmldbUserName;
+ }
- public static void setXacmldbUserName(String xacmldbUserName) {
- PolicyController.xacmldbUserName = xacmldbUserName;
- }
+ public static void setXacmldbUserName(String xacmldbUserName) {
+ PolicyController.xacmldbUserName = xacmldbUserName;
+ }
- public static String getXacmldbPassword() {
- return xacmldbPassword;
- }
+ public static String getXacmldbPassword() {
+ return xacmldbPassword;
+ }
- public static void setXacmldbPassword(String xacmldbPassword) {
- PolicyController.xacmldbPassword = xacmldbPassword;
- }
+ public static void setXacmldbPassword(String xacmldbPassword) {
+ PolicyController.xacmldbPassword = xacmldbPassword;
+ }
- public static String getAutoPushAvailable() {
- return autoPushAvailable;
- }
-
- public static void setAutoPushAvailable(String autoPushAvailable) {
- PolicyController.autoPushAvailable = autoPushAvailable;
- }
-
- public static String getAutoPushDSClosedLoop() {
- return autoPushDSClosedLoop;
- }
-
- public static void setAutoPushDSClosedLoop(String autoPushDSClosedLoop) {
- PolicyController.autoPushDSClosedLoop = autoPushDSClosedLoop;
- }
-
- public static String getAutoPushDSFirewall() {
- return autoPushDSFirewall;
- }
-
- public static void setAutoPushDSFirewall(String autoPushDSFirewall) {
- PolicyController.autoPushDSFirewall = autoPushDSFirewall;
- }
-
- public static String getAutoPushDSMicroservice() {
- return autoPushDSMicroservice;
- }
-
- public static void setAutoPushDSMicroservice(String autoPushDSMicroservice) {
- PolicyController.autoPushDSMicroservice = autoPushDSMicroservice;
- }
-
- public static String getAutoPushPDPGroup() {
- return autoPushPDPGroup;
- }
-
- public static void setAutoPushPDPGroup(String autoPushPDPGroup) {
- PolicyController.autoPushPDPGroup = autoPushPDPGroup;
- }
-
- public static String getPapUrl() {
- return papUrl;
- }
-
- public static void setPapUrl(String papUrl) {
- PolicyController.papUrl = papUrl;
- }
-
- public static String getMsOnapName() {
- return msOnapName;
- }
-
- public static void setMsOnapName(String msOnapName) {
- PolicyController.msOnapName = msOnapName;
- }
-
- public static String getMsPolicyName() {
- return msPolicyName;
- }
-
- public static void setMsPolicyName(String msPolicyName) {
- PolicyController.msPolicyName = msPolicyName;
- }
-
- public static String getConfigHome() {
- return configHome;
- }
-
- public static void setConfigHome(String configHome) {
- PolicyController.configHome = configHome;
- }
-
- public static String getActionHome() {
- return actionHome;
- }
-
- public static void setActionHome(String actionHome) {
- PolicyController.actionHome = actionHome;
- }
-
- public static Object getMapaccess() {
- return mapAccess;
- }
-
- public static String getPolicydata() {
- return policyData;
- }
-
- public static String getCharacterencoding() {
- return characterEncoding;
- }
-
- public static String getContenttype() {
- return contentType;
- }
-
- public static String getFile() {
- return file;
- }
-
- public static void setFileSizeLimit(String uploadSize) {
- //Default size limit is 30MB
- if (uploadSize == null || uploadSize.isEmpty()) {
- fileSizeLimit = 30000000;
- }
- else {
- fileSizeLimit = Long.parseLong(uploadSize);
- }
- }
-
- public static long getFileSizeLimit() {
- return fileSizeLimit;
- }
- public String convertDate(String dateTTL) {
- String formateDate = null;
- if(dateTTL.contains("-")){
- formateDate = dateTTL.replace("-", "/");
- }
- return formateDate;
- }
+ public static String getAutoPushAvailable() {
+ return autoPushAvailable;
+ }
+
+ public static void setAutoPushAvailable(String autoPushAvailable) {
+ PolicyController.autoPushAvailable = autoPushAvailable;
+ }
+
+ public static String getAutoPushDSClosedLoop() {
+ return autoPushDSClosedLoop;
+ }
+
+ public static void setAutoPushDSClosedLoop(String autoPushDSClosedLoop) {
+ PolicyController.autoPushDSClosedLoop = autoPushDSClosedLoop;
+ }
+
+ public static String getAutoPushDSFirewall() {
+ return autoPushDSFirewall;
+ }
+
+ public static void setAutoPushDSFirewall(String autoPushDSFirewall) {
+ PolicyController.autoPushDSFirewall = autoPushDSFirewall;
+ }
+
+ public static String getAutoPushDSMicroservice() {
+ return autoPushDSMicroservice;
+ }
+
+ public static void setAutoPushDSMicroservice(String autoPushDSMicroservice) {
+ PolicyController.autoPushDSMicroservice = autoPushDSMicroservice;
+ }
+
+ public static String getAutoPushPDPGroup() {
+ return autoPushPDPGroup;
+ }
+
+ public static void setAutoPushPDPGroup(String autoPushPDPGroup) {
+ PolicyController.autoPushPDPGroup = autoPushPDPGroup;
+ }
+
+ public static String getPapUrl() {
+ return papUrl;
+ }
+
+ public static void setPapUrl(String papUrl) {
+ PolicyController.papUrl = papUrl;
+ }
+
+ public static String getMsOnapName() {
+ return msOnapName;
+ }
+
+ public static void setMsOnapName(String msOnapName) {
+ PolicyController.msOnapName = msOnapName;
+ }
+
+ public static String getMsPolicyName() {
+ return msPolicyName;
+ }
+
+ public static void setMsPolicyName(String msPolicyName) {
+ PolicyController.msPolicyName = msPolicyName;
+ }
+
+ public static String getConfigHome() {
+ return configHome;
+ }
+
+ public static void setConfigHome(String configHome) {
+ PolicyController.configHome = configHome;
+ }
+
+ public static String getActionHome() {
+ return actionHome;
+ }
+
+ public static void setActionHome(String actionHome) {
+ PolicyController.actionHome = actionHome;
+ }
+
+ public static Object getMapaccess() {
+ return mapAccess;
+ }
+
+ public static String getPolicydata() {
+ return policyData;
+ }
+
+ public static String getCharacterencoding() {
+ return characterEncoding;
+ }
+
+ public static String getContenttype() {
+ return contentType;
+ }
+
+ public static String getFile() {
+ return file;
+ }
+
+ public static void setFileSizeLimit(String uploadSize) {
+ //Default size limit is 30MB
+ if (uploadSize == null || uploadSize.isEmpty()) {
+ fileSizeLimit = 30000000;
+ }
+ else {
+ fileSizeLimit = Long.parseLong(uploadSize);
+ }
+ }
+
+ public static long getFileSizeLimit() {
+ return fileSizeLimit;
+ }
+ public String convertDate(String dateTTL) {
+ String formateDate = null;
+ if(dateTTL.contains("-")){
+ formateDate = dateTTL.replace("-", "/");
+ }
+ return formateDate;
+ }
}
diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndDMAAP.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndDMAAP.java
index 0281f6010..065f084ba 100644
--- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndDMAAP.java
+++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndDMAAP.java
@@ -3,6 +3,7 @@
* PolicyEngineAPI
* ================================================================================
* Copyright (C) 2017 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.
@@ -33,98 +34,103 @@ import org.onap.policy.utils.BusPublisher;
import org.onap.policy.xacml.api.XACMLErrorConstants;
public class ManualClientEndDMAAP {
- private static StdPDPNotification notification = null;
- private static String resultJson = null;
- private static Logger logger = FlexLogger.getLogger(ManualClientEndDMAAP.class.getName());
- private static BusConsumer dmaapConsumer = null;
- private static String uniquID = null;
- private static String topic = null;
-
- private ManualClientEndDMAAP() {
- // Empty constructor
- }
-
+ private static StdPDPNotification notification = null;
+ private static String resultJson = null;
+ private static Logger logger = FlexLogger.getLogger(ManualClientEndDMAAP.class.getName());
+ private static BusConsumer dmaapConsumer = null;
+ private static String uniquID = null;
+ private static String topic = null;
+ private static int RETRY_LIMIT = 4;
+ private ManualClientEndDMAAP() {
+ // Empty constructor
+ }
- public static PDPNotification result(NotificationScheme scheme) {
- if (resultJson == null || notification == null) {
- logger.debug("No Result" );
- return null;
- }
- if(scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
- boolean removed = false;
- boolean updated = false;
- if(notification.getRemovedPolicies()!=null && !notification.getRemovedPolicies().isEmpty()){
- removed = true;
- }
- if(notification.getLoadedPolicies()!=null && !notification.getLoadedPolicies().isEmpty()){
- updated = true;
- }
- if(removed && updated) {
- notification.setNotificationType(NotificationType.BOTH);
- }else if(removed){
- notification.setNotificationType(NotificationType.REMOVE);
- }else if(updated){
- notification.setNotificationType(NotificationType.UPDATE);
- }
- return notification;
- }else if(scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) {
- return MatchStore.checkMatch(notification);
- }
- return null;
- }
- private static void publishMessage(String pubTopic, String uniqueID, List<String> dmaapList, String aafLogin, String aafPassword) {
+ public static PDPNotification result(NotificationScheme scheme) {
+ if (resultJson == null || notification == null) {
+ logger.debug("No Result" );
+ return null;
+ }
+ if(scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
+ boolean removed = false;
+ boolean updated = false;
+ if(notification.getRemovedPolicies()!=null && !notification.getRemovedPolicies().isEmpty()){
+ removed = true;
+ }
+ if(notification.getLoadedPolicies()!=null && !notification.getLoadedPolicies().isEmpty()){
+ updated = true;
+ }
+ if(removed && updated) {
+ notification.setNotificationType(NotificationType.BOTH);
+ }else if(removed){
+ notification.setNotificationType(NotificationType.REMOVE);
+ }else if(updated){
+ notification.setNotificationType(NotificationType.UPDATE);
+ }
+ return notification;
+ }else if(scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) {
+ return MatchStore.checkMatch(notification);
+ }
+ return null;
+ }
+
+ private static void publishMessage(String pubTopic, String uniqueID, List<String> dmaapList, String aafLogin, String aafPassword) {
BusPublisher pub = null;
- try {
- pub = new BusPublisher.DmaapPublisherWrapper(dmaapList, topic, aafLogin, aafPassword);
- final JSONObject msg1 = new JSONObject ();
- msg1.put ( "JSON", "DMaaP Update Request UID=" + uniqueID);
- pub.send ( "MyPartitionKey", msg1.toString () );
- } catch (Exception e) {
- logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create DMaaP Publisher: ", e);
- }
- if(pub != null){
- pub.close ();
- }
- }
+ try {
+ pub = new BusPublisher.DmaapPublisherWrapper(dmaapList, topic, aafLogin, aafPassword);
+ final JSONObject msg1 = new JSONObject ();
+ msg1.put ( "JSON", "DMaaP Update Request UID=" + uniqueID);
+ pub.send ( "MyPartitionKey", msg1.toString () );
+ } catch (Exception e) {
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create DMaaP Publisher: ", e);
+ }
+ if(pub != null){
+ pub.close ();
+ }
+ }
+
+ //NOTE: should be able to remove this for DMAAP since we will not be creating topics dynamically
+ public static void createTopic (String topic, String uniquID, List<String> dmaapList, String aafLogin, String aafPassword){
+ ManualClientEndDMAAP.topic = topic;
+ publishMessage(topic, uniquID, dmaapList, aafLogin, aafPassword);
+ }
+
+
+ public static void start(List<String> dmaapList, String topic, String aafLogin, String aafPassword, String uniqueID) {
+
+ ManualClientEndDMAAP.uniquID = uniqueID;
+ ManualClientEndDMAAP.topic = topic;
+
+ String id = "0";
+
+ try {
+ dmaapConsumer = new BusConsumer.DmaapConsumerWrapper(dmaapList, topic, aafLogin, aafPassword, "clientGroup", id, 15*1000, 1000);
+ } catch (Exception e) {
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create DMaaP Consumer: ", e);
+ }
+
+ int retries = 1;
+ boolean isSuccess = false;
+ while (retries < RETRY_LIMIT && !isSuccess) {
+ isSuccess = publishMessageAndSetNotification(dmaapList, topic, aafLogin, aafPassword);
+ retries++;
+ }
+ }
- //NOTE: should be able to remove this for DMAAP since we will not be creating topics dynamically
- public static void createTopic (String topic, String uniquID, List<String> dmaapList, String aafLogin, String aafPassword){
- ManualClientEndDMAAP.topic = topic;
- publishMessage(topic, uniquID, dmaapList, aafLogin, aafPassword);
- }
-
-
- public static void start(List<String> dmaapList, String topic, String aafLogin, String aafPassword, String uniqueID) {
-
- ManualClientEndDMAAP.uniquID = uniqueID;
- ManualClientEndDMAAP.topic = topic;
-
- String id = "0";
-
- try {
- dmaapConsumer = new BusConsumer.DmaapConsumerWrapper(dmaapList, topic, aafLogin, aafPassword, "clientGroup", id, 15*1000, 1000);
- } catch (Exception e) {
- logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create DMaaP Consumer: ", e);
- }
-
- int count = 1;
- while (count < 4) {
- publishMessage(topic, uniquID, dmaapList, aafLogin, aafPassword);
- try {
- for ( String msg : dmaapConsumer.fetch () )
- {
- logger.debug("Manual Notification Recieved Message " + msg + " from DMaaP server : " + dmaapList.toString());
- resultJson = msg;
- if (!msg.contains("DMaaP Update")){
- notification = NotificationUnMarshal.notificationJSON(msg);
- count = 4;
- }
- }
- }catch (Exception e) {
- logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to fetch messages from DMaaP servers: ", e);
- }
- count++;
- }
- }
+ private static boolean publishMessageAndSetNotification(List<String> dmaapList, String topic, String aafLogin, String aafPassword) {
+ publishMessage(topic, uniquID, dmaapList, aafLogin, aafPassword);
+ try {
+ for ( String msg : dmaapConsumer.fetch () ) {
+ logger.debug("Manual Notification Recieved Message " + msg + " from DMaaP server : " + dmaapList.toString());
+ resultJson = msg;
+ if (!msg.contains("DMaaP Update")){
+ notification = NotificationUnMarshal.notificationJSON(msg);
+ return true;
+ }
+ }
+ }catch (Exception e) {
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to fetch messages from DMaaP servers: ", e);
+ }
+ return false;
+ }
}
diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndUEB.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndUEB.java
index c04736e86..d67e136e3 100644
--- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndUEB.java
+++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndUEB.java
@@ -3,6 +3,7 @@
* PolicyEngineAPI
* ================================================================================
* Copyright (C) 2017 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.
@@ -39,123 +40,127 @@ import com.att.nsa.cambria.client.CambriaPublisher;
@SuppressWarnings("deprecation")
public class ManualClientEndUEB {
- private static StdPDPNotification notification = null;
- private static String resultJson = null;
- private static Logger logger = FlexLogger.getLogger(ManualClientEndUEB.class.getName());
- private static CambriaConsumer CConsumer = null;
- @SuppressWarnings("unused")
- private static List<String> uebURLList = null;
- @SuppressWarnings("unused")
- private static boolean messageNotReceived = false;
- @SuppressWarnings("unused")
- private static String url = null;
- private static String uniquID = null;
- private static String topic = null;
+ private static StdPDPNotification notification = null;
+ private static String resultJson = null;
+ private static Logger logger = FlexLogger.getLogger(ManualClientEndUEB.class.getName());
+ private static CambriaConsumer CConsumer = null;
+ @SuppressWarnings("unused")
+ private static List<String> uebURLList = null;
+ @SuppressWarnings("unused")
+ private static boolean messageNotReceived = false;
+ @SuppressWarnings("unused")
+ private static String url = null;
+ private static String uniquID = null;
+ private static String topic = null;
+ private static int RETRY_LIMIT = 4;
- private ManualClientEndUEB() {
- // Empty constructor
- }
+ private ManualClientEndUEB() {
+ // Empty constructor
+ }
- public static PDPNotification result(NotificationScheme scheme) {
- if (resultJson == null || notification == null) {
- logger.debug("No Result" );
- return null;
- }
- if(scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
- boolean removed = false;
- boolean updated = false;
- if(notification.getRemovedPolicies()!=null && !notification.getRemovedPolicies().isEmpty()){
- removed = true;
- }
- if(notification.getLoadedPolicies()!=null && !notification.getLoadedPolicies().isEmpty()){
- updated = true;
- }
- if(removed && updated) {
- notification.setNotificationType(NotificationType.BOTH);
- }else if(removed){
- notification.setNotificationType(NotificationType.REMOVE);
- }else if(updated){
- notification.setNotificationType(NotificationType.UPDATE);
- }
- return notification;
- }else if(scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) {
- return MatchStore.checkMatch(notification);
- }
- return null;
- }
+ public static PDPNotification result(NotificationScheme scheme) {
+ if (resultJson == null || notification == null) {
+ logger.debug("No Result" );
+ return null;
+ }
+ if(scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
+ boolean removed = false;
+ boolean updated = false;
+ if(notification.getRemovedPolicies()!=null && !notification.getRemovedPolicies().isEmpty()){
+ removed = true;
+ }
+ if(notification.getLoadedPolicies()!=null && !notification.getLoadedPolicies().isEmpty()){
+ updated = true;
+ }
+ if(removed && updated) {
+ notification.setNotificationType(NotificationType.BOTH);
+ }else if(removed){
+ notification.setNotificationType(NotificationType.REMOVE);
+ }else if(updated){
+ notification.setNotificationType(NotificationType.UPDATE);
+ }
+ return notification;
+ }else if(scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) {
+ return MatchStore.checkMatch(notification);
+ }
+ return null;
+ }
- private static void publishMessage(String pubTopic, String uniqueID , List<String> uebURLList) {
-
- String UEBlist = uebURLList.toString();
- UEBlist = UEBlist.substring(1,UEBlist.length()-1);
+ private static void publishMessage(String pubTopic, String uniqueID , List<String> uebURLList) {
+
+ String UEBlist = uebURLList.toString();
+ UEBlist = UEBlist.substring(1,UEBlist.length()-1);
CambriaPublisher pub = null;
- try {
- pub = CambriaClientFactory.createSimplePublisher(null, UEBlist, pubTopic);
- } catch (Exception e1) {
- logger.error("Exception Occured"+e1);
- }
+ try {
+ pub = CambriaClientFactory.createSimplePublisher(null, UEBlist, pubTopic);
+ } catch (Exception e1) {
+ logger.error("Exception Occured"+e1);
+ }
final JSONObject msg1 = new JSONObject ();
msg1.put ( "JSON", "UEB Update Ruest UID=" + uniqueID);
if(pub != null){
- try {
- pub.send ( "MyPartitionKey", msg1.toString () );
- pub.close ();
- } catch (IOException e) {
- logger.error("Exception Occured"+e);
- }
+ try {
+ pub.send ( "MyPartitionKey", msg1.toString () );
+ pub.close ();
+ } catch (IOException e) {
+ logger.error("Exception Occured"+e);
+ }
}
- }
+ }
+
+ public static void createTopic (String url, String uniquID, List<String> uebURLList){
+ URL aURL;
+ try {
+ aURL = new URL(url);
+ topic = aURL.getHost() + aURL.getPort();
+ } catch (MalformedURLException e) {
+ topic = url.replace("[:/]", "");
+ }
+
+ publishMessage(topic+ uniquID , uniquID, uebURLList);
- public static void createTopic (String url, String uniquID, List<String> uebURLList){
- URL aURL;
- try {
- aURL = new URL(url);
- topic = aURL.getHost() + aURL.getPort();
- } catch (MalformedURLException e) {
- topic = url.replace("[:/]", "");
- }
+ }
+ public static void start(String url, List<String> uebURLList,
+ String uniqueID) {
+ ManualClientEndUEB.uebURLList = uebURLList;
+ ManualClientEndUEB.url = url;
+ ManualClientEndUEB.uniquID = uniqueID;
+ URL aURL;
+ try {
+ aURL = new URL(url);
+ ManualClientEndUEB.topic = aURL.getHost() + aURL.getPort();
+ } catch (MalformedURLException e) {
+ ManualClientEndUEB.topic = url.replace("[:/]", "");
+ }
+ String id = "0";
+ try {
+ CConsumer = CambriaClientFactory.createConsumer ( null, uebURLList, topic + uniquID, "clientGroup", id, 15*1000, 1000 );
+ } catch (Exception e1) {
+ logger.error("Exception Occured"+e1);
+ }
+ int retries = 1;
+ boolean isSuccess = false;
+ while (retries < RETRY_LIMIT && !isSuccess) {
+ isSuccess = publishMessageAndSetNotification(uebURLList);
+ retries++;
+ }
+ }
- publishMessage(topic+ uniquID , uniquID, uebURLList);
-
- }
- public static void start(String url, List<String> uebURLList,
- String uniqueID) {
- ManualClientEndUEB.uebURLList = uebURLList;
- ManualClientEndUEB.url = url;
- ManualClientEndUEB.uniquID = uniqueID;
- URL aURL;
- try {
- aURL = new URL(url);
- ManualClientEndUEB.topic = aURL.getHost() + aURL.getPort();
- } catch (MalformedURLException e) {
- ManualClientEndUEB.topic = url.replace("[:/]", "");
- }
- String id = "0";
- try {
- CConsumer = CambriaClientFactory.createConsumer ( null, uebURLList, topic + uniquID, "clientGroup", id, 15*1000, 1000 );
- } catch (Exception e1) {
- logger.error("Exception Occured"+e1);
- }
- int count = 1;
- while (count < 4) {
- publishMessage(topic + "UpdateRequest", uniquID, uebURLList);
- try {
- for ( String msg : CConsumer.fetch () )
- {
-
- logger.debug("Manual Notification Recieved Message " + msg + " from UEB cluster : " + uebURLList.toString());
- resultJson = msg;
- if (!msg.contains("UEB Update")){
- notification = NotificationUnMarshal.notificationJSON(msg);
- count = 4;
- }
- }
- }catch (Exception e) {
- logger.error("Error in Manual CLient UEB notification ", e);
- }
- count++;
- }
- }
-
+ private static boolean publishMessageAndSetNotification(List<String> uebURLList) {
+ publishMessage(topic + "UpdateRequest", uniquID, uebURLList);
+ try {
+ for ( String msg : CConsumer.fetch () ) {
+ logger.debug("Manual Notification Recieved Message " + msg + " from UEB cluster : " + uebURLList.toString());
+ resultJson = msg;
+ if (!msg.contains("UEB Update")){
+ notification = NotificationUnMarshal.notificationJSON(msg);
+ return true;
+ }
+ }
+ }catch (Exception e) {
+ logger.error("Error in Manual CLient UEB notification ", e);
+ }
+ return false;
+ }
}
diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java
index f09b5779c..8f3cf043a 100644
--- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java
+++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java
@@ -3,6 +3,7 @@
* PolicyEngineAPI
* ================================================================================
* Copyright (C) 2017-2018 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.
@@ -348,7 +349,7 @@ public class StdPolicyEngine {
return deletePolicyImpl(parameters);
}
- public PolicyChangeResponse deletePolicyImpl(final DeletePolicyParameters parameters) throws PolicyException {
+ private PolicyChangeResponse deletePolicyImpl(final DeletePolicyParameters parameters) throws PolicyException {
final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
String body = null;
// Create Request.
@@ -379,7 +380,7 @@ public class StdPolicyEngine {
return getDictionaryItemImpl(parameters);
}
- public DictionaryResponse getDictionaryItemImpl(final DictionaryParameters parameters) throws PolicyException {
+ private DictionaryResponse getDictionaryItemImpl(final DictionaryParameters parameters) throws PolicyException {
final StdDictionaryResponse response = new StdDictionaryResponse();
String body = "{}";
// Create Request.
@@ -450,7 +451,7 @@ public class StdPolicyEngine {
return createUpdateDictionaryItemImpl(parameters, true);
}
- public PolicyChangeResponse createUpdateDictionaryItemImpl(final DictionaryParameters parameters,
+ private PolicyChangeResponse createUpdateDictionaryItemImpl(final DictionaryParameters parameters,
final boolean updateFlag) throws PolicyException {
final String resource = getDictionaryResouceName(updateFlag);
@@ -487,7 +488,7 @@ public class StdPolicyEngine {
return policyEngineImportImpl(importParameters);
}
- public PolicyChangeResponse policyEngineImportImpl(final ImportParameters importParameters) throws PolicyException {
+ private PolicyChangeResponse policyEngineImportImpl(final ImportParameters importParameters) throws PolicyException {
final LinkedMultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
// Create Request.
try {
@@ -530,7 +531,7 @@ public class StdPolicyEngine {
return createUpdatePolicyImpl(policyParameters, true);
}
- public PolicyChangeResponse createUpdatePolicyImpl(final PolicyParameters policyParameters,
+ private PolicyChangeResponse createUpdatePolicyImpl(final PolicyParameters policyParameters,
final boolean updateFlag) throws PolicyException {
final String resource = getPolicyResourceName(updateFlag);
String body = null;
@@ -575,7 +576,7 @@ public class StdPolicyEngine {
}
}
- public DecisionResponse getDecisionImpl(final String onapName, final Map<String, String> decisionAttributes,
+ private DecisionResponse getDecisionImpl(final String onapName, final Map<String, String> decisionAttributes,
final UUID requestID) throws PolicyDecisionException {
String body = null;
// Create Request.
@@ -604,7 +605,7 @@ public class StdPolicyEngine {
}
}
- public Collection<PolicyConfig> getConfigImpl(final ConfigRequestParameters configRequestParameters)
+ private Collection<PolicyConfig> getConfigImpl(final ConfigRequestParameters configRequestParameters)
throws PolicyConfigException {
String body = null;
// Create Request.
@@ -632,51 +633,53 @@ public class StdPolicyEngine {
private ArrayList<PolicyConfig> configResult(final APIPolicyConfigResponse[] response)
throws PolicyConfigException {
final ArrayList<PolicyConfig> result = new ArrayList<>();
- if (response != null) {
- for (final APIPolicyConfigResponse policyConfigResponse : response) {
- final StdPolicyConfig policyConfig = new StdPolicyConfig();
- policyConfig.setConfigStatus(policyConfigResponse.getPolicyConfigMessage());
- policyConfig.setMatchingConditions(policyConfigResponse.getMatchingConditions());
- policyConfig.setPolicyConfigStatus(policyConfigResponse.getPolicyConfigStatus());
- policyConfig.setPolicyName(policyConfigResponse.getPolicyName());
- policyConfig.setPolicyType(policyConfigResponse.getType());
- policyConfig.setPolicyVersion(policyConfigResponse.getPolicyVersion());
- policyConfig.setPolicyType(policyConfigResponse.getPolicyType());
- policyConfig.setResponseAttributes(policyConfigResponse.getResponseAttributes());
- setMatches(policyConfig.getMatchingConditions());
- if (policyConfigResponse.getType() != null) {
- try {
- switch (policyConfigResponse.getType()) {
- case JSON:
- final StringReader reader = new StringReader(policyConfigResponse.getConfig());
- try (final JsonReader jsonReader = Json.createReader(reader)) {
- final JsonObject object = jsonReader.readObject();
- policyConfig.setJsonObject(object);
- }
- break;
- case OTHER:
- policyConfig.setOther(policyConfigResponse.getConfig());
- break;
- case PROPERTIES:
- final Properties props = new Properties();
- props.putAll(policyConfigResponse.getProperty());
- policyConfig.setProperties(props);
- break;
- case XML:
- final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- final DocumentBuilder builder = factory.newDocumentBuilder();
- final StringReader stringReader = new StringReader(policyConfigResponse.getConfig());
- policyConfig.setDocument(builder.parse(new InputSource(stringReader)));
- break;
- }
- } catch (final Exception exception) {
- LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + exception);
- throw new PolicyConfigException(
- XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the config", exception);
+ if (response == null) {
+ return result;
+ }
+
+ for (final APIPolicyConfigResponse policyConfigResponse : response) {
+ final StdPolicyConfig policyConfig = new StdPolicyConfig();
+ policyConfig.setConfigStatus(policyConfigResponse.getPolicyConfigMessage());
+ policyConfig.setMatchingConditions(policyConfigResponse.getMatchingConditions());
+ policyConfig.setPolicyConfigStatus(policyConfigResponse.getPolicyConfigStatus());
+ policyConfig.setPolicyName(policyConfigResponse.getPolicyName());
+ policyConfig.setPolicyType(policyConfigResponse.getType());
+ policyConfig.setPolicyVersion(policyConfigResponse.getPolicyVersion());
+ policyConfig.setPolicyType(policyConfigResponse.getPolicyType());
+ policyConfig.setResponseAttributes(policyConfigResponse.getResponseAttributes());
+ setMatches(policyConfig.getMatchingConditions());
+ if (policyConfigResponse.getType() != null) {
+ try {
+ switch (policyConfigResponse.getType()) {
+ case JSON:
+ final StringReader reader = new StringReader(policyConfigResponse.getConfig());
+ try (final JsonReader jsonReader = Json.createReader(reader)) {
+ final JsonObject object = jsonReader.readObject();
+ policyConfig.setJsonObject(object);
+ }
+ break;
+ case OTHER:
+ policyConfig.setOther(policyConfigResponse.getConfig());
+ break;
+ case PROPERTIES:
+ final Properties props = new Properties();
+ props.putAll(policyConfigResponse.getProperty());
+ policyConfig.setProperties(props);
+ break;
+ case XML:
+ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ final DocumentBuilder builder = factory.newDocumentBuilder();
+ final StringReader stringReader = new StringReader(policyConfigResponse.getConfig());
+ policyConfig.setDocument(builder.parse(new InputSource(stringReader)));
+ break;
}
+ } catch (final Exception exception) {
+ LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + exception);
+ throw new PolicyConfigException(
+ XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the config", exception);
}
- result.add(policyConfig);
}
+ result.add(policyConfig);
}
return result;
}
@@ -774,7 +777,7 @@ public class StdPolicyEngine {
clientEncoding = encoder.encodeToString((userName + ":" + pass).getBytes(StandardCharsets.UTF_8));
}
- public Collection<String> listConfigImpl(final ConfigRequestParameters listRequestParameters)
+ private Collection<String> listConfigImpl(final ConfigRequestParameters listRequestParameters)
throws PolicyConfigException {
final Collection<String> policyList = new ArrayList<>();
if (junit) {
@@ -792,7 +795,7 @@ public class StdPolicyEngine {
return policyList;
}
- public Collection<PolicyResponse> sendEventImpl(final Map<String, String> eventAttributes, final UUID requestID)
+ private Collection<PolicyResponse> sendEventImpl(final Map<String, String> eventAttributes, final UUID requestID)
throws PolicyEventException {
String body = null;
// Create Request.
@@ -864,7 +867,7 @@ public class StdPolicyEngine {
apiKey = properties.getProperty(UEB_API_KEY_PROP_NAME);
apiSecret = properties.getProperty(UEB_API_SECRET_PROP_NAME);
- setNotificationType(notificationTypeValue, DEFAULT_NOTIFICATION);
+ setNotificationType(notificationTypeValue);
if (serverList == null) {
notificationType.clear();
@@ -872,7 +875,7 @@ public class StdPolicyEngine {
LOGGER.info(
"Properties file doesn't have the NOTIFICATION_SERVERS parameter system will use defualt websockets");
} else {
- notificationURLList = getPropertyValueAsList(serverList.trim(), COMMA);
+ notificationURLList = getPropertyValueAsList(serverList.trim());
}
if (topic != null) {
@@ -907,19 +910,7 @@ public class StdPolicyEngine {
// Check the Keys for PDP_URLs
for (final String propertyKey : prop.stringPropertyNames()) {
if (propertyKey.startsWith(PDP_URL_PROP_NAME)) {
- final String propertyValue = prop.getProperty(propertyKey);
- if (propertyValue == null) {
- throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
- + "Properties file doesn't have the PDP_URL parameter");
- }
- if (propertyValue.contains(SEMICOLLON)) {
- final List<String> pdpDefault = Arrays.asList(propertyValue.split(REGEX));
- for (final String pdpVal : pdpDefault) {
- readPDPParam(pdpVal);
- }
- } else {
- readPDPParam(propertyValue);
- }
+ readPDPPropertyURL(prop, propertyKey);
}
}
if (pdps == null || pdps.isEmpty()) {
@@ -928,13 +919,29 @@ public class StdPolicyEngine {
}
}
- private void setNotificationType(final String propertyValue, final String defaultValue) {
+ private void readPDPPropertyURL(Properties prop, String propertyKey) throws PolicyEngineException {
+ final String propertyValue = prop.getProperty(propertyKey);
+ if (propertyValue == null) {
+ throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Properties file doesn't have the PDP_URL parameter");
+ }
+ if (propertyValue.contains(SEMICOLLON)) {
+ final List<String> pdpDefault = Arrays.asList(propertyValue.split(REGEX));
+ for (final String pdpVal : pdpDefault) {
+ readPDPParam(pdpVal);
+ }
+ } else {
+ readPDPParam(propertyValue);
+ }
+ }
+
+ private void setNotificationType(final String propertyValue) {
if (propertyValue == null) {
- notificationType.add(defaultValue);
+ notificationType.add(DEFAULT_NOTIFICATION);
LOGGER.info(
"Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets");
} else {
- notificationType = getPropertyValueAsList(propertyValue.trim(), COMMA);
+ notificationType = getPropertyValueAsList(propertyValue.trim());
}
}
@@ -992,9 +999,9 @@ public class StdPolicyEngine {
}
}
- private List<String> getPropertyValueAsList(final String propertyValue, final String split) {
- if (propertyValue.contains(split)) {
- return Arrays.asList(propertyValue.split(split));
+ private List<String> getPropertyValueAsList(final String propertyValue) {
+ if (propertyValue.contains(COMMA)) {
+ return Arrays.asList(propertyValue.split(COMMA));
}
final List<String> valuesList = new ArrayList<>();
valuesList.add(propertyValue);
@@ -1087,28 +1094,29 @@ public class StdPolicyEngine {
if (junit) {
return;
}
+ if (pdps == null) {
+ return;
+ }
- if (pdps != null) {
- if (UEB.equals(notificationType.get(0)) && !this.uebThread) {
- this.uebClientThread = new AutoClientUEB(pdps.get(0), notificationURLList, apiKey, apiSecret);
- AutoClientUEB.setAuto(scheme, handler);
- this.registerUEBThread = new Thread(this.uebClientThread);
- this.registerUEBThread.start();
- this.uebThread = true;
- } else if (notificationType.get(0).equals(DMAAP) && !this.dmaapThread) {
- this.dmaapClientThread = new AutoClientDMAAP(notificationURLList, topic, userName, pass);
- AutoClientDMAAP.setAuto(scheme, handler);
- this.registerDMAAPThread = new Thread(this.dmaapClientThread);
- this.registerDMAAPThread.start();
- this.dmaapThread = true;
- } else {
- if (pdps.get(0) != null) {
- if (AutoClientEnd.getUrl() == null) {
- AutoClientEnd.start(pdps.get(0));
- } else {
- AutoClientEnd.stop();
- AutoClientEnd.start(pdps.get(0));
- }
+ if (UEB.equals(notificationType.get(0)) && !this.uebThread) {
+ this.uebClientThread = new AutoClientUEB(pdps.get(0), notificationURLList, apiKey, apiSecret);
+ AutoClientUEB.setAuto(scheme, handler);
+ this.registerUEBThread = new Thread(this.uebClientThread);
+ this.registerUEBThread.start();
+ this.uebThread = true;
+ } else if (notificationType.get(0).equals(DMAAP) && !this.dmaapThread) {
+ this.dmaapClientThread = new AutoClientDMAAP(notificationURLList, topic, userName, pass);
+ AutoClientDMAAP.setAuto(scheme, handler);
+ this.registerDMAAPThread = new Thread(this.dmaapClientThread);
+ this.registerDMAAPThread.start();
+ this.dmaapThread = true;
+ } else {
+ if (pdps.get(0) != null) {
+ if (AutoClientEnd.getUrl() == null) {
+ AutoClientEnd.start(pdps.get(0));
+ } else {
+ AutoClientEnd.stop();
+ AutoClientEnd.start(pdps.get(0));
}
}
}
@@ -1227,7 +1235,7 @@ public class StdPolicyEngine {
/*
* Create Config Policy API Implementation
*/
- public String createUpdateConfigPolicyImpl(final String policyName, final String policyDescription,
+ private String createUpdateConfigPolicyImpl(final String policyName, final String policyDescription,
final String onapName, final String configName, final Map<String, String> configAttributes,
final String configType, final String body, final String policyScope, final UUID requestID,
final String riskLevel, final String riskType, final String guard, final String ttlDate,
@@ -1276,7 +1284,7 @@ public class StdPolicyEngine {
/*
* Create Update Config Firewall Policy API implementation
*/
- public String createUpdateConfigFirewallPolicyImpl(final String policyName, final JsonObject firewallJson,
+ private String createUpdateConfigFirewallPolicyImpl(final String policyName, final JsonObject firewallJson,
final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
validateParameters(policyName, policyScope);
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/std/NotificationStore.java b/PolicyEngineUtils/src/main/java/org/onap/policy/std/NotificationStore.java
index 24e126386..6164418d9 100644
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/std/NotificationStore.java
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/std/NotificationStore.java
@@ -3,6 +3,7 @@
* PolicyEngineUtils
* ================================================================================
* Copyright (C) 2017 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.
@@ -41,8 +42,8 @@ public class NotificationStore {
private static StdPDPNotification notificationRecord = new StdPDPNotification();
private NotificationStore () {
- // Sonar prefers that we have an empty public constructor
- // as opposed to an implicit public constructor.
+ // Sonar prefers that we have an empty public constructor
+ // as opposed to an implicit public constructor.
}
public static StdPDPNotification getDeltaNotification(StdPDPNotification newNotification) {
@@ -63,195 +64,218 @@ public class NotificationStore {
}
return notificationDelta;
}
+
+ if (newNotification == null) {
+ return notificationDelta;
+ }
// do the Delta operation.
- if (newNotification != null) {
- // check for old removed policies.
- if (!newNotification.getRemovedPolicies().isEmpty()) {
- for (RemovedPolicy newRemovedPolicy : newNotification.getRemovedPolicies()) {
- //Look for policy Not in Remove
- Boolean removed = true;
- String policyName = newRemovedPolicy.getPolicyName();
- String ver = newRemovedPolicy.getVersionNo();
- for (RemovedPolicy oldRemovedPolicy : notificationRecord.getRemovedPolicies()) {
- if (policyName.equals(oldRemovedPolicy.getPolicyName())
- && ver.equals(oldRemovedPolicy.getVersionNo())) {
- removed = false;
- // Don't want a duplicate.
- oldRemovedPolicies.remove(oldRemovedPolicy);
- }
- }
- //We need to change our record we have an Update record of this remove.
- for (LoadedPolicy oldUpdatedPolicy : notificationRecord.getLoadedPolicies()) {
- if (policyName.equals(oldUpdatedPolicy.getPolicyName())
- && ver.equals(oldUpdatedPolicy.getVersionNo())) {
- oldUpdatedPolicies.remove(oldUpdatedPolicy);
- oldUpdatedLostPolicies.remove(oldUpdatedPolicy);
- }
- }
- if (removed) {
- remove = true;
- notificationRecord.getRemovedPolicies().add(newRemovedPolicy);
- removedDelta.add((StdRemovedPolicy) newRemovedPolicy);
- }
- // This will be converted to New Later.
- oldRemovedPolicies.add(newRemovedPolicy);
- }
+ // check for old removed policies.
+ if (!newNotification.getRemovedPolicies().isEmpty()) {
+ for (RemovedPolicy newRemovedPolicy : newNotification.getRemovedPolicies()) {
+ remove = updateRemovedPolicies(removedDelta, oldUpdatedLostPolicies, oldRemovedPolicies, oldUpdatedPolicies, remove, newRemovedPolicy);
}
- // Check for old Updated Policies.
- if (!newNotification.getLoadedPolicies().isEmpty()) {
- for (LoadedPolicy newUpdatedPolicy : newNotification.getLoadedPolicies()) {
- // Look for policies which are not in Update
- Boolean updated = true;
- String policyName = newUpdatedPolicy.getPolicyName();
- String ver = newUpdatedPolicy.getVersionNo();
- for (LoadedPolicy oldUpdatedPolicy : notificationRecord.getLoadedPolicies()) {
- if (policyName.equals(oldUpdatedPolicy.getPolicyName())
- && ver.equals(oldUpdatedPolicy.getVersionNo())) {
- updated = false;
- // Remove the policy from copy.
- oldUpdatedLostPolicies.remove(oldUpdatedPolicy);
- // Eliminating Duplicate.
- oldUpdatedPolicies.remove(oldUpdatedPolicy);
- }
- }
- // Change the record if the policy has been Removed earlier.
- for (RemovedPolicy oldRemovedPolicy : notificationRecord.getRemovedPolicies()) {
- if (oldRemovedPolicy.getPolicyName().equals(policyName)
- && oldRemovedPolicy.getVersionNo().equals(ver)) {
- oldRemovedPolicies.remove(oldRemovedPolicy);
- }
- }
- if (updated) {
- update = true;
- updatedDelta.add((StdLoadedPolicy) newUpdatedPolicy);
- }
- // This will be converted to new Later
- oldUpdatedPolicies.add(newUpdatedPolicy);
- }
- // Conversion of Update to Remove if that occurred.
- if (!oldUpdatedLostPolicies.isEmpty()) {
- for (LoadedPolicy updatedPolicy : oldUpdatedLostPolicies) {
- StdRemovedPolicy removedPolicy = new StdRemovedPolicy();
- removedPolicy.setPolicyName(updatedPolicy.getPolicyName());
- removedPolicy.setVersionNo(updatedPolicy.getVersionNo());
- removedDelta.add(removedPolicy);
- remove = true;
- }
- }
+ }
+ // Check for old Updated Policies.
+ if (!newNotification.getLoadedPolicies().isEmpty()) {
+ for (LoadedPolicy newUpdatedPolicy : newNotification.getLoadedPolicies()) {
+ update = modifyUpdatedPolicies(updatedDelta, oldUpdatedLostPolicies, oldRemovedPolicies, oldUpdatedPolicies, update, newUpdatedPolicy);
}
- // Update our Record.
- if (!oldUpdatedPolicies.isEmpty()) {
- for (LoadedPolicy updatedPolicy : oldUpdatedPolicies) {
- newUpdatedPolicies.add((StdLoadedPolicy) updatedPolicy);
+ // Conversion of Update to Remove if that occurred.
+ if (!oldUpdatedLostPolicies.isEmpty()) {
+ for (LoadedPolicy updatedPolicy : oldUpdatedLostPolicies) {
+ StdRemovedPolicy removedPolicy = new StdRemovedPolicy();
+ removedPolicy.setPolicyName(updatedPolicy.getPolicyName());
+ removedPolicy.setVersionNo(updatedPolicy.getVersionNo());
+ removedDelta.add(removedPolicy);
+ remove = true;
}
}
- if (!oldRemovedPolicies.isEmpty()) {
- for (RemovedPolicy removedPolicy : oldRemovedPolicies) {
- newRemovedPolicies.add((StdRemovedPolicy) removedPolicy);
- }
+ }
+ // Update our Record.
+ if (!oldUpdatedPolicies.isEmpty()) {
+ for (LoadedPolicy updatedPolicy : oldUpdatedPolicies) {
+ newUpdatedPolicies.add((StdLoadedPolicy) updatedPolicy);
}
- notificationRecord.setRemovedPolicies(newRemovedPolicies);
- notificationRecord.setLoadedPolicies(newUpdatedPolicies);
- // Update the notification Result.
- notificationDelta.setRemovedPolicies(removedDelta);
- notificationDelta.setLoadedPolicies(updatedDelta);
- if (remove && update) {
- notificationDelta.setNotificationType(NotificationType.BOTH);
- } else if (remove) {
- notificationDelta.setNotificationType(NotificationType.REMOVE);
- } else if (update) {
- notificationDelta.setNotificationType(NotificationType.UPDATE);
+ }
+ if (!oldRemovedPolicies.isEmpty()) {
+ for (RemovedPolicy removedPolicy : oldRemovedPolicies) {
+ newRemovedPolicies.add((StdRemovedPolicy) removedPolicy);
}
}
+ notificationRecord.setRemovedPolicies(newRemovedPolicies);
+ notificationRecord.setLoadedPolicies(newUpdatedPolicies);
+ // Update the notification Result.
+ notificationDelta.setRemovedPolicies(removedDelta);
+ notificationDelta.setLoadedPolicies(updatedDelta);
+ if (remove && update) {
+ notificationDelta.setNotificationType(NotificationType.BOTH);
+ } else if (remove) {
+ notificationDelta.setNotificationType(NotificationType.REMOVE);
+ } else if (update) {
+ notificationDelta.setNotificationType(NotificationType.UPDATE);
+ }
+
return notificationDelta;
}
+ private static Boolean modifyUpdatedPolicies(ArrayList<StdLoadedPolicy> updatedDelta, Collection<LoadedPolicy> oldUpdatedLostPolicies, Collection<RemovedPolicy> oldRemovedPolicies, Collection<LoadedPolicy> oldUpdatedPolicies, Boolean update, LoadedPolicy newUpdatedPolicy) {
+ // Look for policies which are not in Update
+ Boolean updated = true;
+ String policyName = newUpdatedPolicy.getPolicyName();
+ String ver = newUpdatedPolicy.getVersionNo();
+ for (LoadedPolicy oldUpdatedPolicy : notificationRecord.getLoadedPolicies()) {
+ if (policyName.equals(oldUpdatedPolicy.getPolicyName())
+ && ver.equals(oldUpdatedPolicy.getVersionNo())) {
+ updated = false;
+ // Remove the policy from copy.
+ oldUpdatedLostPolicies.remove(oldUpdatedPolicy);
+ // Eliminating Duplicate.
+ oldUpdatedPolicies.remove(oldUpdatedPolicy);
+ }
+ }
+ // Change the record if the policy has been Removed earlier.
+ for (RemovedPolicy oldRemovedPolicy : notificationRecord.getRemovedPolicies()) {
+ if (oldRemovedPolicy.getPolicyName().equals(policyName)
+ && oldRemovedPolicy.getVersionNo().equals(ver)) {
+ oldRemovedPolicies.remove(oldRemovedPolicy);
+ }
+ }
+ if (updated) {
+ update = true;
+ updatedDelta.add((StdLoadedPolicy) newUpdatedPolicy);
+ }
+ // This will be converted to new Later
+ oldUpdatedPolicies.add(newUpdatedPolicy);
+ return update;
+ }
+
+ private static Boolean updateRemovedPolicies(ArrayList<StdRemovedPolicy> removedDelta, Collection<LoadedPolicy> oldUpdatedLostPolicies, Collection<RemovedPolicy> oldRemovedPolicies, Collection<LoadedPolicy> oldUpdatedPolicies, Boolean remove, RemovedPolicy newRemovedPolicy) {
+ //Look for policy Not in Remove
+ Boolean removed = true;
+ String policyName = newRemovedPolicy.getPolicyName();
+ String ver = newRemovedPolicy.getVersionNo();
+ for (RemovedPolicy oldRemovedPolicy : notificationRecord.getRemovedPolicies()) {
+ if (policyName.equals(oldRemovedPolicy.getPolicyName())
+ && ver.equals(oldRemovedPolicy.getVersionNo())) {
+ removed = false;
+ // Don't want a duplicate.
+ oldRemovedPolicies.remove(oldRemovedPolicy);
+ }
+ }
+ //We need to change our record we have an Update record of this remove.
+ for (LoadedPolicy oldUpdatedPolicy : notificationRecord.getLoadedPolicies()) {
+ if (policyName.equals(oldUpdatedPolicy.getPolicyName())
+ && ver.equals(oldUpdatedPolicy.getVersionNo())) {
+ oldUpdatedPolicies.remove(oldUpdatedPolicy);
+ oldUpdatedLostPolicies.remove(oldUpdatedPolicy);
+ }
+ }
+ if (removed) {
+ remove = true;
+ notificationRecord.getRemovedPolicies().add(newRemovedPolicy);
+ removedDelta.add((StdRemovedPolicy) newRemovedPolicy);
+ }
+ // This will be converted to New Later.
+ oldRemovedPolicies.add(newRemovedPolicy);
+ return remove;
+ }
+
public static void recordNotification(StdPDPNotification notification) {
- if (notification != null) {
- if (notificationRecord.getRemovedPolicies() == null || notificationRecord.getLoadedPolicies() == null) {
- notificationRecord = notification;
- } else {
- // Check if there is anything new and update the record.
- if (notificationRecord.getLoadedPolicies() != null || notificationRecord.getRemovedPolicies() != null) {
- HashSet<StdRemovedPolicy> removedPolicies = new HashSet<>();
- for (RemovedPolicy rPolicy : notificationRecord.getRemovedPolicies()) {
- StdRemovedPolicy sRPolicy = new StdRemovedPolicy();
- sRPolicy.setPolicyName(rPolicy.getPolicyName());
- sRPolicy.setVersionNo(rPolicy.getVersionNo());
- removedPolicies.add(sRPolicy);
- }
- HashSet<StdLoadedPolicy> updatedPolicies = new HashSet<>();
- for (LoadedPolicy uPolicy : notificationRecord.getLoadedPolicies()) {
- StdLoadedPolicy sUPolicy = new StdLoadedPolicy();
- sUPolicy.setMatches(uPolicy.getMatches());
- sUPolicy.setPolicyName(uPolicy.getPolicyName());
- sUPolicy.setVersionNo(uPolicy.getVersionNo());
- sUPolicy.setUpdateType(uPolicy.getUpdateType());
- updatedPolicies.add(sUPolicy);
- }
+ if (notification == null) {
+ return;
+ }
- // Checking with the new updated policies.
- if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) {
- for (LoadedPolicy newUpdatedPolicy : notification.getLoadedPolicies()) {
- // If it was removed earlier then we need to remove from our record
- Iterator<StdRemovedPolicy> oldRemovedPolicy = removedPolicies.iterator();
- String policyName = newUpdatedPolicy.getPolicyName();
- String ver = newUpdatedPolicy.getVersionNo();
- while (oldRemovedPolicy.hasNext()) {
- RemovedPolicy policy = oldRemovedPolicy.next();
- if (policyName.equals(policy.getPolicyName())
- && ver.equals(policy.getVersionNo())) {
- oldRemovedPolicy.remove();
- }
- }
- // If it was previously updated need to Overwrite it to the record.
- updatedPolicies.removeIf(policy -> policyName.equals(policy.getPolicyName())
- && ver.equals(policy.getVersionNo()));
+ if (notificationRecord.getRemovedPolicies() == null || notificationRecord.getLoadedPolicies() == null) {
+ notificationRecord = notification;
+ } else {
+ // Check if there is anything new and update the record.
+ if (notificationRecord.getLoadedPolicies() != null || notificationRecord.getRemovedPolicies() != null) {
+ HashSet<StdRemovedPolicy> removedPolicies = new HashSet<>();
+ for (RemovedPolicy rPolicy : notificationRecord.getRemovedPolicies()) {
+ StdRemovedPolicy sRPolicy = new StdRemovedPolicy();
+ sRPolicy.setPolicyName(rPolicy.getPolicyName());
+ sRPolicy.setVersionNo(rPolicy.getVersionNo());
+ removedPolicies.add(sRPolicy);
+ }
+ HashSet<StdLoadedPolicy> updatedPolicies = new HashSet<>();
+ for (LoadedPolicy uPolicy : notificationRecord.getLoadedPolicies()) {
+ StdLoadedPolicy sUPolicy = new StdLoadedPolicy();
+ sUPolicy.setMatches(uPolicy.getMatches());
+ sUPolicy.setPolicyName(uPolicy.getPolicyName());
+ sUPolicy.setVersionNo(uPolicy.getVersionNo());
+ sUPolicy.setUpdateType(uPolicy.getUpdateType());
+ updatedPolicies.add(sUPolicy);
+ }
- StdLoadedPolicy sUPolicy = new StdLoadedPolicy();
- sUPolicy.setMatches(newUpdatedPolicy.getMatches());
- sUPolicy.setPolicyName(newUpdatedPolicy.getPolicyName());
- sUPolicy.setVersionNo(newUpdatedPolicy.getVersionNo());
- sUPolicy.setUpdateType(newUpdatedPolicy.getUpdateType());
- updatedPolicies.add(sUPolicy);
- }
- }
- // Checking with New Removed Policies.
- if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) {
- for (RemovedPolicy newRemovedPolicy : notification.getRemovedPolicies()) {
- // If it was previously removed Overwrite it to the record.
- Iterator<StdRemovedPolicy> oldRemovedPolicy = removedPolicies.iterator();
- String policyName = newRemovedPolicy.getPolicyName();
- String ver = newRemovedPolicy.getVersionNo();
- while (oldRemovedPolicy.hasNext()) {
- RemovedPolicy policy = oldRemovedPolicy.next();
- if (policyName.equals(policy.getPolicyName())
- && ver.equals(policy.getVersionNo())) {
- oldRemovedPolicy.remove();
- }
- }
- // If it was added earlier then we need to remove from our record.
- updatedPolicies.removeIf(policy -> policyName.equals(policy.getPolicyName())
- && ver.equals(policy.getVersionNo()));
+ // Checking with the new updated policies.
+ if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) {
+ checkNewUpdatedPolicies(notification, removedPolicies, updatedPolicies);
+ }
+ // Checking with New Removed Policies.
+ if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) {
+ checkNewRemovedPolicies(notification, removedPolicies, updatedPolicies);
+ }
+ notificationRecord.setRemovedPolicies(removedPolicies);
+ notificationRecord.setLoadedPolicies(updatedPolicies);
+ }
+ if (!notificationRecord.getLoadedPolicies().isEmpty() && !notificationRecord.getRemovedPolicies()
+ .isEmpty()) {
+ notificationRecord.setNotificationType(NotificationType.BOTH);
+ } else if (!notificationRecord.getLoadedPolicies().isEmpty()) {
+ notificationRecord.setNotificationType(NotificationType.UPDATE);
+ } else if (!notificationRecord.getRemovedPolicies().isEmpty()) {
+ notificationRecord.setNotificationType(NotificationType.REMOVE);
+ }
+ }
+ }
- StdRemovedPolicy sRPolicy = new StdRemovedPolicy();
- sRPolicy.setPolicyName(policyName);
- sRPolicy.setVersionNo(ver);
- removedPolicies.add(sRPolicy);
- }
- }
- notificationRecord.setRemovedPolicies(removedPolicies);
- notificationRecord.setLoadedPolicies(updatedPolicies);
+ private static void checkNewUpdatedPolicies(StdPDPNotification notification, HashSet<StdRemovedPolicy> removedPolicies, HashSet<StdLoadedPolicy> updatedPolicies) {
+ for (LoadedPolicy newUpdatedPolicy : notification.getLoadedPolicies()) {
+ // If it was removed earlier then we need to remove from our record
+ Iterator<StdRemovedPolicy> oldRemovedPolicy = removedPolicies.iterator();
+ String policyName = newUpdatedPolicy.getPolicyName();
+ String ver = newUpdatedPolicy.getVersionNo();
+ while (oldRemovedPolicy.hasNext()) {
+ RemovedPolicy policy = oldRemovedPolicy.next();
+ if (policyName.equals(policy.getPolicyName())
+ && ver.equals(policy.getVersionNo())) {
+ oldRemovedPolicy.remove();
}
- if (!notificationRecord.getLoadedPolicies().isEmpty() && !notificationRecord.getRemovedPolicies()
- .isEmpty()) {
- notificationRecord.setNotificationType(NotificationType.BOTH);
- } else if (!notificationRecord.getLoadedPolicies().isEmpty()) {
- notificationRecord.setNotificationType(NotificationType.UPDATE);
- } else if (!notificationRecord.getRemovedPolicies().isEmpty()) {
- notificationRecord.setNotificationType(NotificationType.REMOVE);
+ }
+ // If it was previously updated need to Overwrite it to the record.
+ updatedPolicies.removeIf(policy -> policyName.equals(policy.getPolicyName())
+ && ver.equals(policy.getVersionNo()));
+
+ StdLoadedPolicy sUPolicy = new StdLoadedPolicy();
+ sUPolicy.setMatches(newUpdatedPolicy.getMatches());
+ sUPolicy.setPolicyName(newUpdatedPolicy.getPolicyName());
+ sUPolicy.setVersionNo(newUpdatedPolicy.getVersionNo());
+ sUPolicy.setUpdateType(newUpdatedPolicy.getUpdateType());
+ updatedPolicies.add(sUPolicy);
+ }
+ }
+
+ private static void checkNewRemovedPolicies(StdPDPNotification notification, HashSet<StdRemovedPolicy> removedPolicies, HashSet<StdLoadedPolicy> updatedPolicies) {
+ for (RemovedPolicy newRemovedPolicy : notification.getRemovedPolicies()) {
+ // If it was previously removed Overwrite it to the record.
+ Iterator<StdRemovedPolicy> oldRemovedPolicy = removedPolicies.iterator();
+ String policyName = newRemovedPolicy.getPolicyName();
+ String ver = newRemovedPolicy.getVersionNo();
+ while (oldRemovedPolicy.hasNext()) {
+ RemovedPolicy policy = oldRemovedPolicy.next();
+ if (policyName.equals(policy.getPolicyName())
+ && ver.equals(policy.getVersionNo())) {
+ oldRemovedPolicy.remove();
}
}
+ // If it was added earlier then we need to remove from our record.
+ updatedPolicies.removeIf(policy -> policyName.equals(policy.getPolicyName())
+ && ver.equals(policy.getVersionNo()));
+
+ StdRemovedPolicy sRPolicy = new StdRemovedPolicy();
+ sRPolicy.setPolicyName(policyName);
+ sRPolicy.setVersionNo(ver);
+ removedPolicies.add(sRPolicy);
}
}