diff options
author | Krishnajinka <kris.jinka@samsung.com> | 2018-07-25 15:05:28 +0900 |
---|---|---|
committer | Krishnakumar Jinka <kris.jinka@samsung.com> | 2018-07-25 14:56:22 +0000 |
commit | 87ef46b7f3004e78b89c5a5c60d1160b332abbb2 (patch) | |
tree | 28283fd019ced509c95e4260cb3131bcf521b9fe /ONAP-PDP-REST/src | |
parent | 5ad6783ca5a09c0061b661a48210f6d8e22cd7d3 (diff) |
Fix issues reported by sonar
Fix issues related to unused method variables, extract constants,
not nest more than 3 control stmts, use try with res in policy
engine project. Rework for comments
Issue-ID: POLICY-1008
Change-Id: If0953de9e802110df14862707f3b525652cdf112
Signed-off-by: Krishnajinka <kris.jinka@samsung.com>
Diffstat (limited to 'ONAP-PDP-REST/src')
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java | 457 | ||||
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java | 123 |
2 files changed, 282 insertions, 298 deletions
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java index 49400d615..b33c4bd16 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java @@ -3,6 +3,7 @@ * ONAP-PDP-REST * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,240 +47,240 @@ import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.*; public class XACMLPdpRegisterThread implements Runnable { - private static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpRegisterThread.class); - private static final Logger auditLogger = FlexLogger.getLogger("auditLogger"); - private ONAPLoggingContext baseLoggingContext = null; - + private static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpRegisterThread.class); + private static final Logger auditLogger = FlexLogger.getLogger("auditLogger"); + private ONAPLoggingContext baseLoggingContext = null; - public volatile boolean isRunning = false; - - public XACMLPdpRegisterThread(ONAPLoggingContext baseLoggingContext) { - this.baseLoggingContext = baseLoggingContext; - } - public synchronized boolean isRunning() { - return this.isRunning; - } - - public synchronized void terminate() { - this.isRunning = false; - } - - /** - * - * This is our thread that runs on startup to tell the PAP server we are up-and-running. - * - */ - @Override - public void run() { - synchronized(this) { - this.isRunning = true; - } - // get a new logging context for the thread - ONAPLoggingContext loggingContext = new ONAPLoggingContext(baseLoggingContext); - loggingContext.setServiceName("PDP:PAP.register"); - //are we registered with at least one - boolean registered = false; - boolean interrupted = false; - /* - int seconds; - try { - seconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_SLEEP)); - } catch (NumberFormatException e) { - LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR +"REGISTER_SLEEP: ", e); - seconds = 5; - } - if (seconds < 5) { - seconds = 5; - } - int retries; - try { - retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_RETRIES)); - } catch (NumberFormatException e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +" REGISTER_SLEEP: ", e); - retries = -1; - } - */ - PapUrlResolver papUrls = PapUrlResolver.getInstance(); - //while (! registered && ! interrupted && this.isRunning()) { - String tempRootPoliciesProperty = XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); - String tempReferencedPoliciesProperty = XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); - Properties tempPipConfigProperties = new Properties(); - try(InputStream pipFile = Files.newInputStream(XACMLPdpLoader.getPIPConfig())){ - tempPipConfigProperties.load(pipFile); - } catch(Exception e){ - LOGGER.error("Failed to open PIP property file", e); - } - while(papUrls.hasMoreUrls()){ - String papID = papUrls.getUserId(); - String papPass = papUrls.getPass(); - Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); - HttpURLConnection connection = null; - try { - // get a new transaction (request) ID and update the logging context. - // each time through the outer loop is considered a new transaction. - // each time through the inner loop (which handles redirects) is a - // continuation of the same transaction. - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - //PolicyLogger.info("Request Id generated in XACMLPdpRegisterThread under XACML-PDP-REST"); - loggingContext.transactionStarted(); - // - // Get the list of PAP Servlet URLs from the property file - // - //String papUrlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - //String[] papUrls = papUrlList.split(","); - //PapUrlResolver.setPapUrls(papUrls); - URL url = new URL(papUrls.getUrl()); - LOGGER.info("Registering with " + url.toString()); - //PolicyLogger.info("new transaction (request) ID and update to logging context in XACMLPdpRegisterThread"); - boolean finished = false; - while (! finished) { - // - // Open up the connection - // - connection = (HttpURLConnection)url.openConnection(); - // - // Setup our method and headers - // - connection.setRequestMethod("POST"); - connection.setRequestProperty("Authorization", "Basic " + encoding); - connection.setRequestProperty("Accept", "text/x-java-properties"); - connection.setRequestProperty("Content-Type", "text/x-java-properties"); - connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID)); - connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_JMX_PORT)); - connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString()); - connection.setUseCaches(false); - // - // Adding this in. It seems the HttpUrlConnection class does NOT - // properly forward our headers for POST re-direction. It does so - // for a GET re-direction. - // - // So we need to handle this ourselves. - // - connection.setInstanceFollowRedirects(false); - connection.setDoOutput(true); - connection.setDoInput(true); - try { - // - // Send our current policy configuration - // - String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + tempRootPoliciesProperty; - lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + tempReferencedPoliciesProperty + "\n"; - try (InputStream listsInputStream = new ByteArrayInputStream(lists.getBytes()); - OutputStream os = connection.getOutputStream()) { - IOUtils.copy(listsInputStream, os); + public volatile boolean isRunning = false; - // - // Send our current PIP configuration - // - //IOUtils.copy(pipInputStream, os); - tempPipConfigProperties.store(os, ""); - } - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Failed to send property file", e); - } - // - // Do the connect - // - connection.connect(); - if (connection.getResponseCode() == 204) { - LOGGER.info("Success. We are configured correctly."); - loggingContext.transactionEnded(); - PolicyLogger.audit("Success. We are configured correctly."); - papUrls.registered(); - finished = true; - registered = true; - } else if (connection.getResponseCode() == 200) { - LOGGER.info("Success. We have a new configuration."); - loggingContext.transactionEnded(); - PolicyLogger.audit("Success. We have a new configuration."); - papUrls.registered(); - Properties properties = new Properties(); - properties.load(connection.getInputStream()); - LOGGER.info("New properties: " + properties.toString()); - // - // Queue it - // - // The incoming properties does NOT include urls - Properties returnedPolicyProperties = XACMLProperties.getPolicyProperties(properties, false); - tempRootPoliciesProperty = new String(returnedPolicyProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES)); - tempReferencedPoliciesProperty = new String(returnedPolicyProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)); - Properties returnedPipProperties = XACMLProperties.getPipProperties(properties); - Properties threadSafeReturnedPipProperties = new Properties(); - ByteArrayOutputStream threadSafeReturnedPipPropertiesOs = new ByteArrayOutputStream(); - returnedPipProperties.store(threadSafeReturnedPipPropertiesOs, ""); - InputStream threadSafeReturnedPipPropertiesIs = new ByteArrayInputStream(threadSafeReturnedPipPropertiesOs.toByteArray()); - threadSafeReturnedPipProperties.load(threadSafeReturnedPipPropertiesIs); - tempPipConfigProperties = threadSafeReturnedPipProperties; + public XACMLPdpRegisterThread(ONAPLoggingContext baseLoggingContext) { + this.baseLoggingContext = baseLoggingContext; + } - PutRequest req = new PutRequest(returnedPolicyProperties,returnedPipProperties); - XACMLPdpServlet.queue.offer(req); - // - // We are now registered - // - finished = true; - registered=true; - } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { - // - // Re-direction - // - String newLocation = connection.getHeaderField("Location"); - if (newLocation == null || newLocation.isEmpty()) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location"); - loggingContext.transactionEnded(); - auditLogger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location"); - PolicyLogger.audit("Transaction Failed - See Error.log"); - finished = true; - } else { - LOGGER.info("New Location: " + newLocation); - url = new URL(newLocation); - } - } else { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - loggingContext.transactionEnded(); - auditLogger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - PolicyLogger.audit("Transaction Failed - See Error.log"); - finished = true; - papUrls.failed(); - } - } - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - papUrls.failed(); - } finally { - // cleanup the connection - if (connection != null) { - try { - // For some reason trying to get the inputStream from the connection - // throws an exception rather than returning null when the InputStream does not exist. - InputStream is = null; - try { - is = connection.getInputStream(); - } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to get Input Stream: " + e1); - } - if (is != null) { - is.close(); - } + public synchronized boolean isRunning() { + return this.isRunning; + } - } catch (IOException ex) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to close connection: " + ex, ex); - } - connection.disconnect(); - } - } + public synchronized void terminate() { + this.isRunning = false; + } - papUrls.getNext(); - } - synchronized(this) { - this.isRunning = false; - } - LOGGER.info("Thread exiting...(registered=" + registered + ", interrupted=" + interrupted + ", isRunning=" + this.isRunning() + ", retries=" + "0" + ")"); - } + /** + * + * This is our thread that runs on startup to tell the PAP server we are up-and-running. + * + */ + @Override + public void run() { + synchronized(this) { + this.isRunning = true; + } + // get a new logging context for the thread + ONAPLoggingContext loggingContext = new ONAPLoggingContext(baseLoggingContext); + loggingContext.setServiceName("PDP:PAP.register"); + //are we registered with at least one + boolean registered = false; + boolean interrupted = false; + /* + int seconds; + try { + seconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_SLEEP)); + } catch (NumberFormatException e) { + LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR +"REGISTER_SLEEP: ", e); + seconds = 5; + } + if (seconds < 5) { + seconds = 5; + } + int retries; + try { + retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_RETRIES)); + } catch (NumberFormatException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +" REGISTER_SLEEP: ", e); + retries = -1; + } + */ + PapUrlResolver papUrls = PapUrlResolver.getInstance(); + //while (! registered && ! interrupted && this.isRunning()) { + String tempRootPoliciesProperty = XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); + String tempReferencedPoliciesProperty = XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); + Properties tempPipConfigProperties = new Properties(); + try(InputStream pipFile = Files.newInputStream(XACMLPdpLoader.getPIPConfig())){ + tempPipConfigProperties.load(pipFile); + } catch(Exception e){ + LOGGER.error("Failed to open PIP property file", e); + } + while(papUrls.hasMoreUrls()){ + String papID = papUrls.getUserId(); + String papPass = papUrls.getPass(); + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + HttpURLConnection connection = null; + try { + // get a new transaction (request) ID and update the logging context. + // each time through the outer loop is considered a new transaction. + // each time through the inner loop (which handles redirects) is a + // continuation of the same transaction. + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + //PolicyLogger.info("Request Id generated in XACMLPdpRegisterThread under XACML-PDP-REST"); + loggingContext.transactionStarted(); + // + // Get the list of PAP Servlet URLs from the property file + // + //String papUrlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + //String[] papUrls = papUrlList.split(","); + //PapUrlResolver.setPapUrls(papUrls); + URL url = new URL(papUrls.getUrl()); + LOGGER.info("Registering with " + url.toString()); + //PolicyLogger.info("new transaction (request) ID and update to logging context in XACMLPdpRegisterThread"); + boolean finished = false; + while (! finished) { + // + // Open up the connection + // + connection = (HttpURLConnection)url.openConnection(); + // + // Setup our method and headers + // + connection.setRequestMethod("POST"); + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setRequestProperty("Accept", "text/x-java-properties"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID)); + connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_JMX_PORT)); + connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString()); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + try { + // + // Send our current policy configuration + // + String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + tempRootPoliciesProperty; + lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + tempReferencedPoliciesProperty + "\n"; + try (InputStream listsInputStream = new ByteArrayInputStream(lists.getBytes()); + OutputStream os = connection.getOutputStream()) { + IOUtils.copy(listsInputStream, os); + + // + // Send our current PIP configuration + // + //IOUtils.copy(pipInputStream, os); + tempPipConfigProperties.store(os, ""); + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Failed to send property file", e); + } + // + // Do the connect + // + connection.connect(); + if (connection.getResponseCode() == 204) { + LOGGER.info("Success. We are configured correctly."); + loggingContext.transactionEnded(); + PolicyLogger.audit("Success. We are configured correctly."); + papUrls.registered(); + finished = true; + registered = true; + } else if (connection.getResponseCode() == 200) { + LOGGER.info("Success. We have a new configuration."); + loggingContext.transactionEnded(); + PolicyLogger.audit("Success. We have a new configuration."); + papUrls.registered(); + Properties properties = new Properties(); + properties.load(connection.getInputStream()); + LOGGER.info("New properties: " + properties.toString()); + // + // Queue it + // + // The incoming properties does NOT include urls + Properties returnedPolicyProperties = XACMLProperties.getPolicyProperties(properties, false); + tempRootPoliciesProperty = returnedPolicyProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); + tempReferencedPoliciesProperty = returnedPolicyProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); + Properties returnedPipProperties = XACMLProperties.getPipProperties(properties); + Properties threadSafeReturnedPipProperties = new Properties(); + ByteArrayOutputStream threadSafeReturnedPipPropertiesOs = new ByteArrayOutputStream(); + returnedPipProperties.store(threadSafeReturnedPipPropertiesOs, ""); + InputStream threadSafeReturnedPipPropertiesIs = new ByteArrayInputStream(threadSafeReturnedPipPropertiesOs.toByteArray()); + threadSafeReturnedPipProperties.load(threadSafeReturnedPipPropertiesIs); + tempPipConfigProperties = threadSafeReturnedPipProperties; + + PutRequest req = new PutRequest(returnedPolicyProperties,returnedPipProperties); + XACMLPdpServlet.queue.offer(req); + // + // We are now registered + // + finished = true; + registered=true; + } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { + // + // Re-direction + // + String newLocation = connection.getHeaderField("Location"); + if (newLocation == null || newLocation.isEmpty()) { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location"); + loggingContext.transactionEnded(); + auditLogger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location"); + PolicyLogger.audit("Transaction Failed - See Error.log"); + finished = true; + } else { + LOGGER.info("New Location: " + newLocation); + url = new URL(newLocation); + } + } else { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + loggingContext.transactionEnded(); + auditLogger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + PolicyLogger.audit("Transaction Failed - See Error.log"); + finished = true; + papUrls.failed(); + } + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + papUrls.failed(); + } finally { + // cleanup the connection + if (connection != null) { + try { + // For some reason trying to get the inputStream from the connection + // throws an exception rather than returning null when the InputStream does not exist. + InputStream is = null; + try { + is = connection.getInputStream(); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to get Input Stream: " + e1); + } + if (is != null) { + is.close(); + } + + } catch (IOException ex) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to close connection: " + ex, ex); + } + connection.disconnect(); + } + } + + papUrls.getNext(); + } + synchronized(this) { + this.isRunning = false; + } + LOGGER.info("Thread exiting...(registered=" + registered + ", interrupted=" + interrupted + ", isRunning=" + this.isRunning() + ", retries=" + "0" + ")"); + } } diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java index 936e497f4..6dae064a7 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java @@ -341,83 +341,66 @@ public class PDPServices { if(pdpConfigLocation.contains("/")){ pdpConfigLocation = pdpConfigLocation.replace("/", File.separator); } - InputStream inputStream = null; - JsonReader jsonReader = null; - try { - inputStream = new FileInputStream(new File(pdpConfigLocation)); - try { - if (pdpConfigLocation.endsWith("json")) { - pdpResponse.setType(PolicyType.JSON); - jsonReader = Json.createReader(inputStream); + + try(InputStream inputStream = new FileInputStream(new File(pdpConfigLocation))) { + if (pdpConfigLocation.endsWith("json")) { + pdpResponse.setType(PolicyType.JSON); + try(JsonReader jsonReader = Json.createReader(inputStream);) { pdpResponse.setConfig(jsonReader.readObject().toString()); - jsonReader.close(); - } else if (pdpConfigLocation.endsWith("xml")) { - pdpResponse.setType(PolicyType.XML); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - DocumentBuilder db = null; - try { - db = dbf.newDocumentBuilder(); - Document document = db.parse(inputStream); - DOMSource domSource = new DOMSource(document); - StringWriter writer = new StringWriter(); - StreamResult result = new StreamResult(writer); - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer transformer; - transformer = tf.newTransformer(); - transformer.transform(domSource, result); - pdpResponse.setConfig(writer.toString()); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ e); - throw new PDPException(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the XML config", e); - } - } else if (pdpConfigLocation.endsWith("properties")) { - pdpResponse.setType(PolicyType.PROPERTIES); - Properties configProp = new Properties(); - configProp.load(inputStream); - Map<String, String> propVal = new HashMap<>(); - for(String name: configProp.stringPropertyNames()) { - propVal.put(name, configProp.getProperty(name)); - } - pdpResponse.setProperty(propVal); - } else if (pdpConfigLocation.endsWith("txt")) { - pdpResponse.setType(PolicyType.OTHER); - String other = IOUtils.toString(inputStream); - IOUtils.closeQuietly(inputStream); - pdpResponse.setConfig(other); - } else { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config Not Found"); - pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); - pdpResponse.setPolicyConfigMessage("Illegal form of Configuration Type Found."); - inputStream.close(); - return pdpResponse; } - LOGGER.info("config Retrieved " + pdpConfigLocation); - pdpResponse.setStatus("Config Retrieved! ", - PolicyResponseStatus.NO_ACTION_REQUIRED, - PolicyConfigStatus.CONFIG_RETRIEVED); - return pdpResponse; - } catch (IOException | ParserConfigurationException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - throw new PDPException(XACMLErrorConstants.ERROR_PROCESS_FLOW + - "Cannot open a connection to the configURL", e); - } finally { - if(jsonReader != null) { - try { - jsonReader.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the JsonReader"+e); - } + } else if (pdpConfigLocation.endsWith("xml")) { + pdpResponse.setType(PolicyType.XML); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + DocumentBuilder db = null; + try { + db = dbf.newDocumentBuilder(); + Document document = db.parse(inputStream); + DOMSource domSource = new DOMSource(document); + StringWriter writer = new StringWriter(); + StreamResult result = new StreamResult(writer); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer; + transformer = tf.newTransformer(); + transformer.transform(domSource, result); + pdpResponse.setConfig(writer.toString()); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ e); + throw new PDPException(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the XML config", e); } + } else if (pdpConfigLocation.endsWith("properties")) { + pdpResponse.setType(PolicyType.PROPERTIES); + Properties configProp = new Properties(); + configProp.load(inputStream); + Map<String, String> propVal = new HashMap<>(); + for(String name: configProp.stringPropertyNames()) { + propVal.put(name, configProp.getProperty(name)); + } + pdpResponse.setProperty(propVal); + } else if (pdpConfigLocation.endsWith("txt")) { + pdpResponse.setType(PolicyType.OTHER); + String other = IOUtils.toString(inputStream); + IOUtils.closeQuietly(inputStream); + pdpResponse.setConfig(other); + } else { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config Not Found"); + pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); + pdpResponse.setPolicyConfigMessage("Illegal form of Configuration Type Found."); + return pdpResponse; } + LOGGER.info("config Retrieved " + pdpConfigLocation); + pdpResponse.setStatus("Config Retrieved! ", + PolicyResponseStatus.NO_ACTION_REQUIRED, + PolicyConfigStatus.CONFIG_RETRIEVED); + return pdpResponse; } catch (FileNotFoundException e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); throw new PDPException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in ConfigURL", e); - }finally{ - if(inputStream != null){ - inputStream.close(); - } + } catch (IOException | ParserConfigurationException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + throw new PDPException(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Cannot open a connection to the configURL", e); } } |