diff options
author | ITSERVICES\rb7147 <rb7147@att.com> | 2017-04-25 11:46:00 -0400 |
---|---|---|
committer | ITSERVICES\rb7147 <rb7147@att.com> | 2017-05-03 09:58:17 -0400 |
commit | e0addf5b588a1244f9679becd90999dfcb4c3a94 (patch) | |
tree | 1212772d6366730266ff0e093c874b07aa716c29 /ECOMP-PDP-REST/src/main | |
parent | 39fb0f30472777e4b60d6a7ac8aa4eb9773961ff (diff) |
Policy 1707 commit to LF
Change-Id: Ibe6f01d92f9a434c040abb05d5386e89d675ae65
Signed-off-by: ITSERVICES\rb7147 <rb7147@att.com>
Diffstat (limited to 'ECOMP-PDP-REST/src/main')
52 files changed, 7025 insertions, 477 deletions
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java index d9a3688b4..44a1f5e17 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java @@ -35,7 +35,7 @@ import com.att.research.xacml.util.XACMLProperties; import org.openecomp.policy.common.logging.flexlogger.*; public class PapUrlResolver { - private static final Logger logger = FlexLogger.getLogger(PapUrlResolver.class); + private static final Logger LOGGER = FlexLogger.getLogger(PapUrlResolver.class); //how long to keep a pap failed before making it un-failed, in milli-seconds private static final long FAIL_TIMEOUT = 18000000; @@ -177,7 +177,7 @@ public class PapUrlResolver { //sets the current PAP url as being failed //this will set the failed time to now and remove any succeeded time public void failed(){ - logger.error("PAP Server FAILED: "+sortedUrlNodes[pointer].getUrl()); + LOGGER.error("PAP Server FAILED: "+sortedUrlNodes[pointer].getUrl()); sortedUrlNodes[pointer].setFailedTime(new Date()); sortedUrlNodes[pointer].setSucceededTime(null); @@ -195,7 +195,7 @@ public class PapUrlResolver { public void registered(){ sortedUrlNodes[pointer].setFailedTime(null); sortedUrlNodes[pointer].setSucceededTime(new Date()); - logger.info("PAP server SUCCEEDED "+sortedUrlNodes[pointer].getUrl()); + LOGGER.info("PAP server SUCCEEDED "+sortedUrlNodes[pointer].getUrl()); propertiesUpdated(); } @@ -226,8 +226,8 @@ public class PapUrlResolver { } Properties prop = getProperties(); - logger.debug("Failed PAP Url List: "+prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); - logger.debug("Succeeded PAP Url List: "+prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS)); + LOGGER.debug("Failed PAP Url List: "+prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); + LOGGER.debug("Succeeded PAP Url List: "+prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS)); XACMLProperties.setProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS,prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); XACMLProperties.setProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS,prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS)); } @@ -287,14 +287,6 @@ public class PapUrlResolver { private String userId; private String pass; - public PapUrlNode(String url){ - this.papUrl = url; - failedTime = null; - this.succeededTime = null; - this.userId = ""; - this.pass = ""; - - } public PapUrlNode(String url,String userId,String pass){ this.papUrl = url; failedTime = null; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java index 9c5b120c3..b4433036b 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java @@ -73,14 +73,14 @@ import com.google.common.base.Splitter; * */ public class XACMLPdpLoader { - private static final Logger logger = FlexLogger.getLogger(XACMLPdpLoader.class); + private static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpLoader.class); private static NotificationController notificationController = new NotificationController(); private static final Long notifyDelay = (long) XACMLPdpServlet.getNotificationDelay(); public static synchronized PDPEngine loadEngine(StdPDPStatus status, Properties policyProperties, Properties pipProperties) { - logger.info("loadEngine: " + policyProperties + " " + pipProperties); + LOGGER.info("loadEngine: " + policyProperties + " " + pipProperties); // // First load our policies // @@ -112,19 +112,15 @@ public class XACMLPdpLoader { // Validate the policies // XACMLPdpLoader.validatePolicies(policyProperties, status); - if (logger.isDebugEnabled()) { - logger.debug("Status: " + status); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Status: " + status); } } catch (ConcurrentModificationException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e.getMessage()); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, ""); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e.getMessage()); } catch (Exception e) { String error = "Failed to load Policy Cache properties file: " + e.getMessage(); - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + error, e); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, error); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + error, e); status.addLoadError(error); status.setStatus(PDPStatus.Status.LOAD_ERRORS); } @@ -148,15 +144,13 @@ public class XACMLPdpLoader { // Validate our PIP configurations // XACMLPdpLoader.validatePipConfiguration(pipProperties, status); - if (logger.isDebugEnabled()) { - logger.debug("Status: " + status); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Status: " + status); } } catch (Exception e) { String error = "Failed to load/validate Pip Config properties file: " + e.getMessage(); - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + error, e); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, error); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + error, e); status.addLoadError(XACMLErrorConstants.ERROR_PROCESS_FLOW + error); status.setStatus(PDPStatus.Status.LOAD_ERRORS); } @@ -164,9 +158,7 @@ public class XACMLPdpLoader { // Were they validated? // if (status.getStatus() == Status.LOAD_ERRORS) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"there were load errors"); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"there were load errors"); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"there were load errors"); return null; } // @@ -178,11 +170,9 @@ public class XACMLPdpLoader { // Dump ALL our properties that we are trying to load // try { - logger.info(XACMLProperties.getProperties().toString()); + LOGGER.info(XACMLProperties.getProperties().toString()); } catch (IOException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to get XACML Properties", e); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Failed to get XACML Properties"); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to get XACML Properties", e); } // // Now load the PDP engine @@ -192,13 +182,11 @@ public class XACMLPdpLoader { try { factory = PDPEngineFactory.newInstance(); engine = factory.newEngine(); - logger.info("Loaded new PDP engine."); + LOGGER.info("Loaded new PDP engine."); status.setStatus(Status.UP_TO_DATE); } catch (FactoryException e) { String error = "Failed to create new PDP Engine"; - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +error, e); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, error); + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +error, e); status.addLoadError(error); } // Notification will be Sent Here. @@ -215,9 +203,7 @@ public class XACMLPdpLoader { Thread.sleep(notifyDelay); NotificationController.sendNotification(); }catch(Exception e){ - logger.error(XACMLErrorConstants.ERROR_UNKNOWN + e); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, ""); + LOGGER.error(XACMLErrorConstants.ERROR_UNKNOWN + e); } } }; @@ -240,14 +226,13 @@ public class XACMLPdpLoader { for (String id : refPolicies) { loadPolicy(properties, status, id, false); } - logger.info("Loaded " + status.getLoadedPolicies().size() + LOGGER.info("Loaded " + status.getLoadedPolicies().size() + " policies, failed to load " + status.getFailedPolicies().size() + " policies, " + status.getLoadedRootPolicies().size() + " root policies"); - // TODO Notification Controller is here.. notificationController.check(status, policyContainer); if (status.getLoadedRootPolicies().size() == 0) { - logger.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW +"NO ROOT POLICIES LOADED!!! Cannot serve PEP Requests."); + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW +"NO ROOT POLICIES LOADED!!! Cannot serve PEP Requests."); status.addLoadWarning("NO ROOT POLICIES LOADED!!! Cannot serve PEP Requests."); } policyContainer.clear(); @@ -271,12 +256,12 @@ public class XACMLPdpLoader { } catch (Exception e){ // This Happens if a any issue with the error policyFile. Lets remove it. try { - logger.error("Corrupted policy file, deleting: " + location); + LOGGER.error("Corrupted policy file, deleting: " + location); Files.delete(Paths.get(location)); properties.remove(id + ".file"); rougeFile = true; } catch (IOException e1) { - logger.error(e1); + LOGGER.error(e1); } } } @@ -301,7 +286,6 @@ public class XACMLPdpLoader { String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); locationURI = URI.create(papUrls.getUrl(PapUrlResolver.extractIdFromUrl(location))); URL url = locationURI.toURL(); - //FIXME: modify me URLConnection urlConnection = null; try{ urlConnection = url.openConnection(); @@ -337,13 +321,13 @@ public class XACMLPdpLoader { policy = DOMPolicyDef.load(fis); }catch(Exception e){ try { - logger.error("Corrupted policy file, deleting: " + location); + LOGGER.error("Corrupted policy file, deleting: " + location); Files.delete(outFile); error = true; errorCount++; break; } catch (IOException e1) { - logger.error(e1); + LOGGER.error(e1); } } // @@ -360,25 +344,20 @@ public class XACMLPdpLoader { if (policy != null) { status.addLoadedPolicy(new StdPDPPolicy(id, isRoot, locationURI, properties)); - logger.info("Loaded policy: " + policy.getIdentifier() + LOGGER.info("Loaded policy: " + policy.getIdentifier() + " version: " + policy.getVersion().stringValue()); // Sending the policy objects to the Notification Controller. policyContainer.put(id, policy); } else { String error = "Failed to load policy " + location; - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + error); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, error); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + error); status.setStatus(PDPStatus.Status.LOAD_ERRORS); status.addLoadError(error); status.addFailedPolicy(new StdPDPPolicy(id, isRoot)); } } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"Failed to load policy '" + id + "' from location '" + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"Failed to load policy '" + id + "' from location '" + location + "'", e); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Failed to load policy '" + id + "' from location '" - // + location + "'"); status.setStatus(PDPStatus.Status.LOAD_ERRORS); status.addFailedPolicy(new StdPDPPolicy(id, isRoot)); // @@ -389,18 +368,13 @@ public class XACMLPdpLoader { // Let's remove it // try { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Corrupted policy file, deleting: " + location); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Corrupted policy file, deleting: " + location); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Corrupted policy file, deleting: " + location); Files.delete(Paths.get(location)); } catch (IOException e1) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e1); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e1, ""); + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e1); } } - //throw new PAPException("Failed to load policy '" + id + "' from location '" + location + "'"); } } @@ -419,24 +393,20 @@ public class XACMLPdpLoader { // Check for this, although it should always return something // if (finder == null) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "pip finder factory returned a null engine."); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "pip finder factory returned a null engine."); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "pip finder factory returned a null engine."); throw new PIPException("Could not create PIP Finder"); } else { - logger.info("Loaded PIP finder"); + LOGGER.info("Loaded PIP finder"); } for (PIPEngine engine : finder.getPIPEngines()) { - logger.info("Configured PIP Engine: " + engine.getName()); + LOGGER.info("Configured PIP Engine: " + engine.getName()); StdPDPPIPConfig config = new StdPDPPIPConfig(); config.setName(engine.getName()); status.addLoadedPipConfig(config); } } catch (FactoryException | PIPException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "validate PIP configuration failed: " + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "validate PIP configuration failed: " + e.getLocalizedMessage()); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e.getLocalizedMessage(), "validate PIP configuration failed"); status.addLoadError(e.getLocalizedMessage()); status.setStatus(Status.LOAD_ERRORS); throw new PAPException(e); @@ -486,7 +456,7 @@ public class XACMLPdpLoader { // policyExists = Files.exists(Paths.get(propLocation)); if (policyExists == false) { - logger.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy file " + policy + " expected at " + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy file " + policy + " expected at " + propLocation + " does NOT exist."); } } @@ -509,7 +479,7 @@ public class XACMLPdpLoader { // Set the property so the PDP engine doesn't have // to pull it from the URL but rather the FILE. // - logger.info("Policy does exist: " + LOGGER.info("Policy does exist: " + outFile.toAbsolutePath().toString()); props.setProperty(policy + StdPolicyFinderFactory.PROP_FILE, outFile @@ -546,7 +516,7 @@ public class XACMLPdpLoader { // Create the URL // url = new URL(papUrls.getUrl(PapUrlResolver.extractIdFromUrl(propLocation))); - logger.info("Pulling " + url.toString()); + LOGGER.info("Pulling " + url.toString()); // // Open the connection // @@ -566,7 +536,7 @@ public class XACMLPdpLoader { // // Now save it in the properties as a .file // - logger.info("Pulled policy: " + LOGGER.info("Pulled policy: " + outFile.toAbsolutePath().toString()); props.setProperty(policy + StdPolicyFinderFactory.PROP_FILE, @@ -580,36 +550,23 @@ public class XACMLPdpLoader { } catch (Exception e) { papUrls.failed(); if (e instanceof MalformedURLException) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy '" + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy '" + policy + "' had bad URL in new configuration, URL='" + propLocation + "'"); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Policy '" - // + policy - // + "' had bad URL in new configuration, URL='" - // + propLocation + "'"); } else { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while retrieving policy " + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while retrieving policy " + policy + " from URL " + url.toString() + ", e=" + e); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Error while retrieving policy " - // + policy - // + " from URL " - // + url.toString()); } } papUrls.getNext(); } } else { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy " + policy + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy " + policy + " does NOT exist and does NOT have a URL"); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Policy " + policy - // + " does NOT exist and does NOT have a URL"); } } } @@ -623,7 +580,7 @@ public class XACMLPdpLoader { Path policyProperties = Paths.get(config.toAbsolutePath().toString(), "xacml.policy.properties"); if (Files.notExists(policyProperties)) { - logger.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + policyProperties.toAbsolutePath().toString() + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + policyProperties.toAbsolutePath().toString() + " does NOT exist."); // // Try to create the file @@ -631,11 +588,8 @@ public class XACMLPdpLoader { try { Files.createFile(policyProperties); } catch (IOException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create policy properties file: " + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create policy properties file: " + policyProperties.toAbsolutePath().toString()); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Failed to create policy properties file: " - // + policyProperties.toAbsolutePath().toString()); throw new PAPException( "Failed to create policy properties file: " + policyProperties.toAbsolutePath().toString()); @@ -649,7 +603,7 @@ public class XACMLPdpLoader { Path pipConfigProperties = Paths.get( config.toAbsolutePath().toString(), "xacml.pip.properties"); if (Files.notExists(pipConfigProperties)) { - logger.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + pipConfigProperties.toAbsolutePath().toString() + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + pipConfigProperties.toAbsolutePath().toString() + " does NOT exist."); // // Try to create the file @@ -657,11 +611,8 @@ public class XACMLPdpLoader { try { Files.createFile(pipConfigProperties); } catch (IOException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create pip properties file: " + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create pip properties file: " + pipConfigProperties.toAbsolutePath().toString()); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Failed to create pip properties file: " - //+ pipConfigProperties.toAbsolutePath().toString()); throw new PAPException("Failed to create pip properties file: " + pipConfigProperties.toAbsolutePath().toString()); } @@ -673,18 +624,15 @@ public class XACMLPdpLoader { Path config = Paths.get(XACMLProperties .getProperty(XACMLRestProperties.PROP_PDP_CONFIG)); if (Files.notExists(config)) { - logger.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + config.toAbsolutePath().toString() + " does NOT exist."); + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + config.toAbsolutePath().toString() + " does NOT exist."); // // Try to create the directory // try { Files.createDirectories(config); } catch (IOException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: " + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: " + config.toAbsolutePath().toString(), e); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Failed to create config directory: " - //+ config.toAbsolutePath().toString()); throw new PAPException("Failed to create config directory: " + config.toAbsolutePath().toString()); } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpRegisterThread.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpRegisterThread.java index 83b9f3cf7..e9b665823 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpRegisterThread.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpRegisterThread.java @@ -46,7 +46,7 @@ import org.openecomp.policy.common.logging.eelf.PolicyLogger; import org.openecomp.policy.common.logging.flexlogger.*; public class XACMLPdpRegisterThread implements Runnable { - private static final Logger logger = FlexLogger.getLogger(XACMLPdpRegisterThread.class); + private static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpRegisterThread.class); private static final Logger auditLogger = FlexLogger.getLogger("auditLogger"); private ECOMPLoggingContext baseLoggingContext = null; @@ -87,7 +87,7 @@ public class XACMLPdpRegisterThread implements Runnable { try { seconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_SLEEP)); } catch (NumberFormatException e) { - logger.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR +"REGISTER_SLEEP: ", e); + LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR +"REGISTER_SLEEP: ", e); seconds = 5; } if (seconds < 5) { @@ -97,7 +97,7 @@ public class XACMLPdpRegisterThread implements Runnable { try { retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_RETRIES)); } catch (NumberFormatException e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +" REGISTER_SLEEP: ", e); + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +" REGISTER_SLEEP: ", e); retries = -1; } */ @@ -109,9 +109,7 @@ public class XACMLPdpRegisterThread implements Runnable { try(InputStream pipFile = Files.newInputStream(XACMLPdpLoader.getPIPConfig())){ tempPipConfigProperties.load(pipFile); } catch(Exception e){ - logger.error("Failed to open PIP property file", e); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPdpRegisterThread", "Failed to open PIP property file"); + LOGGER.error("Failed to open PIP property file", e); } while(papUrls.hasMoreUrls()){ String papID = papUrls.getUserId(); @@ -135,7 +133,7 @@ public class XACMLPdpRegisterThread implements Runnable { //String[] papUrls = papUrlList.split(","); //PapUrlResolver.setPapUrls(papUrls); URL url = new URL(papUrls.getUrl()); - logger.info("Registering with " + url.toString()); + LOGGER.info("Registering with " + url.toString()); //PolicyLogger.info("new transaction (request) ID and update to logging context in XACMLPdpRegisterThread"); boolean finished = false; while (! finished) { @@ -181,42 +179,31 @@ public class XACMLPdpRegisterThread implements Runnable { tempPipConfigProperties.store(os, ""); } } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Failed to send property file", e); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to send property file"); + 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."); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.info("Success. We are configured correctly."); + LOGGER.info("Success. We are configured correctly."); loggingContext.transactionEnded(); - // auditLogger.info("Success. We are configured correctly."); - // TODO:EELF Cleanup - Remove logger 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."); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.info("Success. We have a new configuration."); + LOGGER.info("Success. We have a new configuration."); loggingContext.transactionEnded(); - // TODO:EELF Cleanup - Remove logger - //auditLogger.info("Success. We have a new configuration."); PolicyLogger.audit("Success. We have a new configuration."); papUrls.registered(); Properties properties = new Properties(); properties.load(connection.getInputStream()); - logger.info("New properties: " + properties.toString()); + LOGGER.info("New properties: " + properties.toString()); // // Queue it // - // The incoming properties does NOT include urls - //FIXME: problem here is that we need the properties to be filled in BEFORE this thread continues and registers with another pap + // 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)); @@ -227,7 +214,6 @@ public class XACMLPdpRegisterThread implements Runnable { InputStream threadSafeReturnedPipPropertiesIs = new ByteArrayInputStream(threadSafeReturnedPipPropertiesOs.toByteArray()); threadSafeReturnedPipProperties.load(threadSafeReturnedPipPropertiesIs); tempPipConfigProperties = threadSafeReturnedPipProperties; - //FIXME: how will pipproperties respond to threading? PutRequest req = new PutRequest(returnedPolicyProperties,returnedPipProperties); XACMLPdpServlet.queue.offer(req); @@ -242,42 +228,28 @@ public class XACMLPdpRegisterThread implements Runnable { // String newLocation = connection.getHeaderField("Location"); if (newLocation == null || newLocation.isEmpty()) { - logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location"); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.warn(MessageCodes.ERROR_SYSTEM_ERROR, "Did not receive a valid re-direction location"); + 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"); - // TODO:EELF Cleanup - Remove logger PolicyLogger.audit("Transaction Failed - See Error.log"); finished = true; } else { - //FIXME: how to handle this - logger.info("New Location: " + newLocation); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.info("New Location: " + newLocation); + LOGGER.info("New Location: " + newLocation); url = new URL(newLocation); } } else { - logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.warn(MessageCodes.ERROR_SYSTEM_ERROR, "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + 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()); - // TODO:EELF Cleanup - Remove logger PolicyLogger.audit("Transaction Failed - See Error.log"); finished = true; papUrls.failed(); } } } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); PolicyLogger.audit("Transaction Failed - See Error.log"); loggingContext.transactionEnded(); - // TODO:EELF look at this error going to audit. decide what to do. - //auditLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - // TODO:EELF Cleanup - Remove logger papUrls.failed(); } finally { // cleanup the connection @@ -296,38 +268,18 @@ public class XACMLPdpRegisterThread implements Runnable { } } catch (IOException ex) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to close connection: " + ex, ex); - // TODO:EELF Cleanup - Remove logger - //PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, ex, "Failed to close connection"); + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to close connection: " + ex, ex); } connection.disconnect(); } } - // - // Wait a little while to try again - // - /* - try { - if (registered == false) { - if (retries > 0) { - retries--; - } else if (retries == 0) { - break; - } - Thread.sleep(seconds * 1000); - } - } catch (InterruptedException e) { - interrupted = true; - this.terminate(); - } - */ - //end of hasMoreUrls while loop + papUrls.getNext(); } synchronized(this) { this.isRunning = false; } - logger.info("Thread exiting...(registered=" + registered + ", interrupted=" + interrupted + ", isRunning=" + this.isRunning() + ", retries=" + "0" + ")"); + LOGGER.info("Thread exiting...(registered=" + registered + ", interrupted=" + interrupted + ", isRunning=" + this.isRunning() + ", retries=" + "0" + ")"); } } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpServlet.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpServlet.java index 963fcd127..6770c7ebb 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpServlet.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpServlet.java @@ -26,6 +26,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; +import java.lang.reflect.Constructor; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.Files; @@ -47,22 +48,25 @@ import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.entity.ContentType; -import org.openecomp.policy.pdp.rest.jmx.PdpRestMonitor; -import org.openecomp.policy.rest.XACMLRest; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.common.logging.ECOMPLoggingContext; -import org.openecomp.policy.common.logging.ECOMPLoggingUtils; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; +import org.openecomp.policy.api.PolicyParameters; import org.openecomp.policy.common.im.AdministrativeStateException; import org.openecomp.policy.common.im.ForwardProgressException; import org.openecomp.policy.common.im.IntegrityMonitor; import org.openecomp.policy.common.im.IntegrityMonitorProperties; import org.openecomp.policy.common.im.StandbyStatusException; +import org.openecomp.policy.common.logging.ECOMPLoggingContext; +import org.openecomp.policy.common.logging.ECOMPLoggingUtils; +import org.openecomp.policy.common.logging.eelf.MessageCodes; +import org.openecomp.policy.common.logging.eelf.PolicyLogger; +import org.openecomp.policy.pdp.rest.jmx.PdpRestMonitor; +import org.openecomp.policy.rest.XACMLRest; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.pdp.std.functions.PolicyList; +import org.openecomp.policy.xacml.std.pap.StdPDPStatus; import com.att.research.xacml.api.Request; import com.att.research.xacml.api.Response; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; import com.att.research.xacml.api.pap.PDPStatus.Status; import com.att.research.xacml.api.pdp.PDPEngine; import com.att.research.xacml.api.pdp.PDPException; @@ -71,8 +75,6 @@ import com.att.research.xacml.std.dom.DOMResponse; import com.att.research.xacml.std.json.JSONRequest; import com.att.research.xacml.std.json.JSONResponse; import com.att.research.xacml.util.XACMLProperties; -import org.openecomp.policy.xacml.pdp.std.functions.PolicyList; -import org.openecomp.policy.xacml.std.pap.StdPDPStatus; import com.fasterxml.jackson.databind.ObjectMapper; /** @@ -108,6 +110,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class XACMLPdpServlet extends HttpServlet implements Runnable { private static final long serialVersionUID = 1L; private static final String DEFAULT_MAX_CONTENT_LENGTH = "999999999"; //32767 + private static final String CREATE_UPDATE_POLICY_SERVICE = "org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl"; // // Our application debug log // @@ -120,9 +123,9 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { // // audit logger private static final Log auditLogger = LogFactory.getLog("auditLogger"); - + private static final PdpRestMonitor monitor = PdpRestMonitor.singleton; - + // // This thread may getting invoked on startup, to let the PAP know // that we are up and running. @@ -134,7 +137,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { // for access to the pointer. In case we are servicing PEP requests while // an update is occurring from the PAP. // - private PDPEngine pdpEngine = null; + private static PDPEngine pdpEngine = null; private static final Object pdpEngineLock = new Object(); // // This is our PDP's status. What policies are loaded (or not) and @@ -143,7 +146,8 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { // private static volatile StdPDPStatus status = new StdPDPStatus(); private static final Object pdpStatusLock = new Object(); - + private static Constructor<?> createUpdatePolicyConstructor; + private static final String ENVIORNMENT_HEADER = "Environment"; private static String environment = null; // @@ -152,7 +156,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { public static class PutRequest { public Properties policyProperties = null; public Properties pipConfigProperties = null; - + PutRequest(Properties policies, Properties pips) { this.policyProperties = policies; this.pipConfigProperties = pips; @@ -175,13 +179,14 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { // private Thread configThread = null; private volatile boolean configThreadTerminate = false; - private ECOMPLoggingContext baseLoggingContext = null; + private ECOMPLoggingContext baseLoggingContext = null; private IntegrityMonitor im; - /** - * Default constructor. - */ - public XACMLPdpServlet() { - } + private String createUpdateResourceName = null; + /** + * Default constructor. + */ + public XACMLPdpServlet() { + } /** * @see Servlet#init(ServletConfig) @@ -230,7 +235,17 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { "Error loading properties with: XACMLProperties.getProperties()"); throw new ServletException(e.getMessage(), e.getCause()); } - + if(properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME)==null){ + XACMLProperties.reloadProperties(); + try { + properties = XACMLProperties.getProperties(); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, + "Error loading properties with: XACMLProperties.getProperties()"); + throw new ServletException(e.getMessage(), e.getCause()); + } + PolicyLogger.info("\n Properties Given : \n" + properties.toString()); + } pdpResourceName = properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME); if(pdpResourceName == null){ PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XACMLRestProperties.PDP_RESOURCE_NAME, "xacml.pdp"); @@ -251,6 +266,15 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { dependencyNodes[i] = dependencyNodes[i].trim(); } + // CreateUpdatePolicy ResourceName + createUpdateResourceName = properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE); + try{ + Class<?> createUpdateclass = Class.forName(createUpdateResourceName); + createUpdatePolicyConstructor = createUpdateclass.getConstructor(PolicyParameters.class, String.class, boolean.class); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, "createUpdatePolicy.impl.className", "xacml.pdp.init"); + throw new ServletException("Could not find the Class name : " +createUpdateResourceName + "\n" +e.getMessage()); + } // Create an IntegrityMonitor try { @@ -260,7 +284,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor"); throw new ServletException(e); } - + environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); // // Kick off our thread to register with the PAP servlet. @@ -331,7 +355,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { * * EXAMPLE: * xacml.rootPolicies=PolicyA.1, PolicyB.1 - * + * * PolicyA.1.url=http://localhost:9090/PAP?id=b2d7b86d-d8f1-4adf-ba9d-b68b2a90bee1&version=1 * PolicyB.1.url=http://localhost:9090/PAP/id=be962404-27f6-41d8-9521-5acb7f0238be&version=1 * @@ -372,12 +396,12 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { } else { PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPut)"); } - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 1 of 2"); - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 2 of 2"); + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 1 of 2"); + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 2 of 2"); // // Dump our request out // @@ -431,7 +455,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { return; } } - + protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws ServletException, IOException { try { // prevent multiple configuration changes from stacking up @@ -476,7 +500,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { XACMLPdpServlet.queue.offer(new PutRequest(newProperties, null)); loggingContext.transactionEnded(); auditLogger.info("Success"); - PolicyLogger.audit("Success"); + PolicyLogger.audit("Success"); } else if (config.equals("pips")) { newProperties = XACMLProperties.getPipProperties(newProperties); if (newProperties.size() == 0) { @@ -490,7 +514,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { XACMLPdpServlet.queue.offer(new PutRequest(null, newProperties)); loggingContext.transactionEnded(); auditLogger.info("Success"); - PolicyLogger.audit("Success"); + PolicyLogger.audit("Success"); } else if (config.equals("all")) { Properties newPolicyProperties = XACMLProperties.getPolicyProperties(newProperties, true); if (newPolicyProperties.size() == 0) { @@ -513,7 +537,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { XACMLPdpServlet.queue.offer(new PutRequest(newPolicyProperties, newPipProperties)); loggingContext.transactionEnded(); auditLogger.info("Success"); - PolicyLogger.audit("Success"); + PolicyLogger.audit("Success"); } else { // // Invalid value @@ -533,9 +557,9 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } - + } - + /** * Parameters: type=hb|config|Status * @@ -562,12 +586,12 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { } else { PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doGet)"); } - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 1 of 2"); - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 2 of 2"); + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 1 of 2"); + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 2 of 2"); XACMLRest.dumpRequest(request); @@ -645,7 +669,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { } } } - + try { im.startTransaction(); } @@ -668,18 +692,18 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { loggingContext.setServiceName("PDP.getConfig"); response.setContentType("text/x-java-properties"); try { - String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); - lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "") + "\n"; - try (InputStream listInputStream = new ByteArrayInputStream(lists.getBytes()); - InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig()); - OutputStream os = response.getOutputStream()) { - IOUtils.copy(listInputStream, os); - IOUtils.copy(pipInputStream, os); + String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); + lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "") + "\n"; + try (InputStream listInputStream = new ByteArrayInputStream(lists.getBytes()); + InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig()); + OutputStream os = response.getOutputStream()) { + IOUtils.copy(listInputStream, os); + IOUtils.copy(pipInputStream, os); } - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - response.setStatus(HttpServletResponse.SC_OK); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to copy property file", e); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to copy property file"); @@ -687,23 +711,23 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { PolicyLogger.audit("Transaction Failed - See Error.log"); response.sendError(400, "Failed to copy Property file"); } - + } else if ("hb".equals(type)) { returnHB = true; response.setStatus(HttpServletResponse.SC_NO_CONTENT); - + } else if ("Status".equals(type)) { loggingContext.setServiceName("PDP.getStatus"); // convert response object to JSON and include in the response synchronized(pdpStatusLock) { ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(response.getOutputStream(), status); + mapper.writeValue(response.getOutputStream(), status); } - response.setStatus(HttpServletResponse.SC_OK); + response.setStatus(HttpServletResponse.SC_OK); loggingContext.transactionEnded(); auditLogger.info("Success"); - PolicyLogger.audit("Success"); - + PolicyLogger.audit("Success"); + } else { logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid type value: " + type); PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid type value: " + type); @@ -741,14 +765,14 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { } else { PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPost)"); } - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 1 of 2"); - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 2 of 2"); + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 1 of 2"); + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 2 of 2"); monitor.pdpEvaluationAttempts(); - + try { im.startTransaction(); } @@ -772,7 +796,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { im.endTransaction(); return; } - + XACMLRest.dumpRequest(request); // // Set our no-cache header @@ -846,14 +870,14 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { } incomingRequestString = buffer.toString(); logger.info(incomingRequestString); - // + // // Parse into a request // try { if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { pdpRequest = JSONRequest.load(incomingRequestString); } else if ( contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || - contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { + contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { pdpRequest = DOMRequest.load(incomingRequestString); } } @@ -907,11 +931,11 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { return; } // - // Get the pointer to the PDP Engine - // + // Get the pointer to the PDP Engine + // PDPEngine myEngine = null; synchronized(pdpEngineLock) { - myEngine = this.pdpEngine; + myEngine = XACMLPdpServlet.pdpEngine; } if (myEngine == null) { String message = "No engine loaded."; @@ -929,50 +953,50 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { long lTimeStart, lTimeEnd; Response pdpResponse = null; -//TODO - Make this unnecessary -//TODO It seems that the PDP Engine is not thread-safe, so when a configuration change occurs in the middle of processing -//TODO a PEP Request, that Request fails (it throws a NullPointerException in the decide() method). -//TODO Using synchronize will slow down processing of PEP requests, possibly by a significant amount. -//TODO Since configuration changes are rare, it would be A Very Good Thing if we could eliminate this sychronized block. -//TODO -//TODO This problem was found by starting one PDP then -//TODO RestLoadTest switching between 2 configurations, 1 second apart -//TODO both configurations contain the datarouter policy -//TODO both configurations already have all policies cached in the PDPs config directory -//TODO RestLoadTest started with the Datarouter test requests, 5 threads, no interval -//TODO With that configuration this code (without the synchronized) throws a NullPointerException -//TODO within a few seconds. -// -synchronized(pdpEngineLock) { - myEngine = this.pdpEngine; - try { - PolicyList.clearPolicyList(); - lTimeStart = System.currentTimeMillis(); - pdpResponse = myEngine.decide(pdpRequest); - lTimeEnd = System.currentTimeMillis(); - } catch (PDPException e) { - String message = "Exception during decide: " + e.getMessage(); - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - im.endTransaction(); - return; + //TODO - Make this unnecessary + //TODO It seems that the PDP Engine is not thread-safe, so when a configuration change occurs in the middle of processing + //TODO a PEP Request, that Request fails (it throws a NullPointerException in the decide() method). + //TODO Using synchronize will slow down processing of PEP requests, possibly by a significant amount. + //TODO Since configuration changes are rare, it would be A Very Good Thing if we could eliminate this sychronized block. + //TODO + //TODO This problem was found by starting one PDP then + //TODO RestLoadTest switching between 2 configurations, 1 second apart + //TODO both configurations contain the datarouter policy + //TODO both configurations already have all policies cached in the PDPs config directory + //TODO RestLoadTest started with the Datarouter test requests, 5 threads, no interval + //TODO With that configuration this code (without the synchronized) throws a NullPointerException + //TODO within a few seconds. + // + synchronized(pdpEngineLock) { + myEngine = XACMLPdpServlet.pdpEngine; + try { + PolicyList.clearPolicyList(); + lTimeStart = System.currentTimeMillis(); + pdpResponse = myEngine.decide(pdpRequest); + lTimeEnd = System.currentTimeMillis(); + } catch (PDPException e) { + String message = "Exception during decide: " + e.getMessage(); + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + im.endTransaction(); + return; + } } -} monitor.computeLatency(lTimeEnd - lTimeStart); requestLogger.info(lTimeStart + "=" + incomingRequestString); for(String policy : PolicyList.getpolicyList()){ monitor.policyCountAdd(policy, 1); } - - + + logger.info("PolicyID triggered in Request: " + PolicyList.getpolicyList()); - + //need to go through the list and find out if the value is unique and then add it other wise -// monitor.policyCountAdd(PolicyList.getpolicyList(), 1); - + // monitor.policyCountAdd(PolicyList.getpolicyList(), 1); + if (logger.isDebugEnabled()) { logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms"); } @@ -1006,7 +1030,7 @@ synchronized(pdpEngineLock) { outgoingResponseString = JSONResponse.toString(pdpResponse, false); } } else if ( contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || - contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { + contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { // // Get it as a String. This is not very efficient but we need to log our // results for auditing. @@ -1025,11 +1049,11 @@ synchronized(pdpEngineLock) { if (outgoingResponseString.contains("NotApplicable") || outgoingResponseString.contains("Decision not a Permit")){ monitor.pdpEvaluationNA(); } - + if (outgoingResponseString.contains("Permit") && !outgoingResponseString.contains("Decision not a Permit")){ monitor.pdpEvaluationPermit(); } - + if (outgoingResponseString.contains("Deny")){ monitor.pdpEvaluationDeny(); } @@ -1049,16 +1073,16 @@ synchronized(pdpEngineLock) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } - + monitor.pdpEvaluationSuccess(); response.setStatus(HttpServletResponse.SC_OK); loggingContext.transactionEnded(); auditLogger.info("Success"); - PolicyLogger.audit("Success"); + PolicyLogger.audit("Success"); + + } -} - /* * Added for Authorizing the PEP Requests for Environment check. */ @@ -1084,24 +1108,25 @@ synchronized(pdpEngineLock) { // try { // variable not used, but constructor has needed side-effects so don't remove: + @SuppressWarnings("unused") ECOMPLoggingContext loggingContext = new ECOMPLoggingContext(baseLoggingContext); while (! this.configThreadTerminate) { PutRequest request = XACMLPdpServlet.queue.take(); StdPDPStatus newStatus = new StdPDPStatus(); -//TODO - This is related to the problem discussed in the doPost() method about the PDPEngine not being thread-safe. -//TODO See that discussion, and when the PDPEngine is made thread-safe it should be ok to move the loadEngine out of -//TODO the synchronized block. -//TODO However, since configuration changes should be rare we may not care about changing this. -PDPEngine newEngine = null; + //TODO - This is related to the problem discussed in the doPost() method about the PDPEngine not being thread-safe. + //TODO See that discussion, and when the PDPEngine is made thread-safe it should be ok to move the loadEngine out of + //TODO the synchronized block. + //TODO However, since configuration changes should be rare we may not care about changing this. + PDPEngine newEngine = null; synchronized(pdpStatusLock) { XACMLPdpServlet.status.setStatus(Status.UPDATING_CONFIGURATION); -newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, request.pipConfigProperties); + newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, request.pipConfigProperties); } -// PDPEngine newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, request.pipConfigProperties); + // PDPEngine newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, request.pipConfigProperties); if (newEngine != null) { synchronized(XACMLPdpServlet.pdpEngineLock) { - this.pdpEngine = newEngine; + XACMLPdpServlet.pdpEngine = newEngine; try { logger.info("Saving configuration."); if (request.policyProperties != null) { @@ -1135,4 +1160,16 @@ newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, reque } } + public static PDPEngine getPDPEngine(){ + PDPEngine myEngine = null; + synchronized(pdpEngineLock) { + myEngine = XACMLPdpServlet.pdpEngine; + } + return myEngine; + } + + public static Constructor<?> getCreateUpdatePolicyConstructor(){ + return createUpdatePolicyConstructor; + } + } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java new file mode 100644 index 000000000..47afcda67 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java @@ -0,0 +1,591 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.controller; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; + +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.concurrent.atomic.AtomicLong; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.policy.api.ConfigRequestParameters; +import org.openecomp.policy.api.DecisionRequestParameters; +import org.openecomp.policy.api.DecisionResponse; +import org.openecomp.policy.api.DeletePolicyParameters; +import org.openecomp.policy.api.DictionaryParameters; +import org.openecomp.policy.api.DictionaryResponse; +import org.openecomp.policy.api.EventRequestParameters; +import org.openecomp.policy.api.MetricsResponse; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.api.PolicyResponse; +import org.openecomp.policy.api.PushPolicyParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.XACMLPdpServlet; +import org.openecomp.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest; +import org.openecomp.policy.pdp.rest.api.models.ConfigNameRequest; +import org.openecomp.policy.pdp.rest.api.models.ConfigPolicyAPIRequest; +import org.openecomp.policy.pdp.rest.api.models.PolicyConfig; +import org.openecomp.policy.pdp.rest.api.services.CreateUpdateConfigPolicyService; +import org.openecomp.policy.pdp.rest.api.services.CreateUpdateDictionaryService; +import org.openecomp.policy.pdp.rest.api.services.CreateUpdateFirewallPolicyService; +import org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyService; +import org.openecomp.policy.pdp.rest.api.services.DeletePolicyService; +import org.openecomp.policy.pdp.rest.api.services.GetConfigService; +import org.openecomp.policy.pdp.rest.api.services.GetDecisionService; +import org.openecomp.policy.pdp.rest.api.services.GetDictionaryService; +import org.openecomp.policy.pdp.rest.api.services.GetMetricsService; +import org.openecomp.policy.pdp.rest.api.services.ListConfigService; +import org.openecomp.policy.pdp.rest.api.services.PolicyEngineImportService; +import org.openecomp.policy.pdp.rest.api.services.PushPolicyService; +import org.openecomp.policy.pdp.rest.api.services.SendEventService; +import org.openecomp.policy.pdp.rest.config.PDPApiAuth; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import springfox.documentation.annotations.ApiIgnore; + +@RestController +@Api(value = "Policy Engine Services") +@RequestMapping("/") +public class PolicyEngineServices { + private static Logger LOGGER = FlexLogger + .getLogger(PolicyEngineServices.class.getName()); + private final AtomicLong configCounter = new AtomicLong(); + private final AtomicLong configNameCounter = new AtomicLong(); + private final AtomicLong eventCounter = new AtomicLong(); + private final AtomicLong decisionCounter = new AtomicLong(); + private final AtomicLong pushCounter = new AtomicLong(); + private final AtomicLong deleteCounter = new AtomicLong(); + private final AtomicLong createPolicyCounter = new AtomicLong(); + private final AtomicLong updatePolicyCounter = new AtomicLong(); + private final AtomicLong createDictionaryCounter = new AtomicLong(); + private final AtomicLong updateDictionaryCounter = new AtomicLong(); + private final AtomicLong getDictionaryCounter = new AtomicLong(); + private final AtomicLong policyEngineImportCounter = new AtomicLong(); + private final AtomicLong deprecatedCounter = new AtomicLong(); + private final AtomicLong metricCounter = new AtomicLong(); + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Gets the configuration from the PolicyDecisionPoint(PDP)") + @RequestMapping(value = "/getConfig", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity<Collection<PolicyConfig>> getConfig( + @RequestBody ConfigRequestParameters configRequestParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + Collection<PolicyConfig> policyConfig = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "getConfig")) { + GetConfigService getConfigService = new GetConfigService( + configRequestParameters, requestID); + policyConfig = getConfigService.getResult(); + status = getConfigService.getResponseCode(); + } + configCounter.incrementAndGet(); + return new ResponseEntity<Collection<PolicyConfig>>(policyConfig, + status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Gets the configuration from the PolicyDecisionPoint(PDP) using PolicyName") + @RequestMapping(value = "/getConfigByPolicyName", method = RequestMethod.POST) + @ResponseBody + @Deprecated + public ResponseEntity<Collection<PolicyConfig>> getConfigByPolicyName( + @RequestBody ConfigNameRequest configNameRequest, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + Collection<PolicyConfig> policyConfig = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "getConfigByPolicyName")) { + ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); + configRequestParameters.setPolicyName(configNameRequest + .getPolicyName()); + GetConfigService getConfigService = new GetConfigService( + configRequestParameters, requestID); + policyConfig = getConfigService.getResult(); + status = getConfigService.getResponseCode(); + } + configNameCounter.incrementAndGet(); + return new ResponseEntity<Collection<PolicyConfig>>(policyConfig, + status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Gets the list of configuration policies from the PDP") + @RequestMapping(value = "/listConfig", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity<Collection<String>> listConfig( + @RequestBody ConfigRequestParameters configRequestParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + Collection<String> results = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth + .checkPermissions(clientEncoding, requestID, "listConfig")) { + ListConfigService listConfigService = new ListConfigService( + configRequestParameters, requestID); + results = listConfigService.getResult(); + status = listConfigService.getResponseCode(); + } + configCounter.incrementAndGet(); + return new ResponseEntity<Collection<String>>(results, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value= "Gets the policy metrics from the PolicyAccessPoint(PAP)") + @RequestMapping(value="/getMetrics", method=RequestMethod.GET) + @ResponseBody + public ResponseEntity<MetricsResponse> getMetrics( + @RequestHeader(value="ClientAuth", required=true)String clientEncoding, + @RequestHeader(value="X-ECOMP-RequestID", required=false)String requestID) { + MetricsResponse response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if(PDPApiAuth.checkPermissions(clientEncoding, requestID, "getMetrics")){ + GetMetricsService getMetricsService = new GetMetricsService(requestID); + response = getMetricsService.getResult(); + status = getMetricsService.getResponseCode(); + } + metricCounter.incrementAndGet(); + return new ResponseEntity<MetricsResponse>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Sends the Events specified to the Policy Engine") + @RequestMapping(value = "/sendEvent", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity<Collection<PolicyResponse>> sendEvent( + @RequestBody EventRequestParameters eventRequestParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + Collection<PolicyResponse> policyResponse = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "sendEvent")) { + SendEventService sendEventService = new SendEventService( + eventRequestParameters, requestID); + policyResponse = sendEventService.getResult(); + status = sendEventService.getResponseCode(); + } + eventCounter.incrementAndGet(); + return new ResponseEntity<Collection<PolicyResponse>>(policyResponse, + status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Gets the Decision using specified decision parameters") + @RequestMapping(value = "/getDecision", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity<DecisionResponse> getDecision( + @RequestBody DecisionRequestParameters decisionRequestParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + DecisionResponse decisionResponse = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "getDecision")) { + GetDecisionService getDecisionService = new GetDecisionService( + decisionRequestParameters, requestID); + decisionResponse = getDecisionService.getResult(); + status = getDecisionService.getResponseCode(); + } + decisionCounter.incrementAndGet(); + return new ResponseEntity<DecisionResponse>(decisionResponse, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Pushes the specified policy to the PDP Group.") + @RequestMapping(value = "/pushPolicy", method = RequestMethod.PUT) + @ResponseBody + public ResponseEntity<String> pushPolicy( + @RequestBody PushPolicyParameters pushPolicyParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth + .checkPermissions(clientEncoding, requestID, "pushPolicy")) { + PushPolicyService pushPolicyService = new PushPolicyService( + pushPolicyParameters, requestID); + response = pushPolicyService.getResult(); + status = pushPolicyService.getResponseCode(); + } + pushCounter.incrementAndGet(); + return new ResponseEntity<String>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Deletes the specified policy from the PDP Group or PAP.") + @RequestMapping(value = "/deletePolicy", method = RequestMethod.DELETE) + @ResponseBody + public ResponseEntity<String> deletePolicy( + @RequestBody DeletePolicyParameters deletePolicyParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "deletePolicy")) { + DeletePolicyService deletePolicyService = new DeletePolicyService( + deletePolicyParameters, requestID); + response = deletePolicyService.getResult(); + status = deletePolicyService.getResponseCode(); + } + deleteCounter.incrementAndGet(); + return new ResponseEntity<String>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Creates a Policy based on given Policy Parameters.") + @RequestMapping(value = "/createPolicy", method = RequestMethod.PUT) + @ResponseBody + public ResponseEntity<String> createPolicy( + @RequestBody PolicyParameters policyParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "createPolicy")) { + CreateUpdatePolicyService createPolicyService; + try { + createPolicyService = (CreateUpdatePolicyService) XACMLPdpServlet.getCreateUpdatePolicyConstructor().newInstance( + policyParameters, requestID, false); + response = createPolicyService.getResult(); + status = createPolicyService.getResponseCode(); + } catch (InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + LOGGER.error(e.getMessage()); + response = "Problem with CreateUpdate Policy Service. "; + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } + createPolicyCounter.incrementAndGet(); + return new ResponseEntity<String>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Updates a Policy based on given Policy Parameters.") + @RequestMapping(value = "/updatePolicy", method = RequestMethod.PUT) + @ResponseBody + public ResponseEntity<String> updatePolicy( + @RequestBody PolicyParameters policyParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "updatePolicy")) { + CreateUpdatePolicyService updatePolicyService; + try { + updatePolicyService = (CreateUpdatePolicyService) XACMLPdpServlet.getCreateUpdatePolicyConstructor().newInstance( + policyParameters, requestID, true); + response = updatePolicyService.getResult(); + status = updatePolicyService.getResponseCode(); + } catch (InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + LOGGER.error(e.getMessage()); + response = "Problem with CreateUpdate Policy Service. "; + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } + updatePolicyCounter.incrementAndGet(); + return new ResponseEntity<String>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Creates a Dictionary Item for a specific dictionary based on given Parameters.") + @RequestMapping(value = "/createDictionaryItem", method = RequestMethod.PUT) + @ResponseBody + public ResponseEntity<String> createDictionaryItem( + @RequestBody DictionaryParameters dictionaryParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "createDictionary")) { + CreateUpdateDictionaryService createDictionaryService = new CreateUpdateDictionaryService( + dictionaryParameters, requestID, false); + response = createDictionaryService.getResult(); + status = createDictionaryService.getResponseCode(); + } + createDictionaryCounter.incrementAndGet(); + return new ResponseEntity<String>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Updates a Dictionary Item for a specific dictionary based on given Parameters.") + @RequestMapping(value = "/updateDictionaryItem", method = RequestMethod.PUT) + @ResponseBody + public ResponseEntity<String> updateDictionaryItem( + @RequestBody DictionaryParameters dictionaryParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "updateDictionary")) { + CreateUpdateDictionaryService updateDictionaryService = new CreateUpdateDictionaryService( + dictionaryParameters, requestID, true); + response = updateDictionaryService.getResult(); + status = updateDictionaryService.getResponseCode(); + } + updateDictionaryCounter.incrementAndGet(); + return new ResponseEntity<String>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Gets the dictionary items from the PAP") + @RequestMapping(value = "/getDictionaryItems", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity<DictionaryResponse> getDictionaryItems( + @RequestBody DictionaryParameters dictionaryParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + DictionaryResponse dictionaryResponse = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "getDictionary")) { + GetDictionaryService getDictionaryService = new GetDictionaryService( + dictionaryParameters, requestID); + dictionaryResponse = getDictionaryService.getResult(); + status = getDictionaryService.getResponseCode(); + } + getDictionaryCounter.incrementAndGet(); + return new ResponseEntity<DictionaryResponse>(dictionaryResponse, + status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Imports Policy based on the parameters which represent the service used to create a policy Service.") + @RequestMapping(value = "/policyEngineImport", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity<String> policyEngineImport( + @RequestParam("importParametersJson") String importParametersJson, + @RequestParam("file") MultipartFile file, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "policyEngineImport")) { + PolicyEngineImportService policyEngineImportService = new PolicyEngineImportService( + importParametersJson, file, requestID); + response = policyEngineImportService.getResult(); + status = policyEngineImportService.getResponseCode(); + } + policyEngineImportCounter.incrementAndGet(); + return new ResponseEntity<String>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Creates a Config Policy based on given Policy Parameters.") + @RequestMapping(value = "/createConfig", method = RequestMethod.PUT) + @ResponseBody + @Deprecated + public ResponseEntity<String> createConfig( + @RequestBody ConfigPolicyAPIRequest configPolicyAPIRequest, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "createPolicy")) { + CreateUpdateConfigPolicyService createPolicyService = new CreateUpdateConfigPolicyService( + configPolicyAPIRequest, requestID, false); + response = createPolicyService.getResult(); + status = createPolicyService.getResponseCode(); + } + deprecatedCounter.incrementAndGet(); + return new ResponseEntity<String>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Updates a Config Policy based on given Policy Parameters.") + @RequestMapping(value = "/updateConfig", method = RequestMethod.PUT) + @ResponseBody + @Deprecated + public ResponseEntity<String> updateConfig( + @RequestBody ConfigPolicyAPIRequest configPolicyAPIRequest, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "updatePolicy")) { + CreateUpdateConfigPolicyService updatePolicyService = new CreateUpdateConfigPolicyService( + configPolicyAPIRequest, requestID, true); + response = updatePolicyService.getResult(); + status = updatePolicyService.getResponseCode(); + } + deprecatedCounter.incrementAndGet(); + return new ResponseEntity<String>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Creates a Config Firewall Policy") + @RequestMapping(value = "/createFirewallConfig", method = RequestMethod.PUT) + @ResponseBody + @Deprecated + public ResponseEntity<String> createFirewallConfig( + @RequestBody ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "createPolicy")) { + CreateUpdateFirewallPolicyService createFirewallPolicyService = new CreateUpdateFirewallPolicyService( + configFirewallPolicyAPIRequest, requestID, false); + response = createFirewallPolicyService.getResult(); + status = createFirewallPolicyService.getResponseCode(); + } + deprecatedCounter.incrementAndGet(); + return new ResponseEntity<String>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Updates a Config Firewall Policy") + @RequestMapping(value = "/updateFirewallConfig", method = RequestMethod.PUT) + @ResponseBody + @Deprecated + public ResponseEntity<String> updateFirewallConfig( + @RequestBody ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "updatePolicy")) { + CreateUpdateFirewallPolicyService updateFirewallPolicyService = new CreateUpdateFirewallPolicyService( + configFirewallPolicyAPIRequest, requestID, true); + response = updateFirewallPolicyService.getResult(); + status = updateFirewallPolicyService.getResponseCode(); + } + deprecatedCounter.incrementAndGet(); + return new ResponseEntity<String>(response, status); + } + + @ApiOperation(value = "Gets the API Services usage Information") + @ApiIgnore + @RequestMapping(value = "/count", method = RequestMethod.GET) + public String getCount() { + return "Total Config Calls : " + configCounter + "\n" + + "Total Config calls made using Policy File Name: " + + configNameCounter + "\n" + "Total Event Calls : " + + eventCounter + "\nTotal Decision Calls: " + decisionCounter + + "\nTotal Push policy Calls: " + pushCounter + + "\nTotal Delete Policy Calls: " + deleteCounter + + "\nTotal Create Policy Calls: " + createPolicyCounter + + "\nTotal Update Policy Calls: " + updatePolicyCounter + + "\nTotal Create Dictionary Calls: " + createDictionaryCounter + + "\nTotal Update Dictionary Calls: " + updateDictionaryCounter + + "\nTotal Get Dictionary Calls: " + getDictionaryCounter + + "\nTotal PolicyEngine Import Calls: " + + policyEngineImportCounter + + "\nTotal Deprecated Policy Calls: " + deprecatedCounter + + "\nTotal Metrics Calls:" + metricCounter; + } + + @ExceptionHandler({ HttpMessageNotReadableException.class }) + public ResponseEntity<String> messageNotReadableExceptionHandler( + HttpServletRequest req, HttpMessageNotReadableException exception) { + LOGGER.error("Request not readable: {}", exception); + StringBuilder message = new StringBuilder(); + message.append(exception.getMessage()); + if (exception.getCause() != null) { + message.append(" Reason Caused: " + + exception.getCause().getMessage()); + } + return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST); + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java new file mode 100644 index 000000000..4ae368ae7 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.models; + +import io.swagger.annotations.ApiModel; + +import java.io.Serializable; + +@ApiModel +public class ConfigFirewallPolicyAPIRequest implements Serializable{ + private static final long serialVersionUID = -7460640390070215401L; + + private String policyName = null; + private String policyScope = null; + private String firewallJson = null; + private String riskType = "default"; + private String riskLevel = "5"; + private String guard = "false"; + private String ttlDate = null; + + public String getPolicyName() { + return policyName; + } + public String getPolicyScope() { + return policyScope; + } + public String getFirewallJson() { + return firewallJson; + } + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + public void setFirewallJson(String firewallJson) { + this.firewallJson = firewallJson; + } + public String getRiskType() { + return riskType; + } + public void setRiskType(String riskType) { + this.riskType = riskType; + } + public String getRiskLevel() { + return riskLevel; + } + public void setRiskLevel(String riskLevel) { + this.riskLevel = riskLevel; + } + public String getGuard() { + return guard; + } + public void setGuard(String guard) { + this.guard = guard; + } + public String getTtlDate() { + return ttlDate; + } + public void setTtlDate(String ttlDate) { + this.ttlDate = ttlDate; + } +}
\ No newline at end of file diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigNameRequest.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigNameRequest.java new file mode 100644 index 000000000..91881a3b2 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigNameRequest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.models; + +import io.swagger.annotations.ApiModel; + +import java.io.Serializable; + +@ApiModel +public class ConfigNameRequest implements Serializable{ + private static final long serialVersionUID = 4487978240532425305L; + + private String policyName = null; + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + public String getPolicyName() { + return policyName; + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java new file mode 100644 index 000000000..ed5d0ccaf --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.models; + +import io.swagger.annotations.ApiModel; + +import java.io.Serializable; +import java.util.Map; + +@ApiModel +public class ConfigPolicyAPIRequest implements Serializable{ + private static final long serialVersionUID = -4103391389984557025L; + + private String policyScope = null; + private String policyName = null; + private String policyDescription = null; + private String ecompName = null; + private String configName = null; + private Map<String,String> configAttributes = null; + private String configType = null; + private String body = null; + private String riskType = "default"; + private String riskLevel = "5"; + private String guard = "false"; + private String ttlDate = null; + + /** + * @return the policyScope + */ + public String getPolicyScope() { + return policyScope; + } + /** + * @return the policyName + */ + public String getPolicyName() { + return policyName; + } + /** + * @return the policyDescription + */ + public String getPolicyDescription() { + return policyDescription; + } + /** + * @return the ecompName + */ + public String getEcompName() { + return ecompName; + } + /** + * @return the configName + */ + public String getConfigName() { + return configName; + } + /** + * @return the configAttributes + */ + public Map<String, String> getConfigAttributes() { + return configAttributes; + } + /** + * @return the configType + */ + public String getConfigType() { + return configType; + } + /** + * @return the body + */ + public String getBody() { + return body; + } + /** + * @param policyScope the policyScope to set + */ + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + /** + * @param policyName the policyName to set + */ + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + /** + * @param policyDescription the policyDescription to set + */ + public void setPolicyDescription(String policyDescription) { + this.policyDescription = policyDescription; + } + /** + * @param ecompName the ecompName to set + */ + public void setEcompName(String ecompName) { + this.ecompName = ecompName; + } + /** + * @param configName the configName to set + */ + public void setConfigName(String configName) { + this.configName = configName; + } + /** + * @param configAttributes the configAttributes to set + */ + public void setConfigAttributes(Map<String, String> configAttributes) { + this.configAttributes = configAttributes; + } + /** + * @param configType the configType to set + */ + public void setConfigType(String configType) { + this.configType = configType; + } + /** + * @param body the body to set + */ + public void setBody(String body) { + this.body = body; + } + /** + * @return the guard + */ + public String getGuard() { + return guard; + } + /** + * @param guard the guard to set + */ + public void setGuard(String guard) { + this.guard = guard; + } + /** + * @return the riskLevel + */ + public String getRiskLevel() { + return riskLevel; + } + /** + * @param riskLevel the riskLevel to set + */ + public void setRiskLevel(String riskLevel) { + this.riskLevel = riskLevel; + } + /** + * @return the ttlDate + */ + public String getTtlDate() { + return ttlDate; + } + /** + * @param ttlDate the ttlDate to set + */ + public void setTtlDate(String ttlDate) { + this.ttlDate = ttlDate; + } + /** + * @return the riskType + */ + public String getRiskType() { + return riskType; + } + /** + * @param riskType the riskType to set + */ + public void setRiskType(String riskType) { + this.riskType = riskType; + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PDPResponse.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PDPResponse.java new file mode 100644 index 000000000..2301d003c --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PDPResponse.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.models; + +import java.util.Map; + +import org.openecomp.policy.api.DecisionResponse; +import org.openecomp.policy.api.PolicyConfigStatus; +import org.openecomp.policy.api.PolicyDecision; +import org.openecomp.policy.api.PolicyResponse; +import org.openecomp.policy.api.PolicyResponseStatus; +import org.openecomp.policy.api.PolicyType; +import org.openecomp.policy.models.APIConfigResponse; + +public class PDPResponse implements APIConfigResponse, PolicyResponse, DecisionResponse{ + private String policyConfigMessage; + private PolicyConfigStatus policyConfigStatus; + private PolicyType type; + private String config; + private String policyName; + private String policyVersion; + private Map<String, String> matchingConditions; + private Map<String, String> responseAttributes; + private Map<String, String> property; + private PolicyResponseStatus policyResponseStatus; + private String policyResponseMessage; + private Map<String,String> actionAdvised; + private Map<String,String> actionTaken; + private Map<String,String> requestAttributes; + private PolicyDecision policyDecision; + private String details; + + public void setStatus(String message, PolicyResponseStatus policyResponseStatus, PolicyConfigStatus policyConfigStatus) { + this.policyConfigMessage = message; + this.policyResponseMessage = message; + this.policyResponseStatus = policyResponseStatus; + this.policyConfigStatus = policyConfigStatus; + } + public String getConfig() { + return config; + } + public void setConfig(String config) { + this.config = config; + } + public PolicyType getType() { + return type; + } + public void setType(PolicyType type) { + this.type = type; + } + public PolicyConfigStatus getPolicyConfigStatus() { + return policyConfigStatus; + } + public void setPolicyConfigStatus(PolicyConfigStatus policyConfigStatus) { + this.policyConfigStatus = policyConfigStatus; + } + public String getPolicyConfigMessage() { + return policyConfigMessage; + } + public void setPolicyConfigMessage(String policyConfigMessage) { + this.policyConfigMessage = policyConfigMessage; + } + public Map<String, String> getProperty() { + return property; + } + public void setProperty(Map<String, String> property) { + this.property = property; + } + public String getPolicyName(){ + return policyName; + } + public void setPolicyName(String policyName){ + this.policyName = policyName; + } + public String getPolicyVersion(){ + return policyVersion; + } + public void setPolicyVersion(String policyVersion){ + this.policyVersion = policyVersion; + } + public Map<String, String> getMatchingConditions(){ + return matchingConditions; + } + public void setMatchingConditions(Map<String, String> matchingConditions){ + this.matchingConditions = matchingConditions; + } + public void setResponseAttributes(Map<String,String> responseAttributes){ + this.responseAttributes = responseAttributes; + } + public Map<String,String> getResponseAttributes(){ + return responseAttributes; + } + public void setPolicyResponseStatus(PolicyResponseStatus policyResponseStatus) { + this.policyResponseStatus = policyResponseStatus; + } + @Override + public PolicyResponseStatus getPolicyResponseStatus() { + return policyResponseStatus; + } + public void setDecision(PolicyDecision policyDecision){ + this.policyDecision = policyDecision; + } + @Override + public PolicyDecision getDecision() { + return policyDecision; + } + public void setDetails(String details){ + this.details = details; + } + @Override + public String getDetails() { + return details; + } + public void setActionAdvised(Map<String, String> actionAdvised) { + this.actionAdvised = actionAdvised; + } + @Override + public Map<String, String> getActionAdvised() { + return actionAdvised; + } + public void setActionTaken(Map<String, String> actionTaken) { + this.actionTaken = actionTaken; + } + @Override + public Map<String, String> getActionTaken() { + return actionTaken; + } + public void setRequestAttributes(Map<String, String> requestAttributes) { + this.requestAttributes = requestAttributes; + } + @Override + public Map<String, String> getRequestAttributes() { + return requestAttributes; + } + public void setPolicyResponseMessage(String policyResponseMessage) { + this.policyResponseMessage = policyResponseMessage; + } + @Override + public String getPolicyResponseMessage() { + return policyResponseMessage; + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PolicyConfig.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PolicyConfig.java new file mode 100644 index 000000000..729ffbb6f --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PolicyConfig.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.models; + +import io.swagger.annotations.ApiModel; + +import java.util.Map; + +import org.openecomp.policy.api.PolicyConfigStatus; +import org.openecomp.policy.api.PolicyType; +import org.openecomp.policy.models.APIConfigResponse; + +@ApiModel +public class PolicyConfig implements APIConfigResponse{ + private String policyConfigMessage; + private PolicyConfigStatus policyConfigStatus; + private PolicyType type; + private String config; + private String policyName; + private String policyVersion; + private Map<String, String> matchingConditions; + private Map<String, String> responseAttributes; + private Map<String, String> property; + public String getConfig() { + return config; + } + public void setConfig(String config) { + this.config = config; + } + public PolicyType getType() { + return type; + } + public void setType(PolicyType type) { + this.type = type; + } + public PolicyConfigStatus getPolicyConfigStatus() { + return policyConfigStatus; + } + public void setPolicyConfigStatus(PolicyConfigStatus policyConfigStatus) { + this.policyConfigStatus = policyConfigStatus; + } + public String getPolicyConfigMessage() { + return policyConfigMessage; + } + public void setPolicyConfigMessage(String policyConfigMessage) { + this.policyConfigMessage = policyConfigMessage; + } + public Map<String, String> getProperty() { + return property; + } + public void setProperty(Map<String, String> property) { + this.property = property; + } + public String getPolicyName(){ + return policyName; + } + public void setPolicyName(String policyName){ + this.policyName = policyName; + } + public String getPolicyVersion(){ + return policyVersion; + } + public void setPolicyVersion(String policyVersion){ + this.policyVersion = policyVersion; + } + public Map<String, String> getMatchingConditions(){ + return matchingConditions; + } + public void setMatchingConditions(Map<String, String> matchingConditions){ + this.matchingConditions = matchingConditions; + } + public void setResponseAttributes(Map<String,String> responseAttributes){ + this.responseAttributes = responseAttributes; + } + public Map<String,String> getResponseAttributes(){ + return responseAttributes; + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java new file mode 100644 index 000000000..14c536605 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.Map; + +import org.openecomp.policy.api.AttributeType; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Action Policy Implementation. + * + * @version 0.1 + */ +public class ActionPolicyService { + private static Logger LOGGER = FlexLogger.getLogger(ActionPolicyService.class.getName()); + private static PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private Map<String,String> componentAttributes = null; + private String actionAttribute = null; + private String actionPerformer = null; + + public ActionPolicyService(String policyScope, String policyName, + PolicyParameters policyParameters) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + if(policyParameters.getAttributes()==null || policyParameters.getAttributes().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Component Attributes given."; + return false; + } + componentAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING); + if (componentAttributes==null||componentAttributes.isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Component Attributes given."; + return false; + } + actionAttribute = policyParameters.getActionAttribute(); + if (actionAttribute==null||actionAttribute.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Attribute given."; + return false; + } + actionPerformer = policyParameters.getActionPerformer(); + if (actionPerformer==null||actionPerformer.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Performer given."; + return false; + } + if(!"PEP".equalsIgnoreCase(actionPerformer)&& !"PDP".equalsIgnoreCase(actionPerformer)){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Performer given."; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + // Create Policy + StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyName, policyParameters.getPolicyDescription(), + componentAttributes, policyParameters.getDynamicRuleAlgorithmLabels(), policyParameters.getDynamicRuleAlgorithmFunctions(), + policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmField2(), actionPerformer, actionAttribute, updateFlag, policyScope, 0); + // send Json to PAP + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Action"}, policyParameters.getRequestID(), "Action"); + LOGGER.info(response); + return response; + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java new file mode 100644 index 000000000..971f2fd35 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.Map; + +import org.openecomp.policy.api.AttributeType; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; + +/** + * BRMS Param Policy Implementation. + * + * @version 0.1 + */ +public class BRMSParamPolicyService{ + private static Logger LOGGER = FlexLogger.getLogger(BRMSParamPolicyService.class.getName()); + private static PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private boolean levelCheck = false; + private Map<AttributeType, Map<String, String>> drlRuleAndUIParams = null; + + public BRMSParamPolicyService(String policyName, String policyScope, + PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if(!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + return false; + } + drlRuleAndUIParams = policyParameters.getAttributes(); + if(drlRuleAndUIParams==null || drlRuleAndUIParams.isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Rule Attributes given."; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + // Create Policy + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("BRMS_Param",policyName, policyParameters.getPolicyDescription(), + "BRMS_PARAM_RULE",updateFlag,policyScope, + drlRuleAndUIParams.get(AttributeType.MATCHING), 0, "DROOLS", + null, drlRuleAndUIParams.get(AttributeType.RULE), policyParameters.getRiskLevel(), + policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date, policyParameters.getControllerName(), policyParameters.getDependencyNames()); + // Send JSON to PAP + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigBrmsParam"); + LOGGER.info(response); + return response; + } + +}
\ No newline at end of file diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSRawPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSRawPolicyService.java new file mode 100644 index 000000000..c68b1695b --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSRawPolicyService.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.Map; + +import org.openecomp.policy.api.AttributeType; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.openecomp.policy.utils.PolicyUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; + +/** + * BRMS RAW Policy Implementation. + * + * @version 0.1 + */ +public class BRMSRawPolicyService{ + private static Logger LOGGER = FlexLogger.getLogger(BRMSRawPolicyService.class.getName()); + private static PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private boolean levelCheck = false; + private String brmsRawBody = null; + + public BRMSRawPolicyService(String policyName, String policyScope, + PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + brmsRawBody = policyParameters.getConfigBody(); + if(brmsRawBody==null || brmsRawBody.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Rule Body given"; + return false; + } + message = PolicyUtils.brmsRawValidate(brmsRawBody); + if(message.contains("[ERR")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Raw rule given is invalid" +message; + return false; + } + levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if(!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + Map<String,String> ruleAttributes = null; + if(policyParameters.getAttributes()!=null){ + ruleAttributes = policyParameters.getAttributes().get(AttributeType.RULE); + } + // Create Policy + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("BRMS_Raw",policyName,policyParameters.getPolicyDescription(), + "BRMS_RAW_RULE",updateFlag,policyScope, ruleAttributes, 0, "DROOLS", + brmsRawBody, policyParameters.getRiskLevel(), + policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date, policyParameters.getControllerName(), policyParameters.getDependencyNames()); + // Send JSON to PAP + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigBrmsRaw"); + LOGGER.info(response); + return response; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java new file mode 100644 index 000000000..a85533be8 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Closed Loop Fault Policy Implementation. + * + * @version 0.1 + */ +public class ClosedLoopFaultPolicyService{ + private static Logger LOGGER = FlexLogger.getLogger(ClosedLoopFaultPolicyService.class.getName()); + private static PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private JsonObject configBody = null; + + public ClosedLoopFaultPolicyService(String policyName, String policyScope, + PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + if(policyParameters.getConfigBody()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present"; + return false; + } + if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + return false; + } + try{ + configBody = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); + } catch(JsonException| IllegalStateException e){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + String oldPolicyName = null; + if (updateFlag){ + operation = "update"; + if (policyName.endsWith("_Draft")) { + oldPolicyName = policyName + "_Draft.1"; + } + } else { + operation = "create"; + } + boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + // get values and attributes from the JsonObject + String ecompName = configBody.get("ecompname").toString().replace("\"", ""); + String jsonBody = configBody.toString(); + if (ecompName==null||ecompName.equals("")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; + LOGGER.error(message); + return message; + } + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + LOGGER.error(message); + return message; + } + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_Fault", policyName, policyParameters.getPolicyDescription(), ecompName, + jsonBody, false, oldPolicyName, null, updateFlag, policyScope, 0, policyParameters.getRiskLevel(), + policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); + //send JSON object to PAP + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigClosedLoop"); + return response; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java new file mode 100644 index 000000000..15a2c3abc --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Closed Loop PM policy Implementation. + * + * @version 0.1 + */ +public class ClosedLoopPMPolicyService{ + private static Logger LOGGER = FlexLogger.getLogger(ClosedLoopPMPolicyService.class.getName()); + private static PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private JsonObject configBody = null; + + public ClosedLoopPMPolicyService(String policyName, String policyScope, + PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + if(policyParameters.getConfigBody()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present"; + return false; + } + if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + return false; + } + try{ + configBody = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); + } catch(JsonException| IllegalStateException e){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException{ + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + // get values and attributes from the JsonObject + String ecompName = configBody.get("ecompname").toString().replace("\"", ""); + String serviceType = configBody.get("serviceTypePolicyName").toString().replace("\"", ""); + String jsonBody = configBody.toString(); + if (ecompName==null||ecompName.equals("")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; + LOGGER.error(message); + return message; + } + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + LOGGER.error(message); + return message; + } + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_PM", policyName, policyParameters.getPolicyDescription(), ecompName, + jsonBody, false, null, serviceType, updateFlag, policyScope, 0, policyParameters.getRiskLevel(), + policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); + //send JSON object to PAP + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigClosedLoop"); + return response; + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java new file mode 100644 index 000000000..8edd1ac61 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.Map; + +import org.openecomp.policy.api.AttributeType; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.openecomp.policy.utils.PolicyUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Config Base Policy Implementation. + * + * @version 0.1 + */ +public class ConfigPolicyService { + private static Logger LOGGER = FlexLogger.getLogger(ConfigPolicyService.class.getName()); + private static PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private boolean levelCheck = false; + private String ecompName = null; + private String configName = null; + + public ConfigPolicyService(String policyName, String policyScope, + PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + if(policyParameters.getConfigBody()==null || policyParameters.getConfigBody().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given."; + return false; + } + if(policyParameters.getConfigBodyType()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body Type given."; + return false; + } + levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + return false; + } + ecompName = policyParameters.getEcompName(); + configName = policyParameters.getConfigName(); + if(ecompName==null || ecompName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given."; + return false; + } + if(configName==null || configName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given."; + return false; + } + message = PolicyUtils.emptyPolicyValidator(ecompName); + if(!message.contains("success")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; + return false; + } + message = PolicyUtils.emptyPolicyValidator(configName); + if(!message.contains("success")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + String configType = policyParameters.getConfigBodyType().toString(); + String body = policyParameters.getConfigBody(); + String configBody = null; + //check body for JSON form and remove single quotes if present + if (configType.equalsIgnoreCase("JSON")) { + if (body.contains("'")) { + configBody = body.replace("'", "\""); + } else { + configBody = body; + } + } else { + configBody = body; + } + Map<String,String> configAttributes = null; + if(policyParameters.getAttributes()!=null){ + configAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING); + } + // create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Base", policyName, policyParameters.getPolicyDescription(), ecompName, configName, configAttributes, configType, + configBody, updateFlag, policyScope,0, policyParameters.getRiskLevel(),policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); + // Send Json to PAP. + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "Config"); + LOGGER.info(response); + return response; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java new file mode 100644 index 000000000..e26fae18a --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.policy.api.AttributeType; +import org.openecomp.policy.api.PolicyClass; +import org.openecomp.policy.api.PolicyConfigType; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.api.PolicyType; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.models.ConfigPolicyAPIRequest; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class CreateUpdateConfigPolicyService { + private static Logger LOGGER = FlexLogger.getLogger(CreateUpdateConfigPolicyService.class.getName()); + + private String response = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + + public CreateUpdateConfigPolicyService( + ConfigPolicyAPIRequest configPolicyAPIRequest, String requestID, + boolean updateFlag) { + try{ + run(configPolicyAPIRequest, requestID, updateFlag); + }catch(PolicyException e){ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private void run(ConfigPolicyAPIRequest configPolicyAPIRequest, + String requestID, boolean updateFlag) throws PolicyException{ + PolicyParameters policyParameters = new PolicyParameters(); + policyParameters.setPolicyClass(PolicyClass.Config); + policyParameters.setPolicyConfigType(PolicyConfigType.Base); + if(configPolicyAPIRequest.getPolicyScope()==null|| configPolicyAPIRequest.getPolicyScope().trim().isEmpty()){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + LOGGER.error(message); + throw new PolicyException(message); + } + if(configPolicyAPIRequest.getPolicyName()==null|| configPolicyAPIRequest.getPolicyName().trim().isEmpty()){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + LOGGER.error(message); + throw new PolicyException(message); + } + policyParameters.setPolicyName(configPolicyAPIRequest.getPolicyScope()+"."+configPolicyAPIRequest.getPolicyName()); + policyParameters.setPolicyDescription(configPolicyAPIRequest.getPolicyDescription()); + policyParameters.setEcompName(configPolicyAPIRequest.getEcompName()); + policyParameters.setConfigName(configPolicyAPIRequest.getConfigName()); + Map<AttributeType, Map<String, String>> attributes = new HashMap<AttributeType, Map<String, String>>(); + attributes.put(AttributeType.MATCHING, configPolicyAPIRequest.getConfigAttributes()); + policyParameters.setAttributes(attributes); + policyParameters.setConfigBodyType(PolicyType.valueOf(configPolicyAPIRequest.getConfigType())); + policyParameters.setConfigBody(configPolicyAPIRequest.getBody()); + policyParameters.setRiskLevel(configPolicyAPIRequest.getRiskLevel()); + policyParameters.setRiskType(configPolicyAPIRequest.getRiskType()); + policyParameters.setGuard(Boolean.parseBoolean(configPolicyAPIRequest.getGuard())); + try { + policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(configPolicyAPIRequest.getTtlDate())); + } catch (ParseException e) { + LOGGER.warn("Error Parsing date given " + configPolicyAPIRequest.getTtlDate()); + policyParameters.setTtlDate(null); + } + CreateUpdatePolicyService createUpdatePolicyService = new CreateUpdatePolicyServiceImpl(policyParameters, requestID, updateFlag); + status = createUpdatePolicyService.getResponseCode(); + response = createUpdatePolicyService.getResult(); + } + + public String getResult() { + return response; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java new file mode 100644 index 000000000..1c3049da3 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java @@ -0,0 +1,156 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.io.ByteArrayInputStream; +import java.util.UUID; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.openecomp.policy.api.DictionaryParameters; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class CreateUpdateDictionaryService { + private static Logger LOGGER = FlexLogger.getLogger(CreateUpdateDictionaryService.class.getName()); + + private String dictionaryResult = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private String message = null; + private Boolean updateFlag = false; + private DictionaryParameters dictionaryParameters = null; + + public CreateUpdateDictionaryService( + DictionaryParameters dictionaryParameters, String requestID, + boolean updateFlag) { + this.updateFlag = updateFlag; + this.dictionaryParameters = dictionaryParameters; + if(dictionaryParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.dictionaryParameters.setRequestID(requestUUID); + } + try{ + run(); + specialCheck(); + }catch(PolicyException e){ + dictionaryResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if(dictionaryResult== null || dictionaryResult.contains("BAD REQUEST")||dictionaryResult.contains("PE300")){ + status = HttpStatus.BAD_REQUEST; + } else if (dictionaryResult.contains("Policy Exist Error")) { + status = HttpStatus.CONFLICT; + } else if (dictionaryResult.contains("PE200")){ + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } + + private void run() throws PolicyException{ + // Check Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyException(message); + } + // Get Result. + try{ + status = HttpStatus.OK; + dictionaryResult = processResult(); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + private String processResult() throws PolicyException{ + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + JsonObject json = null; + try{ + json = PolicyApiUtils.stringToJsonObject(dictionaryParameters.getDictionaryJson()); + } catch(JsonException| IllegalStateException e){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper Dictionary JSON object : " + dictionaryParameters.getDictionaryJson(); + LOGGER.error(message); + return message; + } + String dictionaryFields = json.toString(); + PAPServices papServices = new PAPServices(); + String result = (String) papServices.callPAP(new ByteArrayInputStream(dictionaryFields.getBytes()), new String[] {"operation="+operation, "apiflag=api", "dictionaryType="+dictionaryParameters.getDictionary()}, dictionaryParameters.getRequestID(), "dictionaryItem"); + return result; + } + + private boolean getValidation() { + if(dictionaryParameters==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Dictionary Parameters are not given."; + return false; + } + if(dictionaryParameters.getDictionaryType()==null || dictionaryParameters.getDictionaryType().toString().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Type given."; + return false; + } + if(dictionaryParameters.getDictionary()==null || dictionaryParameters.getDictionary().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary given."; + return false; + } + if(dictionaryParameters.getDictionaryJson()==null || dictionaryParameters.getDictionaryJson().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary JSON given."; + return false; + } + if (updateFlag && dictionaryParameters.getDictionary().equalsIgnoreCase("MicroServiceDictionary")){ + if (!dictionaryParameters.getDictionaryJson().contains("initialFields")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Mising the required field initialFields."; + return false; + } + } + return true; + } + + public String getResult() { + return dictionaryResult; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java new file mode 100644 index 000000000..b547f8dfe --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import org.openecomp.policy.api.PolicyClass; +import org.openecomp.policy.api.PolicyConfigType; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class CreateUpdateFirewallPolicyService { + private static Logger LOGGER = FlexLogger.getLogger(CreateUpdateFirewallPolicyService.class.getName()); + + private String response = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + + public CreateUpdateFirewallPolicyService( + ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, + String requestID, boolean updateFlag) { + try{ + run(configFirewallPolicyAPIRequest, requestID, updateFlag); + }catch(PolicyException e){ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private void run( + ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, + String requestID, boolean updateFlag) throws PolicyException{ + PolicyParameters policyParameters = new PolicyParameters(); + policyParameters.setPolicyClass(PolicyClass.Config); + policyParameters.setPolicyConfigType(PolicyConfigType.Firewall); + if(configFirewallPolicyAPIRequest.getPolicyScope()==null|| configFirewallPolicyAPIRequest.getPolicyScope().trim().isEmpty()){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + LOGGER.error(message); + throw new PolicyException(message); + } + if(configFirewallPolicyAPIRequest.getPolicyName()==null|| configFirewallPolicyAPIRequest.getPolicyName().trim().isEmpty()){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + LOGGER.error(message); + throw new PolicyException(message); + } + policyParameters.setPolicyName(configFirewallPolicyAPIRequest.getPolicyScope()+"."+configFirewallPolicyAPIRequest.getPolicyName()); + policyParameters.setConfigBody(configFirewallPolicyAPIRequest.getFirewallJson()); + policyParameters.setRiskLevel(configFirewallPolicyAPIRequest.getRiskLevel()); + policyParameters.setRiskType(configFirewallPolicyAPIRequest.getRiskType()); + policyParameters.setGuard(Boolean.parseBoolean(configFirewallPolicyAPIRequest.getGuard())); + try { + policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(configFirewallPolicyAPIRequest.getTtlDate())); + } catch (NullPointerException | ParseException e) { + LOGGER.warn("Error Parsing date given " + configFirewallPolicyAPIRequest.getTtlDate()); + policyParameters.setTtlDate(null); + } + CreateUpdatePolicyService createUpdatePolicyService = new CreateUpdatePolicyServiceImpl(policyParameters, requestID, updateFlag); + status = createUpdatePolicyService.getResponseCode(); + response = createUpdatePolicyService.getResult(); + } + + public String getResult() { + return response; + } + + public HttpStatus getResponseCode() { + return status; + } + +}
\ No newline at end of file diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyService.java new file mode 100644 index 000000000..73f9e7448 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyService.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import org.openecomp.policy.api.PolicyException; +import org.springframework.http.HttpStatus; + +public interface CreateUpdatePolicyService { + + public void run() throws PolicyException; + + public String processResult() throws PolicyException; + + public String getResult(); + + public HttpStatus getResponseCode(); + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java new file mode 100644 index 000000000..4032a8a7f --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java @@ -0,0 +1,294 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.openecomp.policy.utils.PolicyUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService { + private static Logger LOGGER = FlexLogger.getLogger(CreateUpdatePolicyService.class.getName()); + + private String policyResult = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private Boolean updateFlag = false; + private String message = null; + private PolicyParameters policyParameters = new PolicyParameters(); + private String policyName = null; + private String policyScope = null; + private String date = null; + + public CreateUpdatePolicyServiceImpl(PolicyParameters policyParameters, + String requestID, boolean updateFlag) { + this.updateFlag = updateFlag; + this.policyParameters = policyParameters; + if(policyParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.policyParameters.setRequestID(requestUUID); + } + try{ + run(); + specialCheck(); + }catch(PolicyException e){ + policyResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + public void run() throws PolicyException{ + // Check Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyException(message); + } + // Get Result. + try{ + status = HttpStatus.OK; + policyResult = processResult(); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + @SuppressWarnings("incomplete-switch") + public String processResult() throws PolicyException{ + String response = null; + if(policyParameters.getPolicyConfigType()!=null){ + // This is a Config Type Policy. + switch(policyParameters.getPolicyConfigType()){ + case BRMS_PARAM: + BRMSParamPolicyService bRMSParamPolicyService = new BRMSParamPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!bRMSParamPolicyService.getValidation()){ + LOGGER.error(bRMSParamPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return bRMSParamPolicyService.getMessage(); + } + // Get Result. + response = bRMSParamPolicyService.getResult(updateFlag); + break; + case BRMS_RAW: + BRMSRawPolicyService bRMSRawPolicyService = new BRMSRawPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!bRMSRawPolicyService.getValidation()){ + LOGGER.error(bRMSRawPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return bRMSRawPolicyService.getMessage(); + } + // Get Result. + response = bRMSRawPolicyService.getResult(updateFlag); + break; + case Base: + ConfigPolicyService configPolicyService = new ConfigPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!configPolicyService.getValidation()){ + LOGGER.error(configPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return configPolicyService.getMessage(); + } + // Get Result. + response = configPolicyService.getResult(updateFlag); + break; + case ClosedLoop_Fault: + ClosedLoopFaultPolicyService closedLoopFaultPolicyService = new ClosedLoopFaultPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!closedLoopFaultPolicyService.getValidation()){ + LOGGER.error(closedLoopFaultPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return closedLoopFaultPolicyService.getMessage(); + } + // Get Result. + response = closedLoopFaultPolicyService.getResult(updateFlag); + break; + case ClosedLoop_PM: + ClosedLoopPMPolicyService closedLoopPMPolicyService = new ClosedLoopPMPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!closedLoopPMPolicyService.getValidation()){ + LOGGER.error(closedLoopPMPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return closedLoopPMPolicyService.getMessage(); + } + // Get Result. + response = closedLoopPMPolicyService.getResult(updateFlag); + break; + case Firewall: + FirewallPolicyService firewallPolicyService = new FirewallPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!firewallPolicyService.getValidation()){ + LOGGER.error(firewallPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return firewallPolicyService.getMessage(); + } + // Get Result. + response = firewallPolicyService.getResult(updateFlag); + break; + case MicroService: + MicroServicesPolicyService microServicesPolicyService = new MicroServicesPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!microServicesPolicyService.getValidation()){ + LOGGER.error(microServicesPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return microServicesPolicyService.getMessage(); + } + // Get Result. + response = microServicesPolicyService.getResult(updateFlag); + break; + default: + String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " Invalid Config Type Present"; + LOGGER.error(message); + status = HttpStatus.BAD_REQUEST; + return message; + } + }else if (policyParameters.getPolicyClass()!=null){ + switch (policyParameters.getPolicyClass()){ + case Action: + ActionPolicyService actionPolicyService = new ActionPolicyService(policyScope, policyName, policyParameters); + // Check Validation. + if(!actionPolicyService.getValidation()){ + LOGGER.error(actionPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return actionPolicyService.getMessage(); + } + // Get Result. + response = actionPolicyService.getResult(updateFlag); + break; + case Decision: + DecisionPolicyService decisionPolicyService = new DecisionPolicyService(policyScope, policyName, policyParameters); + // Check Validation. + if(!decisionPolicyService.getValidation()){ + LOGGER.error(decisionPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return decisionPolicyService.getMessage(); + } + // Get Result. + response = decisionPolicyService.getResult(updateFlag); + break; + } + }else { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Class found."; + LOGGER.error(message); + status = HttpStatus.BAD_REQUEST; + response = message; + } + return response; + } + + protected boolean getValidation() { + if(policyParameters == null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy parameters given. "; + return false; + } + if(policyParameters.getPolicyName() == null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + return false; + } + if (policyParameters.getPolicyName().contains(".")) { + policyName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf(".") + 1, + policyParameters.getPolicyName().length()); + policyScope = policyParameters.getPolicyName().substring(0,policyParameters.getPolicyName().lastIndexOf(".")); + LOGGER.info("Name is " + policyName + " scope is " + policyScope); + } else { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + return false; + } + if (policyName==null||policyName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + return false; + + } + message = PolicyUtils.emptyPolicyValidator(policyScope); + if(!message.contains("success")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; + return false; + } + message = PolicyUtils.emptyPolicyValidator(policyName); + if(!message.contains("success")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; + return false; + } + if(policyParameters.getPolicyDescription()!=null){ + message = PolicyUtils.descriptionValidator(policyParameters.getPolicyDescription()); + if(!message.contains("success")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; + return false; + } + } + if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.toString())){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "This requests contains Non ASCII Characters. Please review your input parameter" + + " values and correct the illegal characters."; + return false; + } + // Set some default Values. + if (policyParameters.getTtlDate()!=null){ + date = convertDate(policyParameters.getTtlDate()); + } + return true; + } + + protected String convertDate(Date date) { + String strDate = null; + if (date!=null) { + SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy"); + strDate = dateformatJava.format(date); + } + return (strDate==null) ? "NA": strDate; + } + + protected void specialCheck() { + if(policyResult== null || policyResult.contains("BAD REQUEST")||policyResult.contains("PE300")){ + status = HttpStatus.BAD_REQUEST; + } else if (policyResult.contains("Policy Exist Error")) { + status = HttpStatus.CONFLICT; + } else if (policyResult.contains("PE200")||policyResult.contains("PE900")){ + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } + + public String getResult() { + return policyResult; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DecisionPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DecisionPolicyService.java new file mode 100644 index 000000000..c6789a0b8 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DecisionPolicyService.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.Map; + +import org.openecomp.policy.api.AttributeType; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.api.RuleProvider; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Decision Policy Implementation + * + * @version 0.1 + */ +public class DecisionPolicyService{ + private static Logger LOGGER = FlexLogger.getLogger(DecisionPolicyService.class.getName()); + private static PAPServices papServices = null; + + private String message = null; + private String policyScope = null; + private String policyName = null; + private PolicyParameters policyParameters = null; + private String ecompName = null; + + public DecisionPolicyService(String policyScope, String policyName, + PolicyParameters policyParameters) { + this.policyScope = policyScope; + this.policyName = policyName; + this.policyParameters = policyParameters; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + ecompName = policyParameters.getEcompName(); + if (ecompName==null||ecompName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given."; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + RuleProvider ruleProvider = policyParameters.getRuleProvider(); + if (ruleProvider==null) { + ruleProvider = RuleProvider.CUSTOM ; + } + Map<String,String> matchingAttributes = null; + Map<String,String> settingsAttributes = null; + if (policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)) { + matchingAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING); + settingsAttributes = policyParameters.getAttributes().get(AttributeType.SETTINGS); + }else if(policyParameters.getAttributes()!=null && !policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){ + settingsAttributes = policyParameters.getAttributes().get(AttributeType.SETTINGS); + }else if(policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && !policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){ + matchingAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING); + } + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyName, policyParameters.getPolicyDescription(), ecompName, ruleProvider.toString(), matchingAttributes, settingsAttributes, policyParameters.getDynamicRuleAlgorithmLabels(), + policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmField2(), null, null, null, updateFlag, policyScope, 0); + // Send JSON to PAP. + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Decision"}, policyParameters.getRequestID(), "Decision"); + LOGGER.info(message); + return response; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java new file mode 100644 index 000000000..d0978fc5b --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java @@ -0,0 +1,258 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.io.File; +import java.util.UUID; + +import org.openecomp.policy.api.DeletePolicyParameters; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; +import org.springframework.http.HttpStatus; + +public class DeletePolicyService { + private static Logger LOGGER = FlexLogger.getLogger(DeletePolicyService.class.getName()); + + private String deleteResult = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private DeletePolicyParameters deletePolicyParameters = null; + private String message = null; + private String filePrefix = null; + private String clientScope = null; + private String policyType = null; + private String policyName = null; + private String policyScope = null; + + public DeletePolicyService(DeletePolicyParameters deletePolicyParameters, + String requestID) { + this.deletePolicyParameters = deletePolicyParameters; + if(deletePolicyParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.deletePolicyParameters.setRequestID(requestUUID); + } + try{ + run(); + specialCheck(); + }catch(PolicyException e){ + deleteResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if(deleteResult==null){ + return; + } + if (deleteResult.contains("BAD REQUEST")||deleteResult.contains("PE300")||deleteResult.contains("not exist")||deleteResult.contains("Invalid policyName")) { + status = HttpStatus.BAD_REQUEST; + } else if (deleteResult.contains("locked down")){ + status = HttpStatus.ACCEPTED; + } else if (deleteResult.contains("not Authorized")) { + status = HttpStatus.FORBIDDEN; + } else if (deleteResult.contains("groupId")) { + status = HttpStatus.NOT_FOUND; + } else if (deleteResult.contains("JPAUtils")||deleteResult.contains("database")||deleteResult.contains("policy file")|| + deleteResult.contains("unknown")||deleteResult.contains("configuration")) { + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } + + private void run() throws PolicyException{ + // Check Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyException(message); + } + // Get Result. + try{ + status = HttpStatus.OK; + deleteResult = processResult(); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + private String processResult() throws PolicyException{ + String response = null; + String fullPolicyName = null; + String pdpGroup = deletePolicyParameters.getPdpGroup(); + // PDP Group Check. + if (pdpGroup==null){ + pdpGroup="NA"; + } + PAPServices papServices = new PAPServices(); + if (!deletePolicyParameters.getPolicyName().contains("xml")) { + + String activeVersion = papServices.getActiveVersion(policyScope, filePrefix, policyName, clientScope, deletePolicyParameters.getRequestID()); + LOGGER.debug("The active version of " + policyScope + File.separator + filePrefix + policyName + " is " + activeVersion); + String id = null; + if ("pe100".equalsIgnoreCase(activeVersion)) { + response = XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is 403. PEP is not Authorized for making this Request!! " + + "Contact Administrator for this Scope. "; + LOGGER.error(response); + return response; + } else if ("pe300".equalsIgnoreCase(activeVersion)) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. " + + "This indicates a problem with getting the version from the PAP or the policy does not exist."; + LOGGER.error(response); + return response; + } + if (!activeVersion.equalsIgnoreCase("0")) { + id = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml"; + LOGGER.debug("The policyId is " + id); + } else { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy. could not retrieve the activeVersion for this policy. " + + "This indicates the policy does not exist, please verify the policy exists."; + LOGGER.error(response); + return response; + } + + fullPolicyName = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml"; + + } else { + fullPolicyName = policyName; + } + + if ("PAP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) { + if (deletePolicyParameters.getDeleteCondition()==null||deletePolicyParameters.getDeleteCondition().toString().trim().isEmpty()){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Delete Condition given."; + LOGGER.error(message); + return message; + } + + StdPAPPolicy deletePapPolicy = new StdPAPPolicy(fullPolicyName, deletePolicyParameters.getDeleteCondition().toString()); + //send JSON object to PAP + response = (String) papServices.callPAP(deletePapPolicy, new String[] {"groupId="+pdpGroup, "apiflag=deletePapApi", "operation=delete" }, deletePolicyParameters.getRequestID(), clientScope); + } else if ("PDP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) { + if (deletePolicyParameters.getPdpGroup()==null||deletePolicyParameters.getPdpGroup().trim().isEmpty()){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PDP Group given."; + LOGGER.error(message); + return message; + } + //send JSON object to PAP + response = (String) papServices.callPAP(null, new String[] {"policyName="+fullPolicyName, "groupId="+pdpGroup, "apiflag=deletePdpApi", "operation=delete" }, deletePolicyParameters.getRequestID(), clientScope); + } else { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Component does not exist. Please enter either PAP or PDP to delete the policy from a specified Policy Component."; + LOGGER.error(message); + response = message; + } + return response; + } + + private boolean getValidation() { + // While Validating, extract the required values. + if (!deletePolicyParameters.getPolicyName().contains("xml")) { + if (deletePolicyParameters.getPolicyName() != null + && deletePolicyParameters.getPolicyName().contains(".")) { + policyName = deletePolicyParameters.getPolicyName().substring(deletePolicyParameters.getPolicyName().lastIndexOf(".") + 1, + deletePolicyParameters.getPolicyName().length()); + policyScope = deletePolicyParameters.getPolicyName().substring(0,deletePolicyParameters.getPolicyName().lastIndexOf(".")); + LOGGER.info("Name is " + policyName + " scope is " + policyScope); + } else { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + return false; + } + } else { + policyName = deletePolicyParameters.getPolicyName(); + } + if (deletePolicyParameters.getPolicyName()==null||deletePolicyParameters.getPolicyName().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + return false; + } + policyType = deletePolicyParameters.getPolicyType(); + if(policyType== null || policyType.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given."; + return false; + } + setClientScope(); + if (clientScope==null||clientScope.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + deletePolicyParameters.getPolicyType() + " is not a valid Policy Type."; + LOGGER.error(message); + return false; + } + LOGGER.debug("clientScope is " + clientScope); + LOGGER.debug("filePrefix is " + filePrefix); + if(deletePolicyParameters.getPolicyComponent()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Component given."; + return false; + } + return true; + } + + private void setClientScope() { + if ("Firewall".equalsIgnoreCase(policyType)) { + clientScope = "ConfigFirewall"; + filePrefix = "Config_FW_"; + } else if ("Action".equalsIgnoreCase(policyType)) { + clientScope = "Action"; + filePrefix = "Action_"; + } else if ("Decision".equalsIgnoreCase(policyType)) { + clientScope = "Decision"; + filePrefix = "Decision_"; + } else if ("Base".equalsIgnoreCase(policyType)) { + clientScope = "Config"; + filePrefix = "Config_"; + } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyType)) { + clientScope = "ConfigClosedLoop"; + filePrefix = "Config_Fault_"; + } else if ("ClosedLoop_PM".equalsIgnoreCase(policyType)) { + clientScope = "ConfigClosedLoop"; + filePrefix = "Config_PM_"; + } else if ("MicroService".equalsIgnoreCase(policyType)) { + clientScope = "ConfigMS"; + filePrefix = "Config_MS_"; + }else if ("BRMS_RAW".equalsIgnoreCase(policyType)) { + clientScope = "ConfigBrmsRaw"; + filePrefix = "Config_BRMS_Raw_"; + } else if ("BRMS_PARAM".equalsIgnoreCase(policyType)) { + clientScope = "ConfigBrmsParam"; + filePrefix = "Config_BRMS_Param_"; + } else { + clientScope = null; + message = XACMLErrorConstants.ERROR_DATA_ISSUE + policyType + + " is not a valid Policy Type."; + } + } + + public String getResult() { + return deleteResult; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java new file mode 100644 index 000000000..1d4305a3b --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Firewall Policy Implementation. + * + * @version 0.1 + */ +public class FirewallPolicyService { + private static Logger LOGGER = FlexLogger.getLogger(FirewallPolicyService.class.getName()); + private static PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private boolean levelCheck = false; + private JsonObject firewallJson = null; + + public FirewallPolicyService(String policyName, String policyScope, + PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + if(policyParameters.getConfigBody()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given."; + return false; + } + try{ + firewallJson = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); + } catch(JsonException| IllegalStateException e){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + return false; + } + if(firewallJson==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config-Body given."; + return false; + } + levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + //set values for basic policy information + String configName = firewallJson.get("configName").toString(); + String configDescription = ""; + String json = firewallJson.toString(); + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Firewall Config", policyName, configDescription, configName, updateFlag, policyScope, json, 0, + policyParameters.getRiskLevel(),policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); + // Send Json to PAP. + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigFirewall"); + LOGGER.info(response); + return response; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java new file mode 100644 index 000000000..b501a5c6a --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java @@ -0,0 +1,303 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import org.openecomp.policy.api.ConfigRequestParameters; +import org.openecomp.policy.api.PolicyConfigException; +import org.openecomp.policy.api.PolicyConfigStatus; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.models.PDPResponse; +import org.openecomp.policy.pdp.rest.api.models.PolicyConfig; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class GetConfigService { + private static Logger LOGGER = FlexLogger.getLogger(GetConfigService.class.getName()); + + private ConfigRequestParameters configRequestParameters = null; + private String message = null; + private HttpStatus responseCode = HttpStatus.BAD_REQUEST; + private Collection<PolicyConfig> policyConfigs = null; + private boolean unique = false; + + public GetConfigService(ConfigRequestParameters configRequestParameters, + String requestID){ + this.configRequestParameters = configRequestParameters; + if(configRequestParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.configRequestParameters.setRequestID(requestUUID); + } + policyConfigs = new ArrayList<PolicyConfig>(); + try{ + run(); + specialCheck(); + }catch(PolicyConfigException e){ + PolicyConfig policyConfig = new PolicyConfig(); + policyConfig.setPolicyConfigMessage(e.getMessage()); + policyConfig.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); + policyConfigs.add(policyConfig); + responseCode = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if(policyConfigs==null || policyConfigs.size()==0){ + responseCode = HttpStatus.BAD_REQUEST; + }else if(policyConfigs.size()==1){ + for(PolicyConfig policyConfig: policyConfigs){ + if(policyConfig.getPolicyConfigMessage()!=null && policyConfig.getPolicyConfigMessage().contains("PE300")){ + responseCode = HttpStatus.BAD_REQUEST; + } + } + }else{ + responseCode = HttpStatus.OK; + } + } + + private void run() throws PolicyConfigException{ + // getValidation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyConfigException(message); + } + // Generate Request. + String modelString = getModel().toString(); + LOGGER.debug("Generated JSON Request is: " + modelString); + if(configRequestParameters.getUnique()){ + LOGGER.info("Requested for Unique Result only. "); + unique = true; + } + // Process Result. + try { + PDPServices pdpServices = new PDPServices(); + responseCode = HttpStatus.OK; + policyConfigs = configResult(pdpServices.generateRequest(modelString, configRequestParameters.getRequestID(), unique, false)); + // Filter addition. + policyConfigs = filterResults(policyConfigs, configRequestParameters); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + responseCode = HttpStatus.BAD_REQUEST; + throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e); + } + } + + private Collection<PolicyConfig> configResult( + Collection<PDPResponse> generateRequest) { + Collection<PolicyConfig> result = new HashSet<PolicyConfig>(); + if (generateRequest == null) { + return null; + } + if (!generateRequest.isEmpty()) { + for (PDPResponse stdStatus : generateRequest) { + PolicyConfig policyConfig = new PolicyConfig(); + policyConfig.setConfig(stdStatus.getConfig()); + policyConfig.setMatchingConditions(stdStatus.getMatchingConditions()); + policyConfig.setPolicyConfigMessage(stdStatus.getPolicyConfigMessage()); + policyConfig.setPolicyConfigStatus(stdStatus.getPolicyConfigStatus()); + policyConfig.setPolicyName(stdStatus.getPolicyName()); + policyConfig.setPolicyVersion(stdStatus.getPolicyVersion()); + policyConfig.setProperty(stdStatus.getProperty()); + policyConfig.setResponseAttributes(stdStatus.getResponseAttributes()); + policyConfig.setType(stdStatus.getType()); + result.add(policyConfig); + } + } + return result; + } + + // Filter logic required for results comparing with requests. + private Collection<PolicyConfig> filterResults( + Collection<PolicyConfig> policyConfigs, + ConfigRequestParameters configRequestParameters) { + List<PolicyConfig> policyConfig = new ArrayList<PolicyConfig>(); + for(PolicyConfig config: policyConfigs){ + if(config.getPolicyName()!=null && configRequestParameters.getPolicyName()!=null && configRequestParameters.getPolicyName().trim().length()>0){ + if(!config.getPolicyName().matches(configRequestParameters.getPolicyName())){ + continue; + } + } + if(config.getMatchingConditions()!=null && config.getMatchingConditions().size()>0){ + if(configRequestParameters.getEcompName()!=null && configRequestParameters.getEcompName().trim().length()>0 && config.getMatchingConditions().containsKey("ECOMPName")){ + if(!config.getMatchingConditions().get("ECOMPName").matches(configRequestParameters.getEcompName())){ + continue; + } + } + if(configRequestParameters.getConfigName()!=null && configRequestParameters.getConfigName().trim().length()>0 && config.getMatchingConditions().containsKey("ConfigName")){ + if(!config.getMatchingConditions().get("ConfigName").matches(configRequestParameters.getConfigName())){ + continue; + } + } + if(configRequestParameters.getConfigAttributes()!=null && configRequestParameters.getConfigAttributes().size()>0){ + boolean flag = false; + for(String key: configRequestParameters.getConfigAttributes().keySet()){ + if(!config.getMatchingConditions().containsKey(key) || !config.getMatchingConditions().get(key).matches(configRequestParameters.getConfigAttributes().get(key))){ + flag = true; + break; + } + } + if(flag){ + continue; + } + } + } + policyConfig.add(config); + } + if(policyConfig.size()==0){ + PolicyConfig pConfig = new PolicyConfig(); + pConfig.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); + pConfig.setPolicyConfigMessage(XACMLErrorConstants.ERROR_DATA_ISSUE+"No Match Found, for the parameters sent."); + policyConfig.add(pConfig); + } + return policyConfig; + } + + private JsonObject getModel() throws PolicyConfigException{ + String policyName = configRequestParameters.getPolicyName(); + if(policyName!= null && !policyName.trim().isEmpty() && !policyName.endsWith("xml")){ + policyName = policyName + ".[\\d].*"; + configRequestParameters.setPolicyName(policyName); + } + JsonArrayBuilder subjectArray = Json.createArrayBuilder(); + JsonArrayBuilder resourceArray = Json.createArrayBuilder(); + if(configRequestParameters.getPolicyName()!=null){ + JsonObjectBuilder subjectBuilder = Json.createObjectBuilder(); + subjectBuilder.add("Value", policyName); + subjectBuilder.add("AttributeId", "PolicyName"); + subjectArray.add(subjectBuilder); + }else{ + LOGGER.info("PolicyName values are not given. "); + } + if(configRequestParameters.getEcompName()!=null){ + JsonObjectBuilder subjectBuilder = Json.createObjectBuilder(); + subjectBuilder.add("Value", configRequestParameters.getEcompName()); + subjectBuilder.add("AttributeId", "ECOMPName"); + subjectArray.add(subjectBuilder); + if(configRequestParameters.getConfigName()!=null){ + subjectBuilder = Json.createObjectBuilder(); + subjectBuilder.add("Value", configRequestParameters.getConfigName()); + subjectBuilder.add("AttributeId", "ConfigName"); + subjectArray.add(subjectBuilder); + resourceArray = getResourceArray(configRequestParameters.getConfigAttributes()); + }else{ + LOGGER.info("Config Name is not given. "); + } + }else{ + LOGGER.info("Ecomp Name is not given. "); + } + JsonObject model = Json.createObjectBuilder() + .add("Request",Json.createObjectBuilder() + .add("AccessSubject",Json.createObjectBuilder() + .add("Attribute",subjectArray)) + .add("Action",Json.createObjectBuilder() + .add("Attribute",Json.createObjectBuilder() + .add("Value","ACCESS") + .add("AttributeId","urn:oasis:names:tc:xacml:1.0:action:action-id"))) + .add("Resource",Json.createObjectBuilder() + .add("Attribute",resourceArray + .add(Json.createObjectBuilder() + .add("Value","Config") + .add("AttributeId","urn:oasis:names:tc:xacml:1.0:resource:resource-id"))))) + .build(); + return model; + } + + private JsonArrayBuilder getResourceArray(Map<String, String> configAttributes) throws PolicyConfigException{ + JsonArrayBuilder resourceArray = Json.createArrayBuilder(); + configAttributes = configRequestParameters.getConfigAttributes(); + if (configAttributes != null && !configAttributes.isEmpty()) { + if(!configAttributes.containsKey("RiskType")){ + configAttributes.put("RiskType", ".*"); + } + if(!configAttributes.containsKey("RiskLevel")){ + configAttributes.put("RiskLevel", ".*"); + } + if(!configAttributes.containsKey("guard")){ + configAttributes.put("guard", ".*"); + } + if(!configAttributes.containsKey("TTLDate")){ + configAttributes.put("TTLDate", ".*"); + } + }else{ + // ConfigAttributes is Null. So add basic values. + configAttributes = new HashMap<String,String>(); + configAttributes.put("RiskType", ".*"); + configAttributes.put("RiskLevel", ".*"); + configAttributes.put("guard", ".*"); + configAttributes.put("TTLDate", ".*"); + } + for (String key : configAttributes.keySet()) { + if (key.isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; + LOGGER.error(message); + throw new PolicyConfigException(message); + } + JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); + resourceBuilder.add("Value", configAttributes.get(key)); + resourceBuilder.add("AttributeId", key); + resourceArray.add(resourceBuilder); + } + return resourceArray; + } + + private Boolean getValidation(){ + if(configRequestParameters==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No config Request Parameters given."; + return false; + } + if(configRequestParameters.getEcompName()==null && configRequestParameters.getPolicyName()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot proceed without eCOMPComponentName or PolicyName"; + return false; + } + return true; + } + + public Collection<PolicyConfig> getResult() { + return policyConfigs; + } + + public HttpStatus getResponseCode() { + return responseCode; + } +}
\ No newline at end of file diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java new file mode 100644 index 000000000..33f2d07d7 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java @@ -0,0 +1,180 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.Collection; +import java.util.Map; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import org.openecomp.policy.api.DecisionRequestParameters; +import org.openecomp.policy.api.DecisionResponse; +import org.openecomp.policy.api.PolicyDecision; +import org.openecomp.policy.api.PolicyDecisionException; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.models.PDPResponse; +import org.openecomp.policy.std.StdDecisionResponse; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class GetDecisionService { + private static Logger LOGGER = FlexLogger.getLogger(GetDecisionService.class.getName()); + + private DecisionResponse decisionResponse = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private DecisionRequestParameters decisionRequestParameters = null; + private String message = null; + private String eCOMPComponentName = null; + private Map<String,String> decisionAttributes = null; + + public GetDecisionService( + DecisionRequestParameters decisionRequestParameters, + String requestID) { + this.decisionRequestParameters = decisionRequestParameters; + if(decisionRequestParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.decisionRequestParameters.setRequestID(requestUUID); + } + try{ + run(); + }catch(PolicyDecisionException e){ + StdDecisionResponse decisionResponse = new StdDecisionResponse(); + decisionResponse.setDecision(PolicyDecision.ERROR); + decisionResponse.setDetails(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + this.decisionResponse = decisionResponse; + status = HttpStatus.BAD_REQUEST; + } + } + + private void run() throws PolicyDecisionException{ + // Get Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyDecisionException(message); + } + // Generate Request. + String modelString = getModel().toString(); + LOGGER.debug("Generated JSON Request is: " + modelString); + // Process Result. + try { + PDPServices pdpServices = new PDPServices(); + status = HttpStatus.OK; + decisionResponse = decisionResult(pdpServices.generateRequest(modelString, decisionRequestParameters.getRequestID(), false, true)); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyDecisionException(e); + } + } + + private DecisionResponse decisionResult( + Collection<PDPResponse> generateRequest) { + StdDecisionResponse policyDecision = new StdDecisionResponse(); + if (generateRequest == null) { + return policyDecision; + } + if (!generateRequest.isEmpty()) { + for (PDPResponse stdStatus : generateRequest) { + policyDecision.setDecision(stdStatus.getDecision()); + policyDecision.setDetails(stdStatus.getDetails()); + } + } + return policyDecision; + } + + private JsonObject getModel() throws PolicyDecisionException{ + JsonArrayBuilder resourceArray = Json.createArrayBuilder(); + for (String key : decisionAttributes.keySet()) { + if (key.isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; + LOGGER.error(message); + throw new PolicyDecisionException(message); + } + JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); + if (decisionAttributes.get(key).matches("[0-9]+")) { + int val = Integer.parseInt(decisionAttributes.get(key)); + resourceBuilder.add("Value", val); + } else { + resourceBuilder.add("Value", decisionAttributes.get(key)); + } + resourceBuilder.add("AttributeId", key); + resourceArray.add(resourceBuilder); + } + JsonObject model = Json + .createObjectBuilder() + .add("Request", Json.createObjectBuilder() + .add("AccessSubject", Json.createObjectBuilder() + .add("Attribute", Json.createObjectBuilder() + .add("Value", eCOMPComponentName) + .add("AttributeId", "ECOMPName"))) + .add("Resource", Json.createObjectBuilder() + .add("Attribute", resourceArray)) + .add("Action", Json.createObjectBuilder() + .add("Attribute", Json.createObjectBuilder() + .add("Value", "DECIDE") + .add("AttributeId", "urn:oasis:names:tc:xacml:1.0:action:action-id")))) + .build(); + return model; + } + + private boolean getValidation() { + if(decisionRequestParameters==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Paramaters"; + return false; + } + eCOMPComponentName = decisionRequestParameters.getECOMPComponentName(); + decisionAttributes = decisionRequestParameters.getDecisionAttributes(); + if (eCOMPComponentName == null || eCOMPComponentName.isEmpty()) { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given : " + eCOMPComponentName; + return false; + } + if (decisionAttributes == null && decisionAttributes.isEmpty()) { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Attributes Given. "; + return false; + } + return true; + } + + public DecisionResponse getResult() { + return decisionResponse; + } + + public HttpStatus getResponseCode() { + return status; + } + +} + diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java new file mode 100644 index 000000000..2305ecbec --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java @@ -0,0 +1,273 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.UUID; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.openecomp.policy.api.DictionaryParameters; +import org.openecomp.policy.api.DictionaryResponse; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.openecomp.policy.std.StdDictionaryResponse; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class GetDictionaryService { + private static Logger LOGGER = FlexLogger.getLogger(GetDictionaryService.class.getName()); + + private DictionaryResponse dictionaryResponse = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private String message = null; + private DictionaryParameters dictionaryParameters = null; + + public GetDictionaryService(DictionaryParameters dictionaryParameters, + String requestID) { + this.dictionaryParameters = dictionaryParameters; + if(dictionaryParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.dictionaryParameters.setRequestID(requestUUID); + } + try{ + run(); + specialCheck(); + }catch(PolicyException e){ + StdDictionaryResponse dictionaryResponse = new StdDictionaryResponse(); + dictionaryResponse.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + this.dictionaryResponse = dictionaryResponse; + status = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if(dictionaryResponse!=null){ + if(dictionaryResponse.getResponseMessage()!=null && dictionaryResponse.getResponseMessage().contains("PE300")){ + status = HttpStatus.BAD_REQUEST; + } + } + } + + private void run() throws PolicyException{ + // Check Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyException(message); + } + // Get Result. + try{ + status = HttpStatus.OK; + dictionaryResponse = processResult(); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + private DictionaryResponse processResult() throws PolicyException{ + StdDictionaryResponse response = new StdDictionaryResponse(); + PAPServices papServices = new PAPServices(); + String result = (String) papServices.callPAP(null, new String[] {"operation=get", "apiflag=api", "dictionaryType="+dictionaryParameters.getDictionary()}, dictionaryParameters.getRequestID(), "dictionaryItem"); + + if (result!=null && result.contains("data")) { + String jsonString = formatDictionaryJson(result); + String responseMessage = result.substring(0, 82); + JsonObject json = null; + try{ + json = PolicyApiUtils.stringToJsonObject(jsonString.replace("\\\\\\", "\\")); + String datas = json.getString("data").replaceFirst("\"\\[", "["); + int i = datas.lastIndexOf("]"); + if( i>=0 ) { + datas = new StringBuilder(datas).replace(i, i+2,"]").toString(); + } + json = PolicyApiUtils.stringToJsonObject(datas); + } catch(JsonException| IllegalStateException e){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper Dictionary JSON object : " + dictionaryParameters.getDictionaryJson(); + LOGGER.error(message); + response.setResponseMessage(message); + response.setResponseCode(400); + return response; + } + response.setResponseCode(papServices.getResponseCode()); + response.setDictionaryJson(json); + response.setResponseMessage(responseMessage); + } else { + response.setResponseCode(400); + response.setResponseMessage(result); + } + return response; + } + + private String formatDictionaryJson(String result) { + String jsonString = result.substring(82); + String dictionary = dictionaryParameters.getDictionary(); + + switch (dictionary) { + case "EcompName": + jsonString = jsonString.replace("ecompNameDictionaryDatas", "DictionaryDatas"); + break; + case "Attribute": + jsonString = jsonString.replace("attributeDictionaryDatas", "DictionaryDatas"); + break; + case "Action": + jsonString = jsonString.replace("actionPolicyDictionaryDatas", "DictionaryDatas"); + break; + case "BRMSParamTemplate": + jsonString = jsonString.replace("brmsParamDictionaryDatas", "DictionaryDatas"); + break; + case "VSCLAction": + jsonString = jsonString.replace("vsclActionDictionaryDatas", "DictionaryDatas"); + break; + case "VNFType": + jsonString = jsonString.replace("vnfTypeDictionaryDatas", "DictionaryDatas"); + break; + case "PEPOptions": + jsonString = jsonString.replace("pepOptionsDictionaryDatas", "DictionaryDatas"); + break; + case "Varbind": + jsonString = jsonString.replace("varbindDictionaryDatas", "DictionaryDatas"); + break; + case "Service": + jsonString = jsonString.replace("closedLoopServiceDictionaryDatas", "DictionaryDatas"); + break; + case "Site": + jsonString = jsonString.replace("closedLoopSiteDictionaryDatas", "DictionaryDatas"); + break; + case "Settings": + jsonString = jsonString.replace("settingsDictionaryDatas", "DictionaryDatas"); + break; + case "DescriptiveScope": + jsonString = jsonString.replace("descriptiveScopeDictionaryDatas", "DictionaryDatas"); + break; + case "Enforcer": + jsonString = jsonString.replace("enforcerDictionaryDatas", "DictionaryDatas"); + break; + case "ActionList": + jsonString = jsonString.replace("actionListDictionaryDatas", "DictionaryDatas"); + break; + case "ProtocolList": + jsonString = jsonString.replace("protocolListDictionaryDatas", "DictionaryDatas"); + break; + case "Zone": + jsonString = jsonString.replace("zoneDictionaryDatas", "DictionaryDatas"); + break; + case "SecurityZone": + jsonString = jsonString.replace("securityZoneDictionaryDatas", "DictionaryDatas"); + break; + case "PrefixList": + jsonString = jsonString.replace("prefixListDictionaryDatas", "DictionaryDatas"); + break; + case "AddressGroup": + jsonString = jsonString.replace("addressGroupDictionaryDatas", "DictionaryDatas"); + break; + case "ServiceGroup": + jsonString = jsonString.replace("serviceGroupDictionaryDatas", "DictionaryDatas"); + break; + case "ServiceList": + jsonString = jsonString.replace("serviceListDictionaryDatas", "DictionaryDatas"); + break; + case "TermList": + case "RuleList": + case "FirewallRuleList": + case "Term": + jsonString = jsonString.replace("termListDictionaryDatas", "DictionaryDatas"); + break; + case "MicroServiceLocation": + jsonString = jsonString.replace("microServiceLocationDictionaryDatas", "DictionaryDatas"); + break; + case "MicroServiceConfigName": + jsonString = jsonString.replace("microServiceCongigNameDictionaryDatas", "DictionaryDatas"); + break; + case "DCAEUUID": + jsonString = jsonString.replace("dcaeUUIDDictionaryDatas", "DictionaryDatas"); + break; + case "MicroServiceModels": + jsonString = jsonString.replace("microServiceModelsDictionaryDatas", "DictionaryDatas"); + break; + case "PolicyScopeService": + jsonString = jsonString.replace("psServiceDictionaryDatas", "DictionaryDatas"); + break; + case "PolicyScopeResource": + jsonString = jsonString.replace("psResourceDictionaryDatas", "DictionaryDatas"); + break; + case "PolicyScopeType": + jsonString = jsonString.replace("psTypeDictionaryDatas", "DictionaryDatas"); + break; + case "PolicyScopeClosedLoop": + jsonString = jsonString.replace("psClosedLoopDictionaryDatas", "DictionaryDatas"); + break; + case "GroupPolicyScopeList": + jsonString = jsonString.replace("groupPolicyScopeListDatas", "DictionaryDatas"); + break; + case "RiskType": + jsonString = jsonString.replace("riskTypeDictionaryDatas", "DictionaryDatas"); + break; + case "SafePolicyWarning": + jsonString = jsonString.replace("safePolicyWarningDatas", "DictionaryDatas"); + break; + case "MicroServiceDictionary": + jsonString = jsonString.replace("microServiceDictionaryDatas", "DictionaryDatas"); + break; + default: + return null; + } + return jsonString; + } + + private boolean getValidation() { + if(dictionaryParameters==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Dictionary Parameters are not given."; + return false; + } + if(dictionaryParameters.getDictionaryType()==null || dictionaryParameters.getDictionaryType().toString().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Type given."; + return false; + } + if(dictionaryParameters.getDictionary()==null || dictionaryParameters.getDictionary().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary given."; + return false; + } + return true; + } + + public DictionaryResponse getResult() { + return dictionaryResponse; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java new file mode 100644 index 000000000..14812edfb --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java @@ -0,0 +1,160 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.UUID; + +import javax.json.JsonException; + +import org.json.JSONObject; +import org.openecomp.policy.api.MetricsRequestParameters; +import org.openecomp.policy.api.MetricsResponse; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.std.StdMetricsResponse; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class GetMetricsService { + private static Logger LOGGER = FlexLogger + .getLogger(GetDictionaryService.class.getName()); + + private MetricsResponse response = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private String message = null; + private MetricsRequestParameters metricsParameters = null; + + public GetMetricsService(String requestID) { + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + } else { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + metricsParameters = new MetricsRequestParameters(); + this.metricsParameters.setRequestID(requestUUID); + + try { + run(); + specialCheck(); + } catch (PolicyException e) { + StdMetricsResponse metricsResponse = new StdMetricsResponse(); + metricsResponse + .setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + + e); + this.response = metricsResponse; + status = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if (response != null) { + if (response.getResponseMessage() != null + && response.getResponseMessage().contains("PE300")) { + status = HttpStatus.BAD_REQUEST; + } + } + } + + private void run() throws PolicyException { + // Check Validation. + /* + * if(!getValidation()){ LOGGER.error(message); throw new + * PolicyException(message); } + */ + // Get Result. + try { + status = HttpStatus.OK; + response = processResult(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + private MetricsResponse processResult() throws PolicyException { + StdMetricsResponse metricsResponse = new StdMetricsResponse(); + PAPServices papServices = new PAPServices(); + String result = (String) papServices.callPAP(null, new String[] { + "operation=get", "apiflag=getMetrics" }, + metricsParameters.getRequestID(), "metrics"); + + JSONObject json = null; + if (result != null) { + if (result.length() > 81 && result.contains("{")) { + try { + String responseMessage = result.substring(0, 82); + String jsonString = result.substring(result.indexOf("{"), + result.length()); + json = new JSONObject(jsonString); + + int papCount = (int) json.get("papCount"); + int pdpCount = (int) json.get("pdpCount"); + + metricsResponse.setResponseCode(papServices + .getResponseCode()); + metricsResponse.setResponseMessage(responseMessage); + metricsResponse.setPapMetrics(papCount); + metricsResponse.setPdpMetrics(pdpCount); + + } catch (JsonException | IllegalStateException e) { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + + " improper JSON object : " + json.toString(); + LOGGER.error(message); + metricsResponse.setResponseMessage(message); + metricsResponse.setResponseCode(400); + return metricsResponse; + } + } else { + message = result; + metricsResponse.setResponseCode(400); + metricsResponse.setResponseMessage(message); + return metricsResponse; + } + + } else { + message = XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "There was an issue with connecting to the PAP, " + + "review the logs for further debugging."; + metricsResponse.setResponseCode(500); + metricsResponse.setResponseMessage(message); + return metricsResponse; + } + + return metricsResponse; + } + + public MetricsResponse getResult() { + return response; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ListConfigService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ListConfigService.java new file mode 100644 index 000000000..9aca4c049 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ListConfigService.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.ArrayList; +import java.util.Collection; + +import org.openecomp.policy.api.ConfigRequestParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.models.PolicyConfig; +import org.springframework.http.HttpStatus; + +public class ListConfigService { + private static Logger LOGGER = FlexLogger.getLogger(ListConfigService.class.getName()); + + private Collection<String> results = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + + public ListConfigService(ConfigRequestParameters configRequestParameters, + String requestID) { + GetConfigService getConfigService = new GetConfigService(configRequestParameters,requestID); + Collection<PolicyConfig> policyConfigs = getConfigService.getResult(); + LOGGER.info("Transferring Config Results to List. "); + if(policyConfigs!=null){ + results = new ArrayList<String>(); + status = HttpStatus.OK; + for(PolicyConfig policyConfig : policyConfigs){ + if(policyConfig.getPolicyConfigMessage()!=null && policyConfig.getPolicyConfigMessage().contains("PE300")){ + results.add(policyConfig.getPolicyConfigMessage()); + status = HttpStatus.BAD_REQUEST; + } else { + results.add("Policy Name: " + policyConfig.getPolicyName()); + } + } + } + } + + public Collection<String> getResult() { + return results; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java new file mode 100644 index 000000000..636b7fbf8 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; + +/** + * MicroServices Policy implementation. + * + * @version 0.1 + */ +public class MicroServicesPolicyService{ + private static Logger LOGGER = FlexLogger.getLogger(MicroServicesPolicyService.class.getName()); + private static PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private String ecompName = null; + private JsonObject microServiceAttributes = null; + private boolean levelCheck = false; + + public MicroServicesPolicyService(String policyName, String policyScope, PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + if(policyParameters.getConfigBody()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Micro Service or Attributes Config Body Present"; + return false; + } + try{ + microServiceAttributes = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); + } catch(JsonException| IllegalStateException e){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + return false; + } + ecompName = policyParameters.getEcompName(); + if (ecompName==null||ecompName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; + return false; + } + levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException{ + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + // get values and attributes from the JsonObject + String uuid = null; + String msLocation = null; + String configName = null; + String microService = microServiceAttributes.get("service").toString().replace("\"", ""); + if (microServiceAttributes.get("uuid")!=null){ + uuid = microServiceAttributes.get("uuid").toString().replace("\"", ""); + } + if (microServiceAttributes.get("location")!=null){ + msLocation = microServiceAttributes.get("location").toString().replace("\"", ""); + } + if (microServiceAttributes.get("configName")!=null){ + configName = microServiceAttributes.get("configName").toString().replace("\"", ""); + } + String policyDescription = microServiceAttributes.get("description").toString().replace("\"", ""); + String priority = microServiceAttributes.get("priority").toString().replace("\"", ""); + String version = microServiceAttributes.get("version").toString().replace("\"", ""); + + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Micro Service", policyName, policyDescription, ecompName, + configName, microService, uuid, msLocation, microServiceAttributes.toString(), priority, + version, updateFlag, policyScope, 0, policyParameters.getRiskLevel(), + policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); + // Send JSON Object to PAP. + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigMS"); + LOGGER.info("Policy MS created Response: " + response); + return response; + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java new file mode 100644 index 000000000..b00346de6 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java @@ -0,0 +1,900 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.io.IOUtils; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.config.PDPApiAuth; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; + +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PAPServices { + private static final String SUCCESS = "success"; + private static Logger LOGGER = FlexLogger.getLogger(PAPServices.class + .getName()); + + private int responseCode = 0; + private static String environment = "DEVL"; + private static Boolean junit = false; + private static List<String> paps = null; + private static final Object papResourceLock = new Object(); + private String operation = null; + private String requestMethod = null; + private String encoding = null; + + public PAPServices() { + environment = PDPApiAuth.getEnvironment(); + if(paps == null){ + synchronized (papResourceLock) { + String urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS); + if(urlList == null){ + urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + } + paps = Arrays.asList(urlList.split(",")); + } + } + } + + private String getPAPEncoding(){ + if(encoding == null){ + String userID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String pass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + Base64.Encoder encoder = Base64.getEncoder(); + encoding = encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)); + } + return encoding; + } + + private void rotatePAPList(){ + synchronized (papResourceLock) { + Collections.rotate(paps, -1); + } + } + + private String getPAP(){ + String result; + synchronized (papResourceLock) { + result = paps.get(0); + } + return result; + } + + public int getResponseCode() { + return responseCode; + } + + public Object callPAP(Object content, String[] parameters, UUID requestID, + String clientScope) throws PolicyException { + String response = null; + HttpURLConnection connection = null; + responseCode = 0; + // Checking for the available PAPs is done during the first Request and + // the List is going to have the connected PAP as first element. + // This makes it Real-Time to change the list depending on their + // availability. + if (paps == null || paps.isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty."; + LOGGER.error(message); + throw new PolicyException(message); + } + int papsCount = 0; + boolean connected = false; + while (papsCount < paps.size()) { + try { + String fullURL = getPAP(); + fullURL = checkParameter(parameters, fullURL); + URL url = new URL(fullURL); + LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---"); + // Open the connection + connection = (HttpURLConnection) url.openConnection(); + // Setting Content-Type + connection.setRequestProperty("Content-Type","application/json"); + // Adding Authorization + connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding()); + connection.setRequestProperty("Environment", environment); + connection.setRequestProperty("ClientScope", clientScope); + // set the method and headers + connection.setRequestMethod(requestMethod); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + // Adding RequestID + if (requestID == null) { + requestID = UUID.randomUUID(); + LOGGER.info("No request ID provided, sending generated ID: " + + requestID.toString()); + } else { + LOGGER.info("Using provided request ID: " + + requestID.toString()); + } + connection.setRequestProperty("X-ECOMP-RequestID", + requestID.toString()); + if (content != null && (content instanceof InputStream)) { + // send current configuration + try (OutputStream os = connection.getOutputStream()) { + int count = IOUtils.copy((InputStream) content, os); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("copied to output, bytes=" + count); + } + } + } else if(content != null){ + // the content is an object to be encoded in JSON + ObjectMapper mapper = new ObjectMapper(); + if (!junit) { + mapper.writeValue(connection.getOutputStream(), + content); + } + } + // DO the connect + connection.connect(); + responseCode = connection.getResponseCode(); + // If Connected to PAP then break from the loop and continue + // with the Request + if (connection.getResponseCode() > 0 || junit) { + connected = true; + break; + } else { + LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : " + connection.getResponseCode()); + rotatePAPList(); + } + } catch (Exception e) { + // This means that the PAP is not working + if (junit) { + connected = true; + break; + } + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "PAP connection Error : " + e); + rotatePAPList(); + } + papsCount++; + } + if (connected) { + // Read the Response + LOGGER.debug("connected to the PAP : " + getPAP()); + LOGGER.debug("--- Response: ---"); + Map<String, List<String>> headers = connection.getHeaderFields(); + for (String key : headers.keySet()) { + LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); + } + + try { + response = checkResponse(connection, requestID); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + e; + throw new PolicyException( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Decoding the result ", e); + } + if (junit) { + response = SUCCESS; + } + return response; + } else { + response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Unable to get valid response from PAP(s) " + paps; + return response; + } + } + + public String getActiveVersion(String policyScope, String filePrefix, String policyName, String clientScope, UUID requestID) { + String version = null; + HttpURLConnection connection = null; + String [] parameters = {"apiflag=version","policyScope="+policyScope, "filePrefix="+filePrefix, "policyName="+policyName}; + if (paps == null || paps.isEmpty()) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty."); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty."); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + } + }else { + int papsCount = 0; + boolean connected = false; + while (papsCount < paps.size()) { + try { + String fullURL = getPAP(); + if (parameters != null && parameters.length > 0) { + String queryString = ""; + for (String p : parameters) { + queryString += "&" + p; + } + fullURL += "?" + queryString.substring(1); + } + + URL url = new URL (fullURL); + + //Open the connection + connection = (HttpURLConnection)url.openConnection(); + + // Setting Content-Type + connection.setRequestProperty("Content-Type", + "application/json"); + + // Adding Authorization + connection.setRequestProperty("Authorization", "Basic " + + getPAPEncoding()); + + connection.setRequestProperty("Environment", environment); + connection.setRequestProperty("ClientScope", clientScope); + + + //set the method and headers + connection.setRequestMethod("GET"); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + // mb1915 - begin + // mb1915 - set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another + connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString()); + // mb1915 - end + + //DO the connect + connection.connect(); + + // If Connected to PAP then break from the loop and continue with the Request + if (connection.getResponseCode() > 0) { + connected = true; + break; + + } else { + LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error"); + } + } catch (Exception e) { + // This means that the PAP is not working + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e); + rotatePAPList(); + } + papsCount++; + } + + if (connected) { + //Read the Response + LOGGER.debug("connected to the PAP : " + getPAP()); + LOGGER.debug("--- Response: ---"); + Map<String, List<String>> headers = connection.getHeaderFields(); + for (String key : headers.keySet()) { + LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); + } + try { + if (connection.getResponseCode() == 200) { + // Check for successful creation of policy + version = connection.getHeaderField("version"); + LOGGER.debug("ActiveVersion from the Header: " + version); + } else if (connection.getResponseCode() == 403) { + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is " + + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. "); + version = "pe100"; + } else if (connection.getResponseCode() == 404) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is " + + connection.getResponseCode() + ". This indicates a problem with getting the version from the PAP"); + version = "pe300"; + } else { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: Error occured while getting the version from the PAP. The request may be incorrect."); + } + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e); + } catch (Exception e1) { + LOGGER.error(e1.getMessage()); + } + } + + } else { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP "); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + } + } + } + return version; + } + + public StdPDPPolicy getGitPath(String policyScope, String filePrefix, String policyName, String activeVersion, String clientScope, UUID requestID, String id) throws PolicyException{ + String gitPath = null; + Boolean isValid = false; + String policyId= null; + String description = null; + String pushVersion = null; + HttpURLConnection connection = null; + String [] parameters = {"apiflag=gitPath", "policyScope="+policyScope, "filePrefix="+filePrefix, + "policyName="+policyName, "activeVersion="+activeVersion}; + if (paps == null || paps.isEmpty()) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty."); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty."); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + } + }else { + int papsCount = 0; + boolean connected = false; + while (papsCount < paps.size()) { + try { + String fullURL = getPAP(); + if (parameters != null && parameters.length > 0) { + String queryString = ""; + for (String p : parameters) { + queryString += "&" + p; + } + fullURL += "?" + queryString.substring(1); + } + + URL url = new URL (fullURL); + + //Open the connection + connection = (HttpURLConnection)url.openConnection(); + + // Setting Content-Type + connection.setRequestProperty("Content-Type", + "application/json"); + + // Adding Authorization + connection.setRequestProperty("Authorization", "Basic " + +getPAPEncoding()); + + connection.setRequestProperty("Environment", environment); + connection.setRequestProperty("ClientScope", clientScope); + + //set the method and headers + connection.setRequestMethod("GET"); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + // mb1915 - begin + // mb1915 - set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another + connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString()); + // mb1915 - end + + //DO the connect + connection.connect(); + + // If Connected to PAP then break from the loop and continue with the Request + if (connection.getResponseCode() > 0) { + connected = true; + break; + + } else { + LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error"); + } + } catch (Exception e) { + // This means that the PAP is not working + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e); + rotatePAPList(); + } + papsCount++; + } + + if (connected) { + //Read the Response + LOGGER.debug("connected to the PAP : " + getPAP()); + LOGGER.debug("--- Response: ---"); + Map<String, List<String>> headers = connection.getHeaderFields(); + for (String key : headers.keySet()) { + LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); + } + try { + if (connection.getResponseCode() == 200) { + // Check for successful creation of policy + gitPath = connection.getHeaderField("gitPath"); + policyId = connection.getHeaderField("policyId"); + description = connection.getHeaderField("description"); + pushVersion = connection.getHeaderField("version"); + isValid = Boolean.parseBoolean(connection.getHeaderField("isValid")); + + LOGGER.debug("GitPath from Header: " + gitPath); + LOGGER.debug("policyId from Header: " + policyId); + LOGGER.debug("description from Header: " + description); + LOGGER.debug("version from Header: " + pushVersion); + LOGGER.debug("isValid from Header: " + isValid); + + /*if (gitPath != null && !gitPath.equalsIgnoreCase("")) { + return gitPath; + }*/ if (gitPath == null || gitPath.trim().isEmpty()) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the gitPath from the PAP"); + } + } else if (connection.getResponseCode() == 404) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "response code of the URL is " + + connection.getResponseCode() + ". This indicates a problem with getting the gitPath from the PAP"); + } else { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "BAD REQUEST: Error occured while getting the gitPath from the PAP. The request may be incorrect."); + } + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e); + } catch (Exception e1) { + LOGGER.error(e1.getMessage()); + } + } + + } else { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP "); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + } + } + } + LOGGER.debug("Full gitPath policy xml file: " + gitPath); + URI selectedURI = getSelectedURI(gitPath, clientScope, requestID); + LOGGER.debug("The selectedURI is : " + selectedURI.toString()); + String name = filePrefix+policyName; + + StdPDPPolicy selectedPolicy; + try { + selectedPolicy = new StdPDPPolicy(id, true, name, selectedURI, isValid, policyId, description, pushVersion); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+e.getMessage()); + throw new PolicyException(e); + } + return selectedPolicy; + } + + private URI getSelectedURI(String gitPath, String clientScope, UUID requestID){ + URI selectedURI = null; + HttpURLConnection connection = null; + String [] parameters = {"apiflag=uri", "gitPath="+gitPath}; + if (paps == null || paps.isEmpty()) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty."); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty."); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + } + }else { + int papsCount = 0; + boolean connected = false; + while (papsCount < paps.size()) { + try { + String fullURL = getPAP(); + if (parameters != null && parameters.length > 0) { + String queryString = ""; + for (String p : parameters) { + queryString += "&" + p; + } + fullURL += "?" + queryString.substring(1); + } + + URL url = new URL (fullURL); + + //Open the connection + connection = (HttpURLConnection)url.openConnection(); + + // Setting Content-Type + connection.setRequestProperty("Content-Type", + "application/json"); + + // Adding Authorization + connection.setRequestProperty("Authorization", "Basic " + + getPAPEncoding()); + + connection.setRequestProperty("Environment", environment); + connection.setRequestProperty("ClientScope", clientScope); + + //set the method and headers + connection.setRequestMethod("GET"); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + // mb1915 - begin + // mb1915 - set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another + connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString()); + // mb1915 - end + + //DO the connect + connection.connect(); + responseCode = connection.getResponseCode(); + // If Connected to PAP then break from the loop and continue with the Request + if (connection.getResponseCode() > 0) { + connected = true; + break; + + } else { + LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error"); + } + } catch (Exception e) { + // This means that the PAP is not working + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e); + rotatePAPList(); + } + papsCount++; + } + + if (connected) { + //Read the Response + LOGGER.debug("connected to the PAP : " + getPAP()); + LOGGER.debug("--- Response: ---"); + Map<String, List<String>> headers = connection.getHeaderFields(); + for (String key : headers.keySet()) { + LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); + } + try { + if (connection.getResponseCode() == 200) { + // Check for successful creation of policy + String uri = connection.getHeaderField("selectedURI"); + LOGGER.debug("URI from Header: " + uri); + if (uri != null && !uri.equalsIgnoreCase("")) { + selectedURI = URI.create(uri); + return selectedURI; + } else { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the gitPath from the PAP"); + } + } else if (connection.getResponseCode() == 404) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "response code of the URL is " + + connection.getResponseCode() + ". This indicates a problem with getting the gitPath from the PAP"); + } else { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "BAD REQUEST: Error occured while getting the gitPath from the PAP. The request may be incorrect."); + } + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e); + } catch (Exception e1) { + LOGGER.error(e1.getMessage()); + } + } + + } else { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP "); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + } + } + } + return selectedURI; + } + + private String checkResponse(HttpURLConnection connection, UUID requestID) throws IOException { + String response = null; + if (responseCode == 200 || junit) { + // Check for successful creation of policy + String isSuccess = null; + if (!junit) { // is this a junit test? + isSuccess = connection.getHeaderField("successMapKey"); + operation = connection.getHeaderField("operation"); + } else { + isSuccess = SUCCESS; + } + if (SUCCESS.equals(isSuccess)) { + if ("update".equals(operation)) { + response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName") + + " was successfully updated. "; + if (connection.getHeaderField("safetyChecker")!=null) { + response = response + "\nPolicy Safety Checker Warning: This closedLoopControlName (" + + connection.getHeaderField("newCLName") + ") " + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") + + "that already exists." + "See detailed information on ClosedLoop Pairs below: " + +"\n"+connection.getHeaderField("safetyChecker"); + } + } else if ("create".equals(operation)) { + response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName") + + " was successfully created."; + if (connection.getHeaderField("safetyChecker")!=null) { + response = response + "\nPolicy Safety Checker Warning: This closedLoopControlName (" + + connection.getHeaderField("newCLName") + ") " + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") + + "that already exists." + "See detailed information on ClosedLoop Pairs below: " + +"\n"+connection.getHeaderField("safetyChecker"); + } + } else if ("delete".equals(operation)) { + response = "Transaction ID: " + requestID + " --The policy was successfully deleted."; + } else if ("import".equals(operation)) { + response = "Transaction ID: " + requestID + " --The policy engine import for "+ connection.getHeaderField("service") + + " was successfull."; + } else if ("createDictionary".equals(operation)) { + response = "Transaction ID: " + requestID + " --Dictionary Item was added successfully!"; + } else if ("updateDictionary".equals(operation)) { + response = "Transaction ID: " + requestID + " --Dictionary Item was updated successfully!"; + } else if ("getDictionary".equals(operation)) { + String json = null; + try { + + //get the json string from the response + InputStream is = connection.getInputStream(); + + // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) + java.util.Scanner scanner = new java.util.Scanner(is); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + + } catch (IOException e1) { + LOGGER.error(e1.getMessage()); + } + response = "Transaction ID: " + requestID + " --Dictionary Items Retrieved " + json; + } else if ("getMetrics".equals(operation)) { + response = "Transaction ID: " + requestID + " --Policy Metrics Retrieved " + connection.getHeaderField("metrics"); + } + LOGGER.info(response); + } else { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Operation unsuccessful, unable to complete the request!"; + LOGGER.error(message); + response = message; + } + } else if (connection.getResponseCode() == 202) { + if ("delete".equalsIgnoreCase(connection.getHeaderField("operation")) && + "true".equals(connection.getHeaderField("lockdown"))) { + response = "Transaction ID: " + + requestID + + " --Policies are locked down, please try again later."; + LOGGER.warn(response); + } + } else if (connection.getResponseCode() == 204) { + if ("push".equals(connection.getHeaderField("operation"))) { + response = "Transaction ID: " + + requestID + + " --Policy '" + + connection.getHeaderField("policyId") + + "' was successfully pushed to the PDP group '" + + connection.getHeaderField("groupId") + "'."; + LOGGER.info(response); + } + } else if (connection.getResponseCode() == 400 && connection.getHeaderField("error") != null) { + response = connection.getHeaderField("error"); + LOGGER.error(response); + } else if (connection.getResponseCode() == 403) { + response = XACMLErrorConstants.ERROR_PERMISSIONS + + "response code of the URL is " + + connection.getResponseCode() + + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + LOGGER.error(response); + } else if (connection.getResponseCode() == 404 && connection.getHeaderField("error") != null) { + if ("unknownGroupId".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + connection.getHeaderField("message") + + " Please check the pdpGroup you are requesting to move the policy to."; + LOGGER.error(response); + } + } else if (connection.getResponseCode() == 409 && connection.getHeaderField("error") != null) { + if ("modelExistsDB".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Import Value Exist Error: The import value " + + connection.getHeaderField("service") + + " already exist on the PAP. " + + "Please create a new import value."; + } else if ("policyExists".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Policy Exist Error: The Policy " + + connection.getHeaderField("policyName") + + " already exist on the PAP. " + + "Please create a new policy or use the update API to modify the existing one."; + } else if ("dictionaryItemExists".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Dictionary Item Exist Error: The Dictionary Item already exist in the database. " + + "Please create a new Dictionary Item or use the update API to modify the existing one."; + } else if ("duplicateGroup".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Group Policy Scope List Exist Error: The Group Policy Scope List for this Dictionary Item already exist in the database. " + + "Duplicate Group Policy Scope Lists for multiple groupNames is not allowed. " + + "Please review the request and verify that the groupPolicyScopeListData1 is unique compared to existing groups."; + } + LOGGER.error(response); + } else if (connection.getResponseCode() == 500 && connection.getHeaderField("error") != null) { + if ("jpautils".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Could not create JPAUtils instance on the PAP"; + } else if ("deleteDB".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Failed to delete Policy from database."; + } else if ("deleteFile".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Cannot delete the policy file"; + } else if ("groupUpdate".equals(connection.getHeaderField("error"))) { + response = connection.getHeaderField("message"); + } else if ("unknown".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_UNKNOWN + + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."; + } else if ("deleteConfig".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Cannot delete the configuration or action body file in specified location."; + } else if ("missing".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Failed to create value in database because service does match a value in file"; + } else if ("importDB".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Database errors during policy engine import"; + } else if ("policyCopyError".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_PROCESS_FLOW + + connection.getHeaderField("message"); + } else if ("addGroupError".equals(connection.getHeaderField("error"))) { + response = connection.getHeaderField("message"); + } else if ("error".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_UNKNOWN + + "Could not create or update the policy for and unknown reason"; + } + LOGGER.error(response); + } else { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "BAD REQUEST: Error occured while attempting perform this operation.. the request may be incorrect."; + LOGGER.error(response); + } + return response; + } + + private String checkParameter(String[] parameters, String fullURL) { + if (parameters != null && parameters.length > 0) { + String queryString = ""; + for (String p : parameters) { + queryString += "&" + p; + if (p.equalsIgnoreCase("operation=post")) { + requestMethod = "POST"; + } else if (p.equalsIgnoreCase("operation=delete")) { + requestMethod = "DELETE"; + operation = "delete"; + } else if (p.equalsIgnoreCase("operation=get")) { + requestMethod = "GET"; + operation = "get"; + } else if (p.equalsIgnoreCase("operation=put")||p.equalsIgnoreCase("operation=create") + ||p.equalsIgnoreCase("operation=update")||p.equalsIgnoreCase("operation=createDictionary")){ + requestMethod = "PUT"; + if (p.equalsIgnoreCase("operation=create")) { + operation = "create"; + } else if (p.equalsIgnoreCase("operation=update")) { + operation = "update"; + } else if (p.equalsIgnoreCase("operation=createDictionary")){ + operation = "createDictionary"; + } + }else if (p.equalsIgnoreCase("importService=MICROSERVICE")||p.equalsIgnoreCase("importService=BRMSPARAM")){ + requestMethod = "PUT"; + } + } + fullURL += "?" + queryString.substring(1); + } + return fullURL; + } + + public StdPDPPolicy pushPolicy(String policyScope, String filePrefix, + String policyName, String clientScope, String pdpGroup, + UUID requestID) throws PolicyException { + String json = "{ " + + "\"apiflag\": \"api\"," + + "\"policyScope\": \""+policyScope+"\"," + + "\"filePrefix\": \""+filePrefix+"\"," + + "\"policyName\": \""+policyName+"\"," + + "\"clientScope\": \""+clientScope+"\"," + + "\"pdpGroup\": \""+pdpGroup+"\"}"; + //String response = null; + HttpURLConnection connection = null; + responseCode = 0; + if (paps == null || paps.isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty."; + LOGGER.error(message); + throw new PolicyException(message); + } + int papsCount = 0; + boolean connected = false; + while (papsCount < paps.size()) { + try { + String fullURL = getPAP(); + fullURL = (fullURL.endsWith("/"))? fullURL+"ecomp/pushPolicy" : fullURL+"/ecomp/pushPolicy"; + URL url = new URL(fullURL); + LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---"); + // Open the connection + connection = (HttpURLConnection) url.openConnection(); + // Setting Content-Type + connection.setRequestProperty("Content-Type","application/json"); + // Adding Authorization + connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding()); + connection.setRequestProperty("Environment", environment); + connection.setRequestProperty("ClientScope", clientScope); + // set the method and headers + connection.setRequestMethod("POST"); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + // Adding RequestID + if (requestID == null) { + requestID = UUID.randomUUID(); + LOGGER.info("No request ID provided, sending generated ID: " + + requestID.toString()); + } else { + LOGGER.info("Using provided request ID: " + + requestID.toString()); + } + connection.setRequestProperty("X-ECOMP-RequestID", + requestID.toString()); + // DO the connect + try (OutputStream os = connection.getOutputStream()) { + int count = IOUtils.copy(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), os); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("copied to output, bytes=" + count); + } + } + connection.connect(); + responseCode = connection.getResponseCode(); + // If Connected to PAP then break from the loop and continue + // with the Request + if (connection.getResponseCode() > 0 || junit) { + connected = true; + break; + } else { + LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : " + connection.getResponseCode()); + rotatePAPList(); + } + } catch (Exception e) { + // This means that the PAP is not working + if (junit) { + connected = true; + break; + } + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "PAP connection Error : " + e); + rotatePAPList(); + } + papsCount++; + } + if (connected) { + // Read the Response + LOGGER.debug("connected to the PAP : " + getPAP()); + LOGGER.debug("--- Response: ---"); + Map<String, List<String>> headers = connection.getHeaderFields(); + for (String key : headers.keySet()) { + LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); + } + try { + if(responseCode==202){ + StdPDPPolicy policy = (StdPDPPolicy) new ObjectInputStream(connection.getInputStream()).readObject(); + return policy; + } + } catch (IOException | ClassNotFoundException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + throw new PolicyException( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Decoding the result ", e); + } + return null; + } else { + return null; + } + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java new file mode 100644 index 000000000..4476b388b --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java @@ -0,0 +1,398 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.MalformedURLException; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonReader; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.commons.io.IOUtils; +import org.openecomp.policy.api.PolicyConfigStatus; +import org.openecomp.policy.api.PolicyDecision; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PolicyResponseStatus; +import org.openecomp.policy.api.PolicyType; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.XACMLPdpServlet; +import org.openecomp.policy.pdp.rest.api.models.PDPResponse; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.std.Matches; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.w3c.dom.Document; + +import com.att.research.xacml.api.Advice; +import com.att.research.xacml.api.AttributeAssignment; +import com.att.research.xacml.api.Decision; +import com.att.research.xacml.api.Obligation; +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.Response; +import com.att.research.xacml.api.Result; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.std.json.JSONRequest; +import com.att.research.xacml.std.json.JSONResponse; +import com.att.research.xacml.util.XACMLProperties; + +public class PDPServices { + private static Logger LOGGER = FlexLogger.getLogger(PDPServices.class.getName()); + // Change the default Priority value here. + private static final int DEFAULT_PRIORITY = 9999; + private boolean unique = false; + private Boolean decide = false; + private Matches match = null; + + public Collection<PDPResponse> generateRequest(String jsonString, UUID requestID, boolean unique, boolean decide) throws PolicyException{ + this.unique = unique; + this.decide = decide; + Collection<PDPResponse> results = null; + Response response = null; + // Create Request. We need XACML API here. + try { + Request request = JSONRequest.load(jsonString); + // Call the PDP + LOGGER.debug("--- Generating Request: ---\n" + JSONRequest.toString(request)); + response = callPDP(request, requestID); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e); + PDPResponse pdpResponse = new PDPResponse(); + results = new HashSet<PDPResponse>(); + pdpResponse.setPolicyConfigMessage("Unable to Call PDP. Error with the URL"); + pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); + pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED); + results.add(pdpResponse); + throw new PolicyException(e); + } + if (response != null) { + results = checkResponse(response); + } else { + LOGGER.debug("No Response Received from PDP"); + PDPResponse pdpResponse = new PDPResponse(); + results = new HashSet<PDPResponse>(); + pdpResponse.setPolicyConfigMessage("No Response Received"); + pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); + pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED); + results.add(pdpResponse); + } + return results; + } + + private Collection<PDPResponse> checkResponse(Response response) throws PolicyException{ + String pdpConfigLocation = null; + Collection<PDPResponse> combinedResult = new HashSet<PDPResponse>(); + int priority = DEFAULT_PRIORITY; + Map<Integer, PDPResponse> uniqueResult = new HashMap<Integer, PDPResponse>(); + for (Result result : response.getResults()) { + if (!result.getDecision().equals(Decision.PERMIT)) { + LOGGER.debug("Decision not a Permit. " + result.getDecision().toString()); + PDPResponse pdpResponse = new PDPResponse(); + if (decide) { + pdpResponse.setDecision(PolicyDecision.DENY); + for(Advice advice: result.getAssociatedAdvice()){ + for(AttributeAssignment attribute: advice.getAttributeAssignments()){ + pdpResponse.setDetails(attribute.getAttributeValue().getValue().toString()); + break; + } + } + combinedResult.add(pdpResponse); + return combinedResult; + } + pdpResponse.setStatus(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Params passed: Decision not a Permit.",PolicyResponseStatus.NO_ACTION_REQUIRED,PolicyConfigStatus.CONFIG_NOT_FOUND); + combinedResult.add(pdpResponse); + return combinedResult; + } else { + if (decide) { + // check for Decision for decision based calls. + PDPResponse pdpResponse = new PDPResponse(); + pdpResponse.setDecision(PolicyDecision.PERMIT); + pdpResponse.setDetails("Decision Permit. OK!"); + combinedResult.add(pdpResponse); + return combinedResult; + } + if (!result.getAssociatedAdvice().isEmpty()) { + // Configurations should be in advice. + // Also PDP took actions could be here. + for (Advice advice : result.getAssociatedAdvice()) { + int config = 0, uri = 0; + String configURL = null; + String policyName = null; + String policyVersion = null; + match = new Matches(); + Map<String, String> matchingConditions = new HashMap<String, String>(); + Map<String, String> configAttributes = new HashMap<String, String>(); + Map<String, String> responseAttributes = new HashMap<String,String>(); + Map<String, String> actionTaken = new HashMap<String, String>(); + PDPResponse pdpResponse = new PDPResponse(); + Map<String, String> adviseAttributes = new HashMap<String, String>(); + for (AttributeAssignment attribute : advice.getAttributeAssignments()) { + adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); + if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("CONFIGURATION")) { + config++; + } else if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) { + uri++; + if (uri == 1) { + configURL = attribute.getAttributeValue().getValue().toString(); + pdpConfigLocation = configURL.replace("$URL", XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)); + } else { + if (!(attribute.getIssuer().equalsIgnoreCase("PDP"))) { + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error having multiple URI in the Policy"); + } + } + } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("PolicyName")) { + policyName = attribute.getAttributeValue().getValue().toString(); + } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("VersionNumber")) { + policyVersion = attribute.getAttributeValue().getValue().toString(); + } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("Priority")){ + try{ + priority = Integer.parseInt(attribute.getAttributeValue().getValue().toString()); + } catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Unable to Parse Integer for Priority. Setting to default value"); + priority = DEFAULT_PRIORITY; + } + } else if (attribute.getAttributeId().stringValue().startsWith("matching")) { + matchingConditions.put(attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", ""),attribute.getAttributeValue().getValue().toString()); + if (attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", "").equals("ECOMPName")) { + match.setEcompName(attribute.getAttributeValue().getValue().toString()); + } else if (attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", "").equals("ConfigName")) { + match.setConfigName(attribute.getAttributeValue().getValue().toString()); + } else { + configAttributes.put(attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", ""),attribute.getAttributeValue().getValue().toString()); + } + } else if (attribute.getAttributeId().stringValue().startsWith("key:")) { + responseAttributes.put(attribute.getAttributeId().stringValue().replaceFirst("(key).", ""), + attribute.getAttributeValue().getValue().toString()); + } else if (attribute.getAttributeId().stringValue().startsWith("controller:")) { + responseAttributes.put("$"+ attribute.getAttributeId().stringValue(), + attribute.getAttributeValue().getValue().toString()); + } else if (attribute.getAttributeId().stringValue().startsWith("dependencies:")) { + responseAttributes.put("$dependency$", + attribute.getAttributeValue().getValue().toString()); + } + } + if (!configAttributes.isEmpty()) { + match.setConfigAttributes(configAttributes); + } + if ((config == 1) && (uri == 1)) { + // If there is a configuration. + try { + LOGGER.debug("Configuration Call to : " + configURL); + pdpResponse = configCall(pdpConfigLocation); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ e); + pdpResponse.setStatus("Error in Calling the Configuration URL "+ e, + PolicyResponseStatus.NO_ACTION_REQUIRED, + PolicyConfigStatus.CONFIG_NOT_FOUND); + } + pdpResponse.setPolicyName(policyName); + pdpResponse.setPolicyVersion(policyVersion); + pdpResponse.setMatchingConditions(matchingConditions); + pdpResponse.setResponseAttributes(responseAttributes); + if(!unique){ + combinedResult.add(pdpResponse); + }else{ + if(!uniqueResult.isEmpty()){ + if(uniqueResult.containsKey(priority)){ + // Not any more unique, check the matching conditions size + int oldSize = uniqueResult.get(priority).getMatchingConditions().size(); + int newSize = matchingConditions.size(); + if(oldSize < newSize){ + uniqueResult.put(priority, pdpResponse); + }else if(oldSize == newSize){ + pdpResponse = new PDPResponse(); + pdpResponse.setStatus("Two/more Policies have Same Priority and matching conditions, Please correct your policies.", + PolicyResponseStatus.NO_ACTION_REQUIRED, + PolicyConfigStatus.CONFIG_NOT_FOUND); + combinedResult.add(pdpResponse); + unique = false; + return combinedResult; + } + }else{ + uniqueResult.put(priority, pdpResponse); + } + }else{ + uniqueResult.put(priority, pdpResponse); + } + } + } else { + // Else it is Action Taken. + LOGGER.info("Action Taken by PDP. "); + actionTaken.putAll(adviseAttributes); + pdpResponse.setActionTaken(actionTaken); + pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.ACTION_TAKEN); + pdpResponse.setPolicyResponseMessage("Action Taken by the PDP"); + combinedResult.add(pdpResponse); + } + } + } + if (!result.getObligations().isEmpty()) { + // Obligation actions + // Action advised should be in obligations. + for (Obligation obligation : result.getObligations()) { + Map<String, String> actionAdvised = new HashMap<String, String>(); + PDPResponse pdpResponse = new PDPResponse(); + for (AttributeAssignment attribute : obligation.getAttributeAssignments()) { + actionAdvised.put(attribute.getAttributeId().stringValue(), + attribute.getAttributeValue().getValue().toString()); + } + pdpResponse.setActionAdvised(actionAdvised); + pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.ACTION_ADVISED); + pdpResponse.setPolicyResponseMessage("Action has been Advised "); + combinedResult.add(pdpResponse); + } + } + } + } + if(unique){ + // Select Unique policy. + int minNum = DEFAULT_PRIORITY; + for(int num: uniqueResult.keySet()){ + if(num < minNum){ + minNum = num; + } + } + combinedResult.add(uniqueResult.get(minNum)); + // Turn off Unique + unique = false; + } + + return combinedResult; + } + + private PDPResponse configCall(String pdpConfigLocation) throws Exception{ + PDPResponse pdpResponse = new PDPResponse(); + if(pdpConfigLocation.contains("/")){ + pdpConfigLocation = pdpConfigLocation.replace("/", File.separator); + } + try { + InputStream inputStream = new FileInputStream(new File(pdpConfigLocation)); + try { + if (pdpConfigLocation.endsWith("json")) { + pdpResponse.setType(PolicyType.JSON); + 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 Exception(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<String, String>(); + 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 e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + throw new Exception(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Cannot open a connection to the configURL", e); + } + } catch (MalformedURLException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in ConfigURL", e); + } + } + + private Response callPDP(Request request, + UUID requestID) throws Exception{ + Response response = null; + // Get the PDPEngine + if (requestID == null) { + requestID = UUID.randomUUID(); + LOGGER.debug("No request ID provided, sending generated ID: " + requestID.toString()); + } else { + LOGGER.debug("Using provided request ID: " + requestID.toString()); + } + PDPEngine pdpEngine = XACMLPdpServlet.getPDPEngine(); + if (pdpEngine == null) { + String message = "PDPEngine not loaded."; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message); + return response; + } + // call the PDPEngine to decide and give the response on the Request. + try { + response = pdpEngine.decide(request); + LOGGER.debug("Response from the PDP is: \n" + JSONResponse.toString(response)); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + return null; + } + return response; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java new file mode 100644 index 000000000..38a0da32e --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java @@ -0,0 +1,186 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.UUID; + +import org.openecomp.policy.api.ImportParameters; +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.ImportParameters.IMPORT_TYPE; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.utils.PolicyUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; +import org.springframework.web.multipart.MultipartFile; + +public class PolicyEngineImportService { + private static Logger LOGGER = FlexLogger.getLogger(PolicyEngineImportService.class.getName()); + + private String importResponse = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private String message = null; + private ImportParameters importParameters = null; + private MultipartFile file = null; + + public PolicyEngineImportService(String importParametersJson, + MultipartFile file, + String requestID) { + try { + this.importParameters = PolicyUtils.jsonStringToObject(importParametersJson, ImportParameters.class); + } catch (Exception e) { + importResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + // This needs to stop here in case if there a issue here. Avoiding Null pointer exceptions. + return; + } + this.file = file; + if(importParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.importParameters.setRequestID(requestUUID); + } + try{ + run(); + specialCheck(); + }catch(PolicyException e){ + importResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if(importResponse.contains("BAD REQUEST") || importResponse.contains("PE300")){ + status = HttpStatus.BAD_REQUEST; + }else if(importResponse.contains("PE200")){ + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } + + private void run() throws PolicyException{ + // Check Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyException(message); + } + // Get Result. + try{ + status = HttpStatus.OK; + importResponse = processResult(); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + private String processResult() throws PolicyException{ + String response = null; + InputStream targetStream = null; + String fileName = file.getOriginalFilename(); + switch (importParameters.getServiceType()){ + case MICROSERVICE: + if (fileName.endsWith(".xmi") || fileName.endsWith(".zip")){ + try { + targetStream = new BufferedInputStream(file.getInputStream()); + } catch (IOException e) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in reading in the file provided"; + LOGGER.error(response + e); + return response; + } + }else{ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Type Given. Please use a file of type .xmi or .zip."; + LOGGER.error(response); + return response; + } + break; + case BRMSPARAM: + if (fileName.endsWith(".drl")){ + try { + targetStream = new BufferedInputStream(file.getInputStream()); + } catch (IOException e) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in reading in the file provided"; + LOGGER.error(response + e); + return response; + } + }else{ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Type Given. Please use a file of type .drl"; + LOGGER.error(response); + return response; + } + break; + default: + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect ServiceType Given. "; + LOGGER.error(response); + return response; + } + String[] parameters = new String[] {"importService=" + importParameters.getServiceType(), "serviceName=" + + importParameters.getServiceName(), "fileName=" + fileName, "version=" + importParameters.getVersion(), "description=" + importParameters.getDescription()}; + PAPServices papServices = new PAPServices(); + response = (String) papServices.callPAP(targetStream, parameters, importParameters.getRequestID(), "importMS"); + return response; + } + + private boolean getValidation() { + if(importParameters==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + " no Import Parameters given. "; + return false; + } + if(importParameters.getServiceName()==null || importParameters.getServiceName().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing service name value."; + return false; + } + if(importParameters.getServiceType()==null || importParameters.getServiceType().toString().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing service Type value."; + return false; + } + if(importParameters.getServiceType().equals(IMPORT_TYPE.MICROSERVICE) && (importParameters.getVersion()==null || importParameters.getVersion().trim().isEmpty())){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing version value."; + return false; + } + if(file==null || file.isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing File."; + return false; + } + return true; + } + + public String getResult() { + return importResponse; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java new file mode 100644 index 000000000..ee8683f1f --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java @@ -0,0 +1,261 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.UUID; + +import org.openecomp.policy.api.PolicyException; +import org.openecomp.policy.api.PushPolicyParameters; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; +import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; +import org.springframework.http.HttpStatus; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; + +public class PushPolicyService { + private static Logger LOGGER = FlexLogger.getLogger(PushPolicyService.class.getName()); + + private String pushResult = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private PushPolicyParameters pushPolicyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String pdpGroup = null; + private String policyType = null; + private String filePrefix = null; + private String clientScope = null; + + public PushPolicyService(PushPolicyParameters pushPolicyParameters, + String requestID) { + this.pushPolicyParameters = pushPolicyParameters; + if(pushPolicyParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.pushPolicyParameters.setRequestID(requestUUID); + } + try{ + run(); + specialCheck(); + }catch(PolicyException e){ + pushResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if(pushResult.contains("BAD REQUEST") || pushResult.contains("PE300")){ + status = HttpStatus.BAD_REQUEST; + } + } + + private void run() throws PolicyException{ + // Check Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyException(message); + } + // Process Results. + try{ + status = HttpStatus.OK; + pushResult = processResult(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + private String processResult() throws PolicyException{ + PAPServices papServices = new PAPServices(); + String response = null; + StdPDPPolicy selectedPolicy = papServices.pushPolicy(policyScope, filePrefix, policyName, clientScope, pdpGroup, pushPolicyParameters.getRequestID()); + if(selectedPolicy==null){ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. " + + "This indicates a problem with getting the version from the PAP or the policy does not exist."; + LOGGER.error(response); + return response; + } + /* //String activeVersion = papServices.getActiveVersion(policyScope, filePrefix, policyName, clientScope, pushPolicyParameters.getRequestID()); + LOGGER.debug("The active version of " + policyScope + File.separator + filePrefix + policyName + " is " + activeVersion); + String id = null; + if ("pe100".equalsIgnoreCase(activeVersion)) { + response = XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is 403. PEP is not Authorized for making this Request!! " + + "Contact Administrator for this Scope. "; + LOGGER.error(response); + return response; + } else if ("pe300".equalsIgnoreCase(activeVersion)) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. " + + "This indicates a problem with getting the version from the PAP or the policy does not exist."; + LOGGER.error(response); + return response; + } + if (!activeVersion.equalsIgnoreCase("0")) { + id = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml"; + LOGGER.debug("The policyId is " + id); + } else { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy. " + + "This indicates the policy does not exist, please verify the policy exists."; + LOGGER.error(response); + return response; + } + StdPDPPolicy selectedPolicy = papServices.getGitPath(policyScope, filePrefix, policyName, activeVersion, clientScope, pushPolicyParameters.getRequestID(), id); + */ + try { + LOGGER.debug("StdPDPPolicy object contains: " + selectedPolicy.getId() + ", " + selectedPolicy.getName() + ", " + selectedPolicy.getLocation().toString()); + response = copyPolicy(selectedPolicy, pdpGroup, clientScope, pushPolicyParameters.getRequestID()); + } catch (PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+e.getMessage()); + throw new PolicyException(e); + } + LOGGER.debug("copyPolicy response: " + response); + if(response.contains("successfully")){ + response = (String) papServices.callPAP(selectedPolicy, new String[]{"groupId=" + pdpGroup, "policyId="+selectedPolicy.getId(), "apiflag=addPolicyToGroup", "operation=PUT"}, pushPolicyParameters.getRequestID(), clientScope); + } + LOGGER.debug("Final API response: " + response); + return response; + } + + private String copyPolicy(PDPPolicy policy, String group, String policyType, UUID requestID) throws PAPException { + String response = null; + if (policy == null || group == null) { + throw new PAPException("Null input policy="+policy+" group="+group); + } + try { + StdPAPPolicy location = new StdPAPPolicy(policy.getLocation()); + response = copyFile(policy.getId(), group, location, policyType, requestID); + } catch (Exception e) { + String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + return response; + } + + private String copyFile(String policyId, String group, StdPAPPolicy location, String clientScope, UUID requestID) throws PAPException { + String response = null; + // send the policy file to the PAP Servlet + PAPServices papService = new PAPServices(); + try { + response = (String) papService.callPAP(location, new String[] {"groupId=" + group, "policyId="+policyId, "apiflag=api", "operation=post"}, requestID, clientScope); + } catch (Exception e) { + String message = "Unable to PUT policy '" + policyId + "', e:" + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + return response; + } + + private boolean getValidation() { + // While Validating, extract the required values. + if (pushPolicyParameters.getPolicyName() != null + && pushPolicyParameters.getPolicyName().contains(".")) { + policyName = pushPolicyParameters.getPolicyName().substring(pushPolicyParameters.getPolicyName().lastIndexOf(".") + 1, + pushPolicyParameters.getPolicyName().length()); + policyScope = pushPolicyParameters.getPolicyName().substring(0,pushPolicyParameters.getPolicyName().lastIndexOf(".")); + LOGGER.info("Name is " + policyName + " scope is " + policyScope); + } else { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + return false; + } + if (policyName==null||policyName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + return false; + } + policyType = pushPolicyParameters.getPolicyType(); + if(policyType== null || policyType.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given."; + return false; + } + + setClientScope(); + if(clientScope==null){ + return false; + } + + pdpGroup = pushPolicyParameters.getPdpGroup(); + if(pdpGroup==null || pdpGroup.trim().isEmpty()){ + pdpGroup = "default"; + } + + LOGGER.debug("clientScope is " + clientScope); + LOGGER.debug("filePrefix is " + filePrefix); + + return true; + } + + private void setClientScope() { + if ("Firewall".equalsIgnoreCase(policyType)) { + clientScope = "ConfigFirewall"; + filePrefix = "Config_FW_"; + } else if ("Action".equalsIgnoreCase(policyType)) { + clientScope = "Action"; + filePrefix = "Action_"; + } else if ("Decision".equalsIgnoreCase(policyType)) { + clientScope = "Decision"; + filePrefix = "Decision_"; + } else if ("Base".equalsIgnoreCase(policyType)) { + clientScope = "Config"; + filePrefix = "Config_"; + } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyType)) { + clientScope = "ConfigClosedLoop"; + filePrefix = "Config_Fault_"; + } else if ("ClosedLoop_PM".equalsIgnoreCase(policyType)) { + clientScope = "ConfigClosedLoop"; + filePrefix = "Config_PM_"; + } else if ("MicroService".equalsIgnoreCase(policyType)) { + clientScope = "ConfigMS"; + filePrefix = "Config_MS_"; + } else if ("BRMS_RAW".equalsIgnoreCase(policyType)) { + clientScope = "ConfigBrmsRaw"; + filePrefix = "Config_BRMS_Raw_"; + } else if ("BRMS_PARAM".equalsIgnoreCase(policyType)) { + clientScope = "ConfigBrmsParam"; + filePrefix = "Config_BRMS_Param_"; + } else { + clientScope = null; + message = XACMLErrorConstants.ERROR_DATA_ISSUE + policyType + + " is not a valid Policy Type."; + } + } + + public String getResult() { + return pushResult; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java new file mode 100644 index 000000000..4659ead5c --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java @@ -0,0 +1,171 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.services; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import org.openecomp.policy.api.EventRequestParameters; +import org.openecomp.policy.api.PolicyEventException; +import org.openecomp.policy.api.PolicyResponse; +import org.openecomp.policy.api.PolicyResponseStatus; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.pdp.rest.api.models.PDPResponse; +import org.openecomp.policy.std.StdPolicyResponse; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class SendEventService { + private static Logger LOGGER = FlexLogger.getLogger(SendEventService.class.getName()); + + private Collection<PolicyResponse> policyResponses = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private EventRequestParameters eventRequestParameters = null; + private String message = null; + + public SendEventService(EventRequestParameters eventRequestParameters, + String requestID) { + this.eventRequestParameters=eventRequestParameters; + if(eventRequestParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.eventRequestParameters.setRequestID(requestUUID); + } + policyResponses = new ArrayList<PolicyResponse>(); + try{ + run(); + }catch(PolicyEventException e){ + StdPolicyResponse policyResponse = new StdPolicyResponse(); + policyResponse.setPolicyResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE+e); + policyResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED); + policyResponses.add(policyResponse); + status = HttpStatus.BAD_REQUEST; + } + } + + private void run() throws PolicyEventException{ + // getValidation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyEventException(message); + } + // Generate Request. + String modelString = getModel().toString(); + LOGGER.debug("Generated JSON Request is: " + modelString); + // Process Result. + try { + PDPServices pdpServices = new PDPServices(); + status = HttpStatus.OK; + policyResponses = eventResult(pdpServices.generateRequest(modelString, eventRequestParameters.getRequestID(),false, false)); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyEventException(XACMLErrorConstants.ERROR_DATA_ISSUE +e); + } + } + + private Collection<PolicyResponse> eventResult( + Collection<PDPResponse> generateRequest) { + Collection<PolicyResponse> result = new HashSet<PolicyResponse>(); + if (generateRequest == null) { + return null; + } + if (!generateRequest.isEmpty()) { + for (PDPResponse stdStatus : generateRequest) { + StdPolicyResponse policyResponse = new StdPolicyResponse(); + policyResponse.setActionAdvised(stdStatus.getActionAdvised()); + policyResponse.setActionTaken(stdStatus.getActionTaken()); + policyResponse.setPolicyResponseMessage(stdStatus.getPolicyResponseMessage()); + policyResponse.setPolicyResponseStatus(stdStatus.getPolicyResponseStatus()); + policyResponse.setRequestAttributes(eventRequestParameters.getEventAttributes()); + result.add(policyResponse); + } + } + return result; + } + + private JsonObject getModel() throws PolicyEventException{ + JsonArrayBuilder resourceArray = Json.createArrayBuilder(); + Map<String,String> eventAttributes = eventRequestParameters.getEventAttributes(); + for (String key : eventAttributes.keySet()) { + if (key.isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; + LOGGER.error(message); + throw new PolicyEventException(message); + } + JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); + if (eventAttributes.get(key).matches("[0-9]+")) { + int val = Integer.parseInt(eventAttributes.get(key)); + resourceBuilder.add("Value", val); + } else { + resourceBuilder.add("Value", eventAttributes.get(key)); + } + resourceBuilder.add("AttributeId", key); + resourceArray.add(resourceBuilder); + } + JsonObject model = Json + .createObjectBuilder() + .add("Request", Json.createObjectBuilder() + .add("Resource",Json.createObjectBuilder() + .add("Attribute",resourceArray))) + .build(); + return model; + } + + private boolean getValidation() { + if (eventRequestParameters == null) { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Parameters Given. "; + return false; + } + if (eventRequestParameters.getEventAttributes() == null || eventRequestParameters.getEventAttributes().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Attributes Given. "; + return false; + } + return true; + } + + public Collection<PolicyResponse> getResult() { + return policyResponses; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/utils/PolicyApiUtils.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/utils/PolicyApiUtils.java new file mode 100644 index 000000000..984cc907b --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/utils/PolicyApiUtils.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.api.utils; + +import java.io.StringReader; + +import javax.json.Json; +import javax.json.JsonException; +import javax.json.JsonObject; +import javax.json.JsonReader; +import javax.json.stream.JsonParsingException; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import com.google.common.base.CharMatcher; + +public class PolicyApiUtils { + private static Logger LOGGER = FlexLogger.getLogger(PolicyApiUtils.class + .getName()); + + public static Boolean validateNONASCIICharactersAndAllowSpaces( + String jsonString) { + Boolean isValidForm = false; + if (jsonString.isEmpty()) { + LOGGER.error("The Value is empty."); + return false; + } else { + if (CharMatcher.ASCII.matchesAllOf((CharSequence) jsonString)) { + LOGGER.info("The Value does not contain ASCII Characters"); + isValidForm = true; + } else { + LOGGER.error("The Value Contains Non ASCII Characters"); + isValidForm = false; + } + } + return isValidForm; + } + + public static boolean isNumeric(String str) { + for (char c : str.toCharArray()) { + if (!Character.isDigit(c)) + return false; + } + return true; + } + + public static JsonObject stringToJsonObject(String value) + throws JsonException, JsonParsingException, IllegalStateException { + JsonReader jsonReader = Json.createReader(new StringReader(value)); + JsonObject object = jsonReader.readObject(); + jsonReader.close(); + return object; + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java new file mode 100644 index 000000000..ed98e5420 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java @@ -0,0 +1,184 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.config; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.StringTokenizer; + +import org.openecomp.policy.api.PolicyEngineException; +import org.openecomp.policy.common.logging.eelf.MessageCodes; +import org.openecomp.policy.common.logging.eelf.PolicyLogger; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.utils.AAFPolicyClient; +import org.openecomp.policy.utils.AAFPolicyException; +import org.openecomp.policy.utils.PolicyUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import com.att.research.xacml.util.XACMLProperties; + +public class PDPApiAuth { + private static String environment = null; + private static Path clientPath = null; + private static Map<String,ArrayList<String>> clientMap = null; + private static Long oldModified = null; + private static AAFPolicyClient aafClient = null; + + /* + * Set Property by reading the properties File. + */ + public static void setProperty() { + environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); + String clientFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PEP_IDFILE); + if(clientFile!=null){ + clientPath = Paths.get(clientFile); + } + try { + aafClient = AAFPolicyClient.getInstance(XACMLProperties.getProperties()); + } catch (AAFPolicyException | IOException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AAF Client Not instantiated properly."); + } + } + + /* + * Return Environment value of the PDP servlet. + */ + public static String getEnvironment() { + if(environment==null){ + setProperty(); + } + return environment; + } + + /* + * Security check for authentication and authorizations. + */ + public static boolean checkPermissions(String clientEncoding, String requestID, + String resource) { + try{ + String[] userNamePass = PolicyUtils.decodeBasicEncoding(clientEncoding); + if(userNamePass==null){ + String usernameAndPassword = null; + byte[] decodedBytes = Base64.getDecoder().decode(clientEncoding); + usernameAndPassword = new String(decodedBytes, "UTF-8"); + StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); + String username = tokenizer.nextToken(); + String password = tokenizer.nextToken(); + userNamePass= new String[]{username, password}; + } + PolicyLogger.info("User " + userNamePass[0] + " is Accessing Policy Engine API."); + Boolean result = false; + // Check Backward Compatibility. + try{ + result = clientAuth(userNamePass); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, e, ""); + } + if(!result){ + try{ + String aafPolicyNameSpace = XACMLProperties.getProperty("policy.aaf.namespace"); + String aafResource = XACMLProperties.getProperty("policy.aaf.resource"); + if(!userNamePass[0].contains("@") && aafPolicyNameSpace!= null){ + userNamePass[0] = userNamePass[0] + "@" + aafPolicyNameSpace; + } + if(aafResource != null){ + resource = aafResource + resource; + } + PolicyLogger.info("Contacting AAF in : " + environment); + result = aafClient.checkAuthPerm(userNamePass[0], userNamePass[1], resource, environment, ".*"); + }catch (NullPointerException e){ + result = false; + } + } + return result; + }catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, e, ""); + return false; + } + } + + private static Boolean clientAuth(String[] userNamePass) throws Exception{ + if(clientPath==null){ + setProperty(); + } + if (Files.notExists(clientPath)) { + return false; + }else if(clientPath.toString().endsWith(".properties")) { + try { + readProps(clientPath); + if (clientMap.containsKey(userNamePass[0]) && clientMap.get(userNamePass[0]).get(0).equals(userNamePass[1])) { + return true; + } + }catch(PolicyEngineException e){ + return false; + } + } + return false; + } + + private static Map<String, ArrayList<String>> readProps(Path clientPath) throws PolicyEngineException{ + if(oldModified!=null){ + Long newModified = clientPath.toFile().lastModified(); + if (newModified == oldModified) { + return clientMap; + } + } + InputStream in; + Properties clientProp = new Properties(); + try { + in = new FileInputStream(clientPath.toFile()); + clientProp.load(in); + } catch (IOException e) { + PolicyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Load the Properties file", e); + } + // Read the Properties and Load the Clients and their scopes. + clientMap = new HashMap<String, ArrayList<String>>(); + // + for (Object propKey : clientProp.keySet()) { + String clientID = (String)propKey; + String clientValue = clientProp.getProperty(clientID); + if (clientValue != null) { + if (clientValue.contains(",")) { + ArrayList<String> clientValues = new ArrayList<String>(Arrays.asList(clientValue.split("\\s*,\\s*"))); + if(clientValues.get(0)!=null || clientValues.get(1)!=null || clientValues.get(0).isEmpty() || clientValues.get(1).isEmpty()){ + clientMap.put(clientID, clientValues); + } + } + } + } + if (clientMap == null || clientMap.isEmpty()) { + PolicyLogger.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "No Clients ID , Client Key and Scopes are available. Cannot serve any Clients !!"); + throw new PolicyEngineException("Empty Client file"); + } + oldModified = clientPath.toFile().lastModified(); + return clientMap; + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestConfig.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestConfig.java new file mode 100644 index 000000000..6686673d3 --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestConfig.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.config; + +import javax.servlet.MultipartConfigElement; + +import org.openecomp.policy.common.logging.eelf.PolicyLogger; +import org.openecomp.policy.pdp.rest.api.controller.PolicyEngineServices; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Configuration +@EnableWebMvc +@EnableSwagger2 +@ComponentScan(basePackageClasses = PolicyEngineServices.class) +public class PDPRestConfig extends WebMvcConfigurerAdapter{ + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); + } + + private ApiInfo apiInfo(){ + return new ApiInfoBuilder() + .title("Policy Engine REST API") + .description("This API helps to make queries against Policy Engine") + .version("3.0") + .build(); + } + + @Bean + public Docket policyAPI(){ + PolicyLogger.info("Setting up Swagger... "); + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("org.openecomp.policy.pdp.rest.api")) + .paths(PathSelectors.any()) + .build() + .apiInfo(apiInfo()); + } + + @Bean + public MultipartConfigElement multipartConfigElement(){ + String location = System.getProperty("java.io.tmpdir"); + MultipartConfigElement mp = new MultipartConfigElement(location); + return mp; + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestInitializer.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestInitializer.java new file mode 100644 index 000000000..e6acc61bd --- /dev/null +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestInitializer.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.policy.pdp.rest.config; + +import javax.servlet.MultipartConfigElement; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.openecomp.policy.common.logging.eelf.PolicyLogger; +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +/** + * PDP REST API configuration initialization. + * + * @version 0.1 + */ +public class PDPRestInitializer implements WebApplicationInitializer { + @Override + public void onStartup(ServletContext container) throws ServletException { + PolicyLogger.info("PDP-REST Application Initialization Started... "); + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + ctx.register(PDPRestConfig.class); + ctx.setServletContext(container); + ctx.refresh(); + ServletRegistration.Dynamic servlet = container.addServlet( + "dispatcher", new DispatcherServlet(ctx)); + servlet.setLoadOnStartup(1); + servlet.addMapping("/api/*"); + servlet.setMultipartConfig(ctx.getBean(MultipartConfigElement.class)); + } +} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPIPFinderFactory.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPIPFinderFactory.java index 3c8b67f31..6de84d174 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPIPFinderFactory.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPIPFinderFactory.java @@ -36,7 +36,7 @@ import com.att.research.xacml.util.XACMLProperties; public class XACMLPdpPIPFinderFactory extends PIPFinderFactory { private ConfigurableEngineFinder pipFinder; - private static Log logger = LogFactory.getLog(XACMLPdpPIPFinderFactory.class); + private static Log LOGGER = LogFactory.getLog(XACMLPdpPIPFinderFactory.class); public XACMLPdpPIPFinderFactory() { } @@ -49,15 +49,15 @@ public class XACMLPdpPIPFinderFactory extends PIPFinderFactory { if (pipFinder == null) { synchronized(this) { if (pipFinder == null) { - if (logger.isDebugEnabled()) { - logger.debug("Creating default configurable engine finder"); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Creating default configurable engine finder"); } pipFinder = new ConfigurableEngineFinder(); Properties xacmlProperties = null; try { xacmlProperties = XACMLProperties.getProperties(); } catch (Exception ex) { - logger.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR+ "Exception getting XACML properties: " + ex.getMessage(), ex); + LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR+ "Exception getting XACML properties: " + ex.getMessage(), ex); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, ex, "Exception getting XACML properties"); return null; } @@ -75,8 +75,8 @@ public class XACMLPdpPIPFinderFactory extends PIPFinderFactory { if (pipFinder == null) { synchronized(this) { if (pipFinder == null) { - if (logger.isDebugEnabled()) { - logger.debug("Creating configurable engine finder using: " + properties); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Creating configurable engine finder using: " + properties); } pipFinder = new ConfigurableEngineFinder(); ((ConfigurableEngineFinder)pipFinder).configure(properties); diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPolicyFinderFactory.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPolicyFinderFactory.java index 9335bef6c..0e06b3b8b 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPolicyFinderFactory.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPolicyFinderFactory.java @@ -50,7 +50,7 @@ public class XACMLPdpPolicyFinderFactory extends PolicyFinderFactory { public static final String PROP_FILE = ".file"; public static final String PROP_URL = ".url"; - private static Log logger = LogFactory.getLog(XACMLPdpPolicyFinderFactory.class); + private static Log LOGGER = LogFactory.getLog(XACMLPdpPolicyFinderFactory.class); private List<PolicyDef> rootPolicies; private List<PolicyDef> referencedPolicies; private boolean needsInit = true; @@ -95,18 +95,18 @@ public class XACMLPdpPolicyFinderFactory extends PolicyFinderFactory { if (propLocation != null) { File fileLocation = new File(propLocation); if (!fileLocation.exists()) { - XACMLPdpPolicyFinderFactory.logger.error("Policy file " + fileLocation.getAbsolutePath() + " does not exist."); + XACMLPdpPolicyFinderFactory.LOGGER.error("Policy file " + fileLocation.getAbsolutePath() + " does not exist."); } else if (!fileLocation.canRead()) { - XACMLPdpPolicyFinderFactory.logger.error("Policy file " + fileLocation.getAbsolutePath() + " cannot be read."); + XACMLPdpPolicyFinderFactory.LOGGER.error("Policy file " + fileLocation.getAbsolutePath() + " cannot be read."); } else { try { - XACMLPdpPolicyFinderFactory.logger.info("Loading policy file " + fileLocation); + XACMLPdpPolicyFinderFactory.LOGGER.info("Loading policy file " + fileLocation); PolicyDef policyDef = DOMPolicyDef.load(fileLocation); if (policyDef != null) { return policyDef; } } catch (DOMStructureException ex) { - XACMLPdpPolicyFinderFactory.logger.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error loading policy file " + fileLocation.getAbsolutePath() + ": " + ex.getMessage(), ex); + XACMLPdpPolicyFinderFactory.LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error loading policy file " + fileLocation.getAbsolutePath() + ": " + ex.getMessage(), ex); return new Policy(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, ex.getMessage()); } } @@ -121,31 +121,31 @@ public class XACMLPdpPolicyFinderFactory extends PolicyFinderFactory { try { URL url = new URL(propLocation); URLConnection urlConnection = url.openConnection(); - XACMLPdpPolicyFinderFactory.logger.info("Loading policy file " + url.toString()); + XACMLPdpPolicyFinderFactory.LOGGER.info("Loading policy file " + url.toString()); is = urlConnection.getInputStream(); PolicyDef policyDef = DOMPolicyDef.load(is); if (policyDef != null) { return policyDef; } } catch (MalformedURLException ex) { - XACMLPdpPolicyFinderFactory.logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Invalid URL " + propLocation + ": " + ex.getMessage(), ex); + XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Invalid URL " + propLocation + ": " + ex.getMessage(), ex); } catch (IOException ex) { - XACMLPdpPolicyFinderFactory.logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "IOException opening URL " + propLocation + ": " + ex.getMessage(), ex); + XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "IOException opening URL " + propLocation + ": " + ex.getMessage(), ex); } catch (DOMStructureException ex) { - XACMLPdpPolicyFinderFactory.logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Invalid Policy " + propLocation + ": " + ex.getMessage(), ex); + XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Invalid Policy " + propLocation + ": " + ex.getMessage(), ex); return new Policy(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, ex.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { - XACMLPdpPolicyFinderFactory.logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception closing InputStream for GET of url " + propLocation + " : " + e.getMessage() + " (May be memory leak)", e); + XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception closing InputStream for GET of url " + propLocation + " : " + e.getMessage() + " (May be memory leak)", e); } } } } - XACMLPdpPolicyFinderFactory.logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"No known location for Policy " + policyId); + XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"No known location for Policy " + policyId); return null; } @@ -179,14 +179,14 @@ public class XACMLPdpPolicyFinderFactory extends PolicyFinderFactory { protected synchronized void init() { if (this.needsInit) { - if (XACMLPdpPolicyFinderFactory.logger.isDebugEnabled()) { - XACMLPdpPolicyFinderFactory.logger.debug("Initializing"); + if (XACMLPdpPolicyFinderFactory.LOGGER.isDebugEnabled()) { + XACMLPdpPolicyFinderFactory.LOGGER.debug("Initializing"); } this.rootPolicies = this.getPolicyDefs(XACMLProperties.PROP_ROOTPOLICIES); this.referencedPolicies = this.getPolicyDefs(XACMLProperties.PROP_REFERENCEDPOLICIES); - if (XACMLPdpPolicyFinderFactory.logger.isDebugEnabled()) { - XACMLPdpPolicyFinderFactory.logger.debug("Root Policies: " + this.rootPolicies); - XACMLPdpPolicyFinderFactory.logger.debug("Referenced Policies: " + this.referencedPolicies); + if (XACMLPdpPolicyFinderFactory.LOGGER.isDebugEnabled()) { + XACMLPdpPolicyFinderFactory.LOGGER.debug("Root Policies: " + this.rootPolicies); + XACMLPdpPolicyFinderFactory.LOGGER.debug("Referenced Policies: " + this.referencedPolicies); } this.needsInit = false; } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMBeanListener.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMBeanListener.java index 309bd1502..e956cd363 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMBeanListener.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMBeanListener.java @@ -28,10 +28,8 @@ import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.common.logging.flexlogger.*; - +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; import org.openecomp.policy.xacml.api.XACMLErrorConstants; /** * @@ -41,44 +39,44 @@ import org.openecomp.policy.xacml.api.XACMLErrorConstants; @WebListener public class PdpRestMBeanListener implements ServletContextListener { private static final String JMX_OBJECT_NAME = "PdpRest:type=PdpRestMonitor"; - private static final Logger logger = FlexLogger.getLogger(PdpRestMBeanListener.class); + private static final Logger LOGGER = FlexLogger.getLogger(PdpRestMBeanListener.class); private ObjectName objectName; @Override public void contextInitialized(ServletContextEvent contextEvent) { - if (logger.isInfoEnabled()) - logger.info("Registering."); + if (LOGGER.isInfoEnabled()) + LOGGER.info("Registering."); final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { objectName = new ObjectName(JMX_OBJECT_NAME); server.registerMBean(PdpRestMonitor.singleton, objectName); - logger.info("MBean registered: " + objectName); + LOGGER.info("MBean registered: " + objectName); } catch (Exception e) { - logger.warn(e.getMessage(), e); + LOGGER.warn(e.getMessage(), e); - logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to Register " +e.getMessage(), e); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to Register " +e.getMessage(), e); } } // mark @Override public void contextDestroyed(ServletContextEvent contextEvent) { - if (logger.isInfoEnabled()) - logger.info("Unregistering"); + if (LOGGER.isInfoEnabled()) + LOGGER.info("Unregistering"); final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { objectName = new ObjectName(JMX_OBJECT_NAME); server.unregisterMBean(objectName); - if (logger.isInfoEnabled()) - logger.info("MBean unregistered: " + objectName); + if (LOGGER.isInfoEnabled()) + LOGGER.info("MBean unregistered: " + objectName); } catch (Exception e) { - logger.warn(e.getMessage(), e); + LOGGER.warn(e.getMessage(), e); - logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to Destroy Context" +e.getMessage(), e); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to Destroy Context" +e.getMessage(), e); } } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMonitor.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMonitor.java index 93dfbe6a0..e814e7408 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMonitor.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMonitor.java @@ -22,11 +22,7 @@ package org.openecomp.policy.pdp.rest.jmx; import java.util.HashMap; import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BinaryOperator; import org.openecomp.policy.xacml.util.MetricsUtil.AvgLatency; import org.openecomp.policy.xacml.util.MetricsUtil.MaxLatency; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java index 6b8857273..5f62be3ac 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java @@ -24,28 +24,36 @@ import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; +import java.util.ArrayList; import java.util.LinkedList; +import java.util.List; import java.util.UUID; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.utils.BusConsumer; +import org.openecomp.policy.utils.BusPublisher; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; import com.att.nsa.cambria.client.CambriaClientFactory; import com.att.nsa.cambria.client.CambriaConsumer; import com.att.nsa.cambria.client.CambriaPublisher; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; import com.att.research.xacml.util.XACMLProperties; -import org.openecomp.policy.common.logging.flexlogger.*; - public class ManualNotificationUpdateThread implements Runnable { - private static final Logger logger = FlexLogger.getLogger(ManualNotificationUpdateThread.class); -// private static List<String> uebURLList = null; + + private static final Logger LOGGER = FlexLogger.getLogger(ManualNotificationUpdateThread.class); + private static String topic = null; private static CambriaConsumer CConsumer = null; -// private static Collection<String> clusterList = null; private static String clusterList = null; -// private Collection<String> urlList = null; private static String update = null; + private static BusConsumer dmaapConsumer = null; + private static List<String> dmaapList = null; + private static String propNotificationType = null; + private static String aafLogin = null; + private static String aafPassword = null; public volatile boolean isRunning = false; @@ -67,77 +75,145 @@ public class ManualNotificationUpdateThread implements Runnable { synchronized(this) { this.isRunning = true; } + URL aURL = null; String group = UUID.randomUUID ().toString (); String id = "0"; String returnTopic = null; - try { - ManualNotificationUpdateThread.clusterList = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_UEB_CLUSTER); - String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID); - aURL = new URL(url); - topic = aURL.getHost() + aURL.getPort(); - } catch (NumberFormatException e) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get UEB cluster list or pdp url: ", e); - this.isRunning = false; - } catch (MalformedURLException e) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing URL to create topic for Notification ", e); - } - String consumerTopic = aURL.getHost() + aURL.getPort() + "UpdateRequest"; - SendMessage(consumerTopic, "Starting-Topic"); - final LinkedList<String> urlList = new LinkedList<String> (); - for ( String u : clusterList.split ( "," ) ){ - urlList.add ( u ); - } - - try { - CConsumer = CambriaClientFactory.createConsumer ( null, urlList, consumerTopic , group, id, 20*1000, 1000 ); - } catch (MalformedURLException | GeneralSecurityException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - - while (this.isRunning()) { - logger.debug("While loop test _ take out "); + propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE); + if ("ueb".equals(propNotificationType)){ + try { + clusterList = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS).trim(); + String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID); + aURL = new URL(url); + topic = aURL.getHost() + aURL.getPort(); + } catch (NumberFormatException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get UEB cluster list or pdp url: ", e); + this.isRunning = false; + } catch (MalformedURLException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing URL to create topic for Notification ", e); + } + + String consumerTopic = aURL.getHost() + aURL.getPort() + "UpdateRequest"; + SendMessage(consumerTopic, "Starting-Topic"); + final LinkedList<String> urlList = new LinkedList<String> (); + for ( String u : clusterList.split ( "," ) ){ + urlList.add ( u ); + } + try { - for ( String msg : CConsumer.fetch () ){ - logger.debug("Manual Notification Recieved Message " + msg + " from UEB cluster : "); - returnTopic = processMessage(msg); - if(returnTopic != null){ - SendMessage(returnTopic, update); + CConsumer = CambriaClientFactory.createConsumer ( null, urlList, consumerTopic , group, id, 20*1000, 1000 ); + } catch (MalformedURLException | GeneralSecurityException e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create UEB Consumer: ", e1); + } + + while (this.isRunning()) { + LOGGER.debug("While loop test _ take out "); + try { + for ( String msg : CConsumer.fetch () ){ + LOGGER.debug("Manual Notification Recieved Message " + msg + " from UEB cluster : "); + returnTopic = processMessage(msg); + if(returnTopic != null){ + SendMessage(returnTopic, update); + } } + } catch (IOException e) { + LOGGER.debug(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing UEB message"); } - } catch (IOException e) { - logger.debug(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing UEB message"); } - } - logger.debug("Stopping UEB Consuer loop will not logger fetch messages from the cluser"); + LOGGER.debug("Stopping UEB Consumer loop will no longer fetch messages from the cluster"); + } else if ("dmaap".equals(propNotificationType)) { + String dmaapServers = null; + try { + dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); + topic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC); + aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN"); + aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD"); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get DMaaP servers list:", e); + this.isRunning = false; + } + + if(dmaapServers==null || topic==null){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + dmaapServers.trim(); + topic.trim(); + aafLogin.trim(); + aafPassword.trim(); + + String consumerTopic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC).trim(); + SendMessage(consumerTopic, "Starting-Topic"); + dmaapList = new ArrayList<String>(); + for ( String u : dmaapServers.split ( "," ) ){ + dmaapList.add ( u ); + } + + try { + + dmaapConsumer = new BusConsumer.DmaapConsumerWrapper(dmaapList, consumerTopic, aafLogin, aafPassword, group, id, 20*1000, 1000); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create DMaaP Consumer: ", e1); + } + while (this.isRunning()) { + LOGGER.debug("While loop test _ take out "); + try { + for ( String msg : dmaapConsumer.fetch () ){ + LOGGER.debug("Manual Notification Recieved Message " + msg + " from DMaaP server : "); + returnTopic = processMessage(msg); + if(returnTopic != null){ + SendMessage(returnTopic, update); + } + } + }catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing DMaaP message: ", e); } + } + LOGGER.debug("Stopping DMaaP Consumer loop will no longer fetch messages from the servers"); } + } private void SendMessage( String topic, String message) { CambriaPublisher pub = null; + BusPublisher publisher = null; try { - pub = CambriaClientFactory.createSimplePublisher (null, clusterList, topic ); - } catch (MalformedURLException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } catch (GeneralSecurityException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); + if ("ueb".equals(propNotificationType)) { + pub = CambriaClientFactory.createSimplePublisher (null, clusterList, topic ); + pub.send( "pdpReturnMessage", message ); + LOGGER.debug("Sending Message to UEB topic: " + topic); + pub.close(); + + } else if ("dmaap".equals(propNotificationType)){ + publisher = new BusPublisher.DmaapPublisherWrapper(dmaapList,topic,aafLogin,aafPassword); + publisher.send( "pdpReturnMessage", message ); + LOGGER.debug("Sending to Message to DMaaP topic: " + topic); + publisher.close(); + } + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ "Error sending notification update: ", e); } + try { pub.send( "pdpReturnMessage", message ); - logger.debug("Sending to Message to tpoic" + topic); + LOGGER.debug("Sending to Message to tpoic" + topic); } catch (IOException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ "Error sending notification update"); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ "Error sending notification update"); } pub.close(); } private String processMessage(String msg) { - logger.debug("notification message: " + msg); + LOGGER.debug("notification message: " + msg); String[] UID = msg.split("=")[1].split("\""); + String returnTopic = topic + UID[0]; if(msg.contains("Starting-Topic")){ return null; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Notification.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Notification.java index 5ab165b0a..c9b510ec3 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Notification.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Notification.java @@ -22,16 +22,19 @@ package org.openecomp.policy.pdp.rest.notifications; import java.util.Collection; +import org.openecomp.policy.api.NotificationType; + /** * Notification is the POJO which will be used to send the Notifications to the Server. * Notification must contain the Removal and Updated policies. * - * @version 0.1 + * @version 0.2 * */ public class Notification { private Collection<Removed> removedPolicies = null; private Collection<Updated> loadedPolicies = null; + private NotificationType notificationType= null; public Collection<Removed> getRemovedPolicies() { return removedPolicies; @@ -49,4 +52,11 @@ public class Notification { this.loadedPolicies = loadedPolicies; } + public NotificationType getNotificationType() { + return notificationType; + } + + public void setNotificationType(NotificationType notificationType){ + this.notificationType= notificationType; + } } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationController.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationController.java index 1dfd07422..14d7aa165 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationController.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationController.java @@ -39,12 +39,15 @@ import java.util.Iterator; import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; -import org.openecomp.policy.pdp.rest.PapUrlResolver; -import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.api.NotificationType; +import org.openecomp.policy.api.RemovedPolicy; +import org.openecomp.policy.api.UpdateType; import org.openecomp.policy.common.logging.flexlogger.FlexLogger; import org.openecomp.policy.common.logging.flexlogger.Logger; - +import org.openecomp.policy.pdp.rest.PapUrlResolver; +import org.openecomp.policy.rest.XACMLRestProperties; import org.openecomp.policy.xacml.api.XACMLErrorConstants; + import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.api.pap.PDPStatus; import com.att.research.xacml.util.XACMLProperties; @@ -64,7 +67,7 @@ import com.fasterxml.jackson.databind.ObjectWriter; * */ public class NotificationController { - private static final Logger logger = FlexLogger.getLogger(NotificationController.class); + private static final Logger LOGGER = FlexLogger.getLogger(NotificationController.class); private static Notification record = new Notification(); private PDPStatus oldStatus = null; private Removed removed = null; @@ -89,14 +92,14 @@ public class NotificationController { oldStatus = newStatus; } // Debugging purpose only. - logger.debug("old config Status :" + oldStatus.getStatus()); - logger.debug("new config Status :" + newStatus.getStatus()); + LOGGER.debug("old config Status :" + oldStatus.getStatus()); + LOGGER.debug("new config Status :" + newStatus.getStatus()); // Depending on the above condition taking the Change as an Update. if (oldStatus.getStatus().toString() != newStatus.getStatus().toString()) { - logger.info("There is an Update to the PDP"); - logger.debug(oldStatus.getLoadedPolicies()); - logger.debug(newStatus.getLoadedPolicies()); + LOGGER.info("There is an Update to the PDP"); + LOGGER.debug(oldStatus.getLoadedPolicies()); + LOGGER.debug(newStatus.getLoadedPolicies()); // Check if there is an Update/additions in the policy. for (PDPPolicy newPolicy : newStatus.getLoadedPolicies()) { boolean change = true; @@ -143,15 +146,16 @@ public class NotificationController { // Call the Notification Server.. notification.setRemovedPolicies(removedPolicies); notification.setLoadedPolicies(updatedPolicies); + notification = setUpdateTypes(updated, removed, notification); ObjectWriter om = new ObjectMapper().writer(); try { notificationJSON = om.writeValueAsString(notification); - logger.info(notificationJSON); + LOGGER.info(notificationJSON); // NotificationServer Method here. propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE); pdpURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID); - if (propNotificationType!=null && propNotificationType.equals("ueb") && !manualThreadStarted) { - logger.debug("Starting Thread to accept UEB notfications."); + if (("ueb".equals(propNotificationType)||"dmaap".equals(propNotificationType)) && !manualThreadStarted) { + LOGGER.debug("Starting Thread to accept UEB or DMAAP notfications."); this.registerMaunualNotificationRunnable = new ManualNotificationUpdateThread(); this.manualNotificationThread = new Thread(this.registerMaunualNotificationRunnable); this.manualNotificationThread.start(); @@ -162,15 +166,15 @@ public class NotificationController { try{ notificationJSON= record(notification); }catch(Exception e){ - logger.error(e); - // TODO:EELF Cleanup - Remove logger + LOGGER.error(e); + // TODO:EELF Cleanup - Remove LOGGER //PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, ""); } NotificationServer.setUpdate(notificationJSON); ManualNotificationUpdateThread.setUpdate(notificationJSON); } catch (JsonProcessingException e) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); - // TODO:EELF Cleanup - Remove logger + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); + // TODO:EELF Cleanup - Remove LOGGER //PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, ""); } } @@ -178,7 +182,12 @@ public class NotificationController { public static void sendNotification(){ if(notificationFlag){ - NotificationServer.sendNotification(notificationJSON, propNotificationType, pdpURL); + try { + NotificationServer.sendNotification(notificationJSON, propNotificationType, pdpURL); + } catch (Exception e) { + LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage()); + e.printStackTrace(); + } notificationFlag = false; } } @@ -186,9 +195,9 @@ public class NotificationController { private void sendremove(PDPPolicy oldPolicy) { removed = new Removed(); // Want to know what is removed ? - // logger.info("The Policy removed is: " + oldPolicy.getId()); - // logger.info("The version no. is: " + oldPolicy.getVersion()); - logger.info("Policy removed: " + oldPolicy.getId()+ " with version number: " + oldPolicy.getVersion()); + // LOGGER.info("The Policy removed is: " + oldPolicy.getId()); + // LOGGER.info("The version no. is: " + oldPolicy.getVersion()); + LOGGER.info("Policy removed: " + oldPolicy.getId()+ " with version number: " + oldPolicy.getVersion()); removed.setPolicyName(oldPolicy.getId()); removed.setVersionNo(oldPolicy.getVersion()); removeFile(oldPolicy); @@ -197,12 +206,13 @@ public class NotificationController { private void sendUpdate(PDPPolicy newPolicy,HashMap<String, PolicyDef> policyContainer) { updated = new Updated(); // Want to know what is new ? - logger.info("The new Policy is: " + newPolicy.getId()); - logger.info("The version no. is: " + newPolicy.getVersion()); + LOGGER.info("The new Policy is: " + newPolicy.getId()); + LOGGER.info("The version no. is: " + newPolicy.getVersion()); updated.setPolicyName(newPolicy.getId()); updated.setVersionNo(newPolicy.getVersion()); + updated.setUpdateType(UpdateType.NEW); // If the policy is of Config type then retrieve its matches. - if (newPolicy.getName().startsWith("Config")) { + if (newPolicy.getName().contains(".Config_")) { // Take a Configuration copy to PDP webapps. final String urlStart = "attributeId=URLID,expression"; final String urlEnd = "}}},{"; @@ -223,19 +233,19 @@ public class NotificationController { HashMap<String, String> matchValues = new HashMap<String, String>(); while (matches.hasNext()) { Match match = matches.next(); - logger.info("Attribute Value is: "+ match.getAttributeValue().getValue().toString()); + LOGGER.info("Attribute Value is: "+ match.getAttributeValue().getValue().toString()); String[] result = match.getAttributeRetrievalBase().toString().split("attributeId="); result[1] = result[1].replaceAll("}", ""); if (!result[1].equals("urn:oasis:names:tc:xacml:1.0:subject:subject-id")) { - logger.info("Attribute id is: " + result[1]); + LOGGER.info("Attribute id is: " + result[1]); } matchValues.put(result[1], match.getAttributeValue().getValue().toString()); - logger.info("Match is : "+ result[1]+ " , " + match.getAttributeValue().getValue().toString()); + LOGGER.info("Match is : "+ result[1]+ " , " + match.getAttributeValue().getValue().toString()); } updated.setMatches(matchValues); } } - }else if(newPolicy.getName().startsWith("Action")){ + }else if(newPolicy.getName().contains(".Action_")){ // Take Configuration copy to PDP Webapps. // Action policies have .json as extension. String urlString = "$URL/Action/" + newPolicy.getId().substring(0, newPolicy.getId().lastIndexOf(".")) + ".json"; @@ -244,7 +254,7 @@ public class NotificationController { } // Adding this for Recording the changes to serve Polling requests.. - public static String record(Notification notification) throws Exception { + private static String record(Notification notification) throws Exception { // Initialization with updates. if (record.getRemovedPolicies() == null || record.getLoadedPolicies() == null) { record.setRemovedPolicies(notification.getRemovedPolicies()); @@ -317,14 +327,44 @@ public class NotificationController { try { json = om.writeValueAsString(record); } catch (JsonProcessingException e) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); - // TODO:EELF Cleanup - Remove logger + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); + // TODO:EELF Cleanup - Remove LOGGER //PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, ""); } - logger.info(json); + LOGGER.info(json); return json; } + private static Notification setUpdateTypes(boolean updated, boolean removed, Notification notification) { + if(notification!=null){ + if(updated && removed){ + notification.setNotificationType(NotificationType.BOTH); + if(notification.getLoadedPolicies()!=null){ + HashSet<Updated> updatedPolicies = new HashSet<Updated>(); + for(Updated oldUpdatedPolicy: notification.getLoadedPolicies()){ + Updated updatePolicy = oldUpdatedPolicy; + if(notification.getRemovedPolicies()!=null){ + for(RemovedPolicy removedPolicy: notification.getRemovedPolicies()){ + String regex = ".(\\d)*.xml"; + if(removedPolicy.getPolicyName().replaceAll(regex, "").equals(oldUpdatedPolicy.getPolicyName().replaceAll(regex, ""))){ + updatePolicy.setUpdateType(UpdateType.UPDATE); + break; + } + } + } + updatedPolicies.add(updatePolicy); + } + notification.setLoadedPolicies(updatedPolicies); + } + }else if(updated){ + notification.setNotificationType(NotificationType.UPDATE); + }else if(removed){ + notification.setNotificationType(NotificationType.REMOVE); + } + } + return notification; + } + private void removeFile(PDPPolicy oldPolicy) { try{ Path removedPolicyFile = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_CONFIG)+File.separator+oldPolicy.getId()); @@ -346,8 +386,8 @@ public class NotificationController { } } }catch(Exception e){ - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Couldn't remove the policy/config file " + oldPolicy.getName()); - // TODO:EELF Cleanup - Remove logger + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Couldn't remove the policy/config file " + oldPolicy.getName()); + // TODO:EELF Cleanup - Remove LOGGER //PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Couldn't remove the policy file " + oldPolicy.getName()); } } @@ -358,7 +398,7 @@ public class NotificationController { try { Files.createDirectories(configLocation); } catch (IOException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"Failed to create config directory: " + configLocation.toAbsolutePath().toString(), e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"Failed to create config directory: " + configLocation.toAbsolutePath().toString(), e); } } PapUrlResolver papUrls = PapUrlResolver.getInstance(); @@ -370,7 +410,7 @@ public class NotificationController { String fileLocation = configLocation.toString() + File.separator + fileName; try { URL papURL = new URL(papAddress); - logger.info("Calling " +papAddress + " for Configuration Copy."); + LOGGER.info("Calling " +papAddress + " for Configuration Copy."); URLConnection urlConnection = papURL.openConnection(); File file= new File(fileLocation); try (InputStream is = urlConnection.getInputStream(); @@ -379,11 +419,11 @@ public class NotificationController { break; } } catch (MalformedURLException e) { - logger.error(e + e.getMessage()); + LOGGER.error(e + e.getMessage()); } catch(FileNotFoundException e){ - logger.error(e + e.getMessage()); + LOGGER.error(e + e.getMessage()); } catch (IOException e) { - logger.error(e + e.getMessage()); + LOGGER.error(e + e.getMessage()); } papUrls.getNext(); } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java index d6cda7491..fe295ebb8 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java @@ -24,8 +24,12 @@ import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; import javax.websocket.OnClose; import javax.websocket.OnError; @@ -34,28 +38,31 @@ import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; -import org.openecomp.policy.rest.XACMLRestProperties; import org.openecomp.policy.common.logging.eelf.MessageCodes; import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import com.att.nsa.cambria.client.CambriaClientFactory; -import com.att.nsa.cambria.client.CambriaPublisher; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.utils.BusPublisher; import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import com.att.research.xacml.util.XACMLProperties; -import org.openecomp.policy.common.logging.flexlogger.*; +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import com.att.nsa.cambria.client.CambriaClientBuilders; +import com.att.research.xacml.util.XACMLProperties; /** * The NotificationServer sends the Server Notifications to the Clients once there is any Event. * WebSockets is being used as a medium for sending Notifications. - * UEB is being used as a medium for sending Notifications. + * UEB is being used as a medium for sending Notifications. + * DMAAP is being used as a medium for sending Notifications. * - * @version 0.1 + * @version 0.2 * **/ @ServerEndpoint(value = "/notifications") public class NotificationServer { - private static final Logger logger = FlexLogger.getLogger(NotificationServer.class); + private static final Logger LOGGER = FlexLogger.getLogger(NotificationServer.class); private static Queue<Session> queue = new ConcurrentLinkedQueue<Session>(); private static String update = null; private static String hosts = null; @@ -63,7 +70,7 @@ public class NotificationServer { @OnOpen public void openConnection(Session session) { - logger.info("Session Connected: " + session.getId()); + LOGGER.info("Session Connected: " + session.getId()); queue.add(session); } @@ -75,7 +82,7 @@ public class NotificationServer { @OnError public void error(Session session, Throwable t) { queue.remove(session); - logger.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Session Error for : " + session.getId() + " Error: " + t.getMessage()); + LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Session Error for : " + session.getId() + " Error: " + t.getMessage()); } @@ -87,16 +94,17 @@ public class NotificationServer { session.getBasicRemote().sendText(update); session.close(); } catch (IOException e) { - logger.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage()); - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending Message update"); + LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage()); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending Message update"); } } } - public static void sendNotification(String notification, String propNotificationType, String pdpURL){ + public static void sendNotification(String notification, String propNotificationType, String pdpURL) throws Exception { - logger.debug("Notification set to " + propNotificationType); + LOGGER.debug("Notification set to " + propNotificationType); if (propNotificationType.equals("ueb")){ + String topic = null; try { aURL = new URL(pdpURL); @@ -104,33 +112,111 @@ public class NotificationServer { } catch (MalformedURLException e1) { pdpURL = pdpURL.replace("/", ""); topic = pdpURL.replace(":", ""); - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in parsing out pdpURL for UEB notfication "); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in parsing out pdpURL for UEB notfication "); PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e1, "Error in parsing out pdpURL for UEB notfication "); } - hosts = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_UEB_CLUSTER); - logger.debug("Creating Publisher for host: " + hosts + " with topic: " + topic); - CambriaPublisher pub = null; + hosts = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); + String apiKey = XACMLProperties.getProperty(XACMLRestProperties.PROP_UEB_API_KEY); + String apiSecret = XACMLProperties.getProperty(XACMLRestProperties.PROP_UEB_API_SECRET); + + LOGGER.debug("Creating Publisher for host: " + hosts + " with topic: " + topic); + CambriaBatchingPublisher pub = null; try { - pub = CambriaClientFactory.createSimplePublisher (null, hosts, topic ); + if(hosts==null || topic==null || apiKey==null || apiSecret==null){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); + } + + hosts.trim(); + topic.trim(); + apiKey.trim(); + apiSecret.trim(); + pub = new CambriaClientBuilders.PublisherBuilder () + .usingHosts ( hosts ) + .onTopic ( topic ) + .authenticatedBy ( apiKey, apiSecret ) + .build () + ; + } catch (MalformedURLException e1) { - // TODO Auto-generated catch block + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error creating the UEB publisher" + e1.getMessage()); e1.printStackTrace(); } catch (GeneralSecurityException e1) { - // TODO Auto-generated catch block + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error creating the UEB publisher" + e1.getMessage()); e1.printStackTrace(); } + try { pub.send( "MyPartitionKey", notification ); } catch (IOException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update"); - } - pub.close(); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update" + e.getMessage()); + } + + // close the publisher. The batching publisher does not send events + // immediately, so you MUST use close to send any remaining messages. + // You provide the amount of time you're willing to wait for the sends + // to succeed before giving up. If any messages are unsent after that time, + // they're returned to your app. You could, for example, persist to disk + // and try again later. + final List stuck = pub.close ( 20, TimeUnit.SECONDS ); + + if ( stuck.size () > 0 ) + { + System.err.println ( stuck.size() + " messages unsent" ); + } + else + { + System.out.println ( "Clean exit; all messages sent: " + notification ); + } + + } else if (propNotificationType.equals("dmaap")) { + + // Setting up the Publisher for DMaaP MR + String dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); + String topic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC); + String aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN"); + String aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD"); + + try { + if(dmaapServers==null || topic==null){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + } + + dmaapServers.trim(); + topic.trim(); + aafLogin.trim(); + aafPassword.trim(); + + List<String> dmaapList = null; + if(dmaapServers.contains(",")) { + dmaapList = new ArrayList<String>(Arrays.asList(dmaapServers.split("\\s*,\\s*"))); + } else { + dmaapList = new ArrayList<String>(); + dmaapList.add(dmaapServers); + } + + BusPublisher publisher = + new BusPublisher.DmaapPublisherWrapper(dmaapList, + topic, + aafLogin, + aafPassword); + + // Sending notification through DMaaP Message Router + publisher.send( "MyPartitionKey", notification); + LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + topic); + publisher.close(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update" + e.getMessage()); + } } + for(Session session: queue) { try { session.getBasicRemote().sendText(notification); } catch (IOException e) { - logger.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage()); + LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage()); } } } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Removed.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Removed.java index 6ba073815..151b40125 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Removed.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Removed.java @@ -20,15 +20,17 @@ package org.openecomp.policy.pdp.rest.notifications; +import org.openecomp.policy.api.RemovedPolicy; + /** * Removal is the POJO for removal updates of the Policy. * It must have the Policy removed and its Version number. * - * @version 0.1 + * @version 0.2 * */ -public class Removed { +public class Removed implements RemovedPolicy{ private String policyName = null; private String versionNo = null; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Updated.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Updated.java index 39236bada..f0d9aa38d 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Updated.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Updated.java @@ -22,17 +22,21 @@ package org.openecomp.policy.pdp.rest.notifications; import java.util.HashMap; +import org.openecomp.policy.api.LoadedPolicy; +import org.openecomp.policy.api.UpdateType; + /** * Updated is the POJO which consists of any new or Updated Policy information. * It must hold the Policy Name, version Number, Matches. * - * @version 0.1 + * @version 0.2 * */ -public class Updated { +public class Updated implements LoadedPolicy{ private String policyName = null; private String versionNo = null; private HashMap<String,String> matches = null; + private UpdateType updateType = null; public String getPolicyName() { return policyName; @@ -57,5 +61,14 @@ public class Updated { public void setMatches(HashMap<String,String> matches) { this.matches = matches; } + + @Override + public UpdateType getUpdateType() { + return this.updateType; + } + + public void setUpdateType(UpdateType updateType){ + this.updateType = updateType; + } } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/AuthenticationService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/AuthenticationService.java index c426b6002..5a6258032 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/AuthenticationService.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/AuthenticationService.java @@ -23,11 +23,8 @@ package org.openecomp.policy.pdp.rest.restAuth; import java.util.Base64; import java.util.StringTokenizer; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; import com.att.research.xacml.util.XACMLProperties; import org.openecomp.policy.common.logging.eelf.MessageCodes; @@ -36,7 +33,6 @@ import org.openecomp.policy.common.logging.eelf.PolicyLogger; public class AuthenticationService { private String pdpID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_USERID); private String pdpPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_PASS); - private static final Log logger = LogFactory.getLog(AuthenticationService.class); public boolean authenticate(String authCredentials) { @@ -49,8 +45,6 @@ public class AuthenticationService { byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); usernameAndPassword = new String(decodedBytes, "UTF-8"); } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - // TODO:EELF Cleanup - Remove logger PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); return false; } @@ -58,12 +52,8 @@ public class AuthenticationService { final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); final String username = tokenizer.nextToken(); final String password = tokenizer.nextToken(); - - boolean authenticationStatus = pdpID.equals(username) && pdpPass.equals(password); - return authenticationStatus; + return pdpID.equals(username) && pdpPass.equals(password); }catch (Exception e){ - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - // TODO:EELF Cleanup - Remove logger PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); return false; } diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java index b3b931eaa..4bc14df02 100644 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java +++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java @@ -32,7 +32,7 @@ import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.openecomp.policy.pdp.rest.restAuth.AuthenticationService; +import org.openecomp.policy.pdp.rest.config.PDPApiAuth; /** * Servlet Filter implementation class PDPAuthenticationFilter @@ -41,12 +41,14 @@ import org.openecomp.policy.pdp.rest.restAuth.AuthenticationService; public class PDPAuthenticationFilter implements Filter { public static final String AUTHENTICATION_HEADER = "Authorization"; + public static final String ENVIRONMENT_HEADER = "Environment"; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; + String environment = httpServletRequest.getHeader(ENVIRONMENT_HEADER); String authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); String path = ((HttpServletRequest) request).getRequestURI(); // better injected @@ -55,8 +57,35 @@ public class PDPAuthenticationFilter implements Filter { boolean authenticationStatus = authenticationService.authenticate(authCredentials); if (authenticationStatus) { - filter.doFilter(request, response); - } else if(path.contains("notifications")){ + if (check(path)) { + // New API request. + path = path.substring(path.substring(1).indexOf("/") + 1); + if (environment == null) { + // Allow Old clients. + if(!path.contains("/api/")){ + request.getRequestDispatcher("/api/" + path).forward(request,response); + }else{ + request.getRequestDispatcher(path).forward(request,response); + } + } else if (environment.equalsIgnoreCase(PDPApiAuth.getEnvironment())) { + // Validated new Clients. + if(!path.contains("/api/")){ + request.getRequestDispatcher("/api/" + path).forward(request,response); + }else{ + request.getRequestDispatcher(path).forward(request,response); + } + } else if(response instanceof HttpServletResponse) { + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + } else { + filter.doFilter(request, response); + } + } else if (path.contains("swagger") || path.contains("api-docs") + || path.contains("configuration") || path.contains("count")) { + path = path.substring(path.substring(1).indexOf("/") + 2); + request.getRequestDispatcher("/api/" + path).forward(request,response); + } else if(path.contains("notifications")){ filter.doFilter(request, response); } else { if (response instanceof HttpServletResponse) { @@ -66,13 +95,23 @@ public class PDPAuthenticationFilter implements Filter { } } } + + private boolean check(String path) { + if(path.endsWith("/pdp/")|| path.endsWith("/pdp")|| path.endsWith("/test")){ + return false; + }else{ + return true; + } + } @Override public void destroy() { + // Do nothing. } @Override public void init(FilterConfig arg0) throws ServletException { + // Do nothing. } } diff --git a/ECOMP-PDP-REST/src/main/resources/logback.xml b/ECOMP-PDP-REST/src/main/resources/logback.xml index 6958fa693..9c0e2ebce 100644 --- a/ECOMP-PDP-REST/src/main/resources/logback.xml +++ b/ECOMP-PDP-REST/src/main/resources/logback.xml @@ -44,14 +44,14 @@ <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{ElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> --> - <property name="defaultAuditPattern" value="%X{TransactionBeginTimestamp}|%X{TransactionEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{TransactionElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> + <property name="defaultAuditPattern" value="%X{TransactionBeginTimestamp}|%X{TransactionEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{TransactionElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> <!-- M E T R I C <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> --> - <property name="defaultMetricPattern" value="%X{MetricBeginTimestamp}|%X{MetricEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%p|%X{severity}|%X{serverIpAddress}|%X{MetricElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> + <property name="defaultMetricPattern" value="%X{MetricBeginTimestamp}|%X{MetricEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{targetEntity}|%X{targetServiceName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%p|%X{severity}|%X{serverIpAddress}|%X{MetricElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> |