diff options
Diffstat (limited to 'ONAP-PDP-REST/src')
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java | 204 | ||||
-rw-r--r-- | ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java | 428 |
2 files changed, 310 insertions, 322 deletions
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java index c9ecee86b..a7dc42642 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java @@ -32,98 +32,104 @@ import org.springframework.http.HttpStatus; public class DeletePolicyService { private static final 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 clientScope = null; private String policyType = null; private String policyName = null; private String policyScope = null; - public DeletePolicyService(DeletePolicyParameters deletePolicyParameters, - String requestID) { + public DeletePolicyService(final DeletePolicyParameters deletePolicyParameters, final String requestID) { this.deletePolicyParameters = deletePolicyParameters; - if(deletePolicyParameters.getRequestID()==null){ + if (deletePolicyParameters.getRequestID() == null) { UUID requestUUID = null; if (requestID != null && !requestID.isEmpty()) { try { requestUUID = UUID.fromString(requestID); - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { requestUUID = UUID.randomUUID(); LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); } - }else{ + } else { requestUUID = UUID.randomUUID(); LOGGER.info("Generated Random UUID: " + requestUUID.toString()); } this.deletePolicyParameters.setRequestID(requestUUID); } - try{ + try { run(); specialCheck(); - }catch(PolicyException e){ + } catch (final PolicyException e) { + LOGGER.error("Unable to process delete policy request for : " + this.deletePolicyParameters); 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("PE200")||deleteResult.contains("not exist")||deleteResult.contains("Invalid policyName")) { - if(deleteResult.contains("groupId")) { + if (deleteResult == null) { + return; + } + if (deleteResult.contains("BAD REQUEST") || deleteResult.contains("PE300") || deleteResult.contains("PE200") + || deleteResult.contains("not exist") || deleteResult.contains("Invalid policyName")) { + if (deleteResult.contains("groupId")) { status = HttpStatus.NOT_FOUND; } else { - status = HttpStatus.BAD_REQUEST; + status = HttpStatus.BAD_REQUEST; } - } else if (deleteResult.contains("locked down")){ + } else if (deleteResult.contains("locked down")) { status = HttpStatus.ACCEPTED; } else if (deleteResult.contains("not Authorized")) { status = HttpStatus.FORBIDDEN; - } else if (deleteResult.contains("JPAUtils")||deleteResult.contains("database")||deleteResult.contains("policy file")|| - deleteResult.contains("unknown")||deleteResult.contains("configuration")) { + } 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()){ + private void run() throws PolicyException { + // Check Validation. + if (!getValidation()) { LOGGER.error(message); throw new PolicyException(message); } - // Get Result. - try{ + // Get Result. + try { + LOGGER.debug("Processing delete request: " + deletePolicyParameters.toString()); status = HttpStatus.OK; deleteResult = processResult(); - }catch (Exception e){ + } catch (final Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); status = HttpStatus.BAD_REQUEST; throw new PolicyException(e); } } - private String processResult() throws PolicyException{ + private String processResult() throws PolicyException { String response = null; String fullPolicyName = null; String pdpGroup = deletePolicyParameters.getPdpGroup(); - // PDP Group Check. - if (pdpGroup==null){ - pdpGroup="NA"; + // PDP Group Check. + if (pdpGroup == null) { + pdpGroup = "NA"; } - PAPServices papServices = new PAPServices(); + final 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); + + final 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. "; + 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)) { @@ -132,86 +138,99 @@ public class DeletePolicyService { LOGGER.error(response); return response; } - if (!activeVersion.equalsIgnoreCase("0")) { + if (!"0".equalsIgnoreCase(activeVersion)) { 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."; + 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()){ + if (deletePolicyParameters.getDeleteCondition() == null + || deletePolicyParameters.getDeleteCondition().toString().trim().isEmpty()) { 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); + + final 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()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PDP Group given."; + if (deletePolicyParameters.getPdpGroup() == null || deletePolicyParameters.getPdpGroup().trim().isEmpty()) { + 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); + // send JSON object to PAP + response = + (String) papServices.callPAP( + null, new String[] {"policyName=" + fullPolicyName, "groupId=" + pdpGroup, + "apiflag=deletePdpApi", "operation=delete"}, + deletePolicyParameters.getRequestID(), clientScope); } else { - 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."; + 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()==null||deletePolicyParameters.getPolicyName().trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - return false; - } - 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(); - } - 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 boolean getValidation() { + // While Validating, extract the required values. + if (deletePolicyParameters.getPolicyName() == null || deletePolicyParameters.getPolicyName().trim().isEmpty()) { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + return false; + } + 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(); + } + 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() { @@ -237,9 +256,9 @@ public class DeletePolicyService { clientScope = "ConfigMS"; filePrefix = "Config_MS_"; } else if ("Optimization".equalsIgnoreCase(policyType)) { - clientScope = "ConfigOptimization"; - filePrefix = "Config_OOF_"; - }else if ("BRMS_RAW".equalsIgnoreCase(policyType)) { + clientScope = "ConfigOptimization"; + filePrefix = "Config_OOF_"; + } else if ("BRMS_RAW".equalsIgnoreCase(policyType)) { clientScope = "ConfigBrmsRaw"; filePrefix = "Config_BRMS_Raw_"; } else if ("BRMS_PARAM".equalsIgnoreCase(policyType)) { @@ -247,8 +266,7 @@ public class DeletePolicyService { filePrefix = "Config_BRMS_Param_"; } else { clientScope = null; - message = XACMLErrorConstants.ERROR_DATA_ISSUE + policyType - + " is not a valid Policy Type."; + message = XACMLErrorConstants.ERROR_DATA_ISSUE + policyType + " is not a valid Policy Type."; } } diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java index 3c0ea3894..425bcebf9 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java @@ -49,69 +49,69 @@ 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 static Logger LOGGER = FlexLogger.getLogger(PAPServices.class.getName()); + private int responseCode = 0; private static String environment = "DEVL"; private static Boolean isJunit = false; private static List<String> paps = null; - private static final Object papResourceLock = new Object(); + private static final Object papResourceLock = new Object(); private String operation = null; private String requestMethod = null; private String encoding = null; - public static void setJunit(boolean isJunit) { + public static void setJunit(final boolean isJunit) { PAPServices.isJunit = isJunit; } public PAPServices() { environment = PDPApiAuth.getEnvironment(); - if(paps == null){ + if (paps == null) { synchronized (papResourceLock) { String urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS); - if(urlList == null){ + 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 =CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)); - Base64.Encoder encoder = Base64.getEncoder(); - encoding = encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)); + + private String getPAPEncoding() { + if (encoding == null) { + final String userID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + final String pass = + CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)); + final Base64.Encoder encoder = Base64.getEncoder(); + encoding = encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8)); } return encoding; } - - private void rotatePAPList(){ + + private void rotatePAPList() { synchronized (papResourceLock) { Collections.rotate(paps, -1); } } - - private String getPAP(){ + + private String getPAP() { String result; synchronized (papResourceLock) { result = paps.get(0); } return result; } - - public static void setPaps(List<String> paps) { - PAPServices.paps = paps; - } + + public static void setPaps(final List<String> paps) { + PAPServices.paps = paps; + } public int getResponseCode() { return responseCode; } - public Object callPAP(Object content, String[] parameters, UUID requestID, - String clientScope) throws PolicyException { + public Object callPAP(final Object content, final String[] parameters, UUID requestID, final String clientScope) + throws PolicyException { String response = null; HttpURLConnection connection = null; responseCode = 0; @@ -120,7 +120,7 @@ public class PAPServices { // This makes it Real-Time to change the list depending on their // availability. if (paps == null || paps.isEmpty()) { - String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAPs List is Empty."; + final String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAPs List is Empty."; LOGGER.error(message); throw new PolicyException(message); } @@ -130,14 +130,14 @@ public class PAPServices { try { String fullURL = getPAP(); fullURL = checkParameter(parameters, fullURL); - URL url = new URL(fullURL); - LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---"); + final 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"); + connection.setRequestProperty("Content-Type", "application/json"); // Adding Authorization - connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding()); + connection.setRequestProperty("Authorization", "Basic " + getPAPEncoding()); connection.setRequestProperty("Environment", environment); connection.setRequestProperty("ClientScope", clientScope); // set the method and headers @@ -149,28 +149,24 @@ public class PAPServices { // Adding RequestID if (requestID == null) { requestID = UUID.randomUUID(); - LOGGER.info("No request ID provided, sending generated ID: " - + requestID.toString()); + LOGGER.info("No request ID provided, sending generated ID: " + requestID.toString()); } else { - LOGGER.info("Using provided request ID: " - + requestID.toString()); + LOGGER.info("Using provided request ID: " + requestID.toString()); } - connection.setRequestProperty("X-ECOMP-RequestID", - 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); + final int count = IOUtils.copy((InputStream) content, os); if (LOGGER.isDebugEnabled()) { LOGGER.debug("copied to output, bytes=" + count); } } - } else if(content != null){ + } else if (content != null) { // the content is an object to be encoded in JSON - ObjectMapper mapper = new ObjectMapper(); + final ObjectMapper mapper = new ObjectMapper(); if (!isJunit) { - mapper.writeValue(connection.getOutputStream(), - content); + mapper.writeValue(connection.getOutputStream(), content); } } // DO the connect @@ -182,17 +178,17 @@ public class PAPServices { connected = true; break; } else { - LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : " + connection.getResponseCode()); + LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "PAP Response Code : " + + connection.getResponseCode()); rotatePAPList(); } - } catch (Exception e) { + } catch (final Exception e) { // This means that the PAP is not working if (isJunit) { connected = true; break; } - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "PAP connection Error : " + e); + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e); rotatePAPList(); } papsCount++; @@ -201,42 +197,41 @@ public class PAPServices { // Read the Response LOGGER.debug("connected to the PAP : " + getPAP()); LOGGER.debug("--- Response: ---"); - if(connection != null){ - 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 (isJunit) { - response = SUCCESS; - } - }else{ - response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "connection is null"; + if (connection != null) { + final Map<String, List<String>> headers = connection.getHeaderFields(); + for (final String key : headers.keySet()) { + LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); + } + + try { + response = checkResponse(connection, requestID); + } catch (final 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 (isJunit) { + response = SUCCESS; + } + } else { + response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "connection is null"; } return response; } else { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Unable to get valid response from PAP(s) " + paps; + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get valid response from PAP(s) " + paps; return response; } } - - public String getActiveVersion(String policyScope, String filePrefix, String policyName, String clientScope, UUID requestID) { + + public String getActiveVersion(final String policyScope, final String filePrefix, final String policyName, + final String clientScope, final UUID requestID) { String version = null; HttpURLConnection connection = null; - String [] parameters = {"apiflag=version","policyScope="+policyScope, "filePrefix="+filePrefix, "policyName="+policyName}; + final 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."); - }else { + } else { int papsCount = 0; boolean connected = false; while (papsCount < paps.size()) { @@ -244,30 +239,27 @@ public class PAPServices { String fullURL = getPAP(); if (parameters != null && parameters.length > 0) { String queryString = ""; - for (String p : parameters) { + for (final String p : parameters) { queryString += "&" + p; } fullURL += "?" + queryString.substring(1); } - URL url = new URL (fullURL); + final URL url = new URL(fullURL); - //Open the connection - connection = (HttpURLConnection)url.openConnection(); + // Open the connection + connection = (HttpURLConnection) url.openConnection(); // Setting Content-Type - connection.setRequestProperty("Content-Type", - "application/json"); + connection.setRequestProperty("Content-Type", "application/json"); // Adding Authorization - connection.setRequestProperty("Authorization", "Basic " - + getPAPEncoding()); + connection.setRequestProperty("Authorization", "Basic " + getPAPEncoding()); connection.setRequestProperty("Environment", environment); connection.setRequestProperty("ClientScope", clientScope); - - //set the method and headers + // set the method and headers connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(false); @@ -275,10 +267,10 @@ public class PAPServices { connection.setDoInput(true); connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString()); - //DO the connect + // DO the connect connection.connect(); - // If Connected to PAP then break from the loop and continue with the Request + // If Connected to PAP then break from the loop and continue with the Request if (connection.getResponseCode() > 0) { connected = true; break; @@ -286,8 +278,8 @@ public class PAPServices { } else { LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error"); } - } catch (Exception e) { - // This means that the PAP is not working + } catch (final Exception e) { + // This means that the PAP is not working LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e); rotatePAPList(); } @@ -295,11 +287,11 @@ public class PAPServices { } if (connected) { - //Read the Response + // 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()) { + final Map<String, List<String>> headers = connection.getHeaderFields(); + for (final String key : headers.keySet()) { LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); } try { @@ -308,29 +300,34 @@ public class PAPServices { 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. "); + 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"); + 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."); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "BAD REQUEST: Error occured while getting the version from the PAP. The request may be incorrect. The response code of the URL is '" + + connection.getResponseCode() + "'"); } - } catch (IOException e) { + } catch (final IOException e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - } + } } else { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps); - } + LOGGER.error( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps); + } } return version; } - - private String checkResponse(HttpURLConnection connection, UUID requestID) throws IOException { + + private String checkResponse(final HttpURLConnection connection, final UUID requestID) throws IOException { String response = null; - if (responseCode == 200 || isJunit) { + if (responseCode == 200 || isJunit) { // Check for successful creation of policy String isSuccess = null; if (!isJunit) { // is this a junit test? @@ -341,110 +338,97 @@ public class PAPServices { } 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 - + "\n\nPolicy Safety Checker Warning: This closedLoopControlName " - + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") - + " that already exists." + " See detailed information on ClosedLoop Pairs below: " - +"\n\n"+connection.getHeaderField("safetyChecker"); + response = "Transaction ID: " + requestID + " --Policy with the name " + + connection.getHeaderField("policyName") + " was successfully updated. "; + if (connection.getHeaderField("safetyChecker") != null) { + response = response + "\n\nPolicy Safety Checker Warning: This closedLoopControlName " + + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") + + " that already exists." + " See detailed information on ClosedLoop Pairs below: " + + "\n\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 - + "\n\nPolicy Safety Checker Warning: This closedLoopControlName " - + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") - + " that already exists. " + "See detailed information on ClosedLoop Pairs below: " - +"\n\n"+connection.getHeaderField("safetyChecker"); + response = "Transaction ID: " + requestID + " --Policy with the name " + + connection.getHeaderField("policyName") + " was successfully created."; + if (connection.getHeaderField("safetyChecker") != null) { + response = response + "\n\nPolicy Safety Checker Warning: This closedLoopControlName " + + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") + + " that already exists. " + "See detailed information on ClosedLoop Pairs below: " + + "\n\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."; + 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; + 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); + + // get the json string from the response + final InputStream is = connection.getInputStream(); + + // read the inputStream into a buffer (trick found online scans entire input + // looking for end-of-file) + final java.util.Scanner scanner = new java.util.Scanner(is); scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; + json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); - - } catch (IOException e1) { + + } catch (final IOException e1) { LOGGER.error(e1.getMessage() + e1); } response = "Transaction ID: " + requestID + " --Dictionary Items Retrieved " + json; } else if ("getMetrics".equals(operation)) { - response = "Transaction ID: " + requestID + " --Policy Metrics Retrieved " + connection.getHeaderField("metrics"); + response = "Transaction ID: " + requestID + " --Policy Metrics Retrieved " + + connection.getHeaderField("metrics"); } LOGGER.info(response); } else { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + final 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."; + 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") + "'."; + 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"); + } 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 " + 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 ("UnknownGroup".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + connection.getHeaderField("message") + response = XACMLErrorConstants.ERROR_DATA_ISSUE + connection.getHeaderField("message") + " Please check the pdpGroup you are requesting to push the policy to."; LOGGER.error(response); } else if ("policyNotAvailableForEdit".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + connection.getHeaderField("message"); + response = XACMLErrorConstants.ERROR_DATA_ISSUE + connection.getHeaderField("message"); } - } else if (connection.getResponseCode() == 409 && connection.getHeaderField("error") != null) { + } 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. " + 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. " + 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 @@ -455,8 +439,8 @@ public class PAPServices { + "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."; - } else if("PolicyInPDP".equals(connection.getHeaderField("error"))){ - response = XACMLErrorConstants.ERROR_DATA_ISSUE + } else if ("PolicyInPDP".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Exist Error: The Policy trying to be deleted is active in PDP. " + "Active PDP Polcies are not allowed to be deleted from PAP. " + "Please First remove the policy from PDP in order to successfully delete the Policy from PAP."; @@ -464,14 +448,11 @@ public class PAPServices { 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"; + 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."; + 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"; + 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"))) { @@ -484,40 +465,37 @@ public class PAPServices { 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"; + 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"); + response = XACMLErrorConstants.ERROR_PROCESS_FLOW + connection.getHeaderField("message"); } else if ("addGroupError".equals(connection.getHeaderField("error"))) { response = connection.getHeaderField("message"); - } else if ("validation".equals(connection.getHeaderField("error"))){ - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Validation errors during policy engine " + connection.getHeaderField("operation") + - " for " + connection.getHeaderField("service"); + } else if ("validation".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Validation errors during policy engine " + + connection.getHeaderField("operation") + " for " + connection.getHeaderField("service"); } else if ("error".equals(connection.getHeaderField("error"))) { response = XACMLErrorConstants.ERROR_UNKNOWN + "Could not create or update the policy for and unknown reason"; - }else{ + } else { response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error occured while attempting perform this operation.. " - + "the request may be incorrect or the PAP is unreachable. " - + connection.getHeaderField("error"); + + "the request may be incorrect or the PAP is unreachable. " + + connection.getHeaderField("error"); } LOGGER.error(response); } else { - response = XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "Error occured while attempting perform this operation.. " - + "the request may be incorrect or the PAP is unreachable."; + response = + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error occured while attempting perform this operation.. " + + "the request may be incorrect or the PAP is unreachable."; LOGGER.error(response); } return response; } - private String checkParameter(String[] parameters, String fullURL) { + private String checkParameter(final String[] parameters, String fullURL) { if (parameters != null && parameters.length > 0) { String queryString = ""; - for (String p : parameters) { + for (final String p : parameters) { queryString += "&" + p; if (p.equalsIgnoreCase("operation=post")) { requestMethod = "POST"; @@ -527,18 +505,19 @@ public class PAPServices { } 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"; + } 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"; + } else if (p.equalsIgnoreCase("operation=createDictionary")) { + operation = "createDictionary"; + } + } else if (p.equalsIgnoreCase("importService=MICROSERVICE") + || p.equalsIgnoreCase("importService=BRMSPARAM")) { + requestMethod = "PUT"; } } fullURL += "?" + queryString.substring(1); @@ -546,21 +525,16 @@ public class PAPServices { 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+"\"}"; - - HttpURLConnection connection = null; + public StdPDPPolicy pushPolicy(final String policyScope, final String filePrefix, final String policyName, + final String clientScope, final String pdpGroup, UUID requestID) throws PolicyException { + final String json = "{ " + "\"apiflag\": \"api\"," + "\"policyScope\": \"" + policyScope + "\"," + + "\"filePrefix\": \"" + filePrefix + "\"," + "\"policyName\": \"" + policyName + "\"," + + "\"clientScope\": \"" + clientScope + "\"," + "\"pdpGroup\": \"" + pdpGroup + "\"}"; + + HttpURLConnection connection = null; responseCode = 0; if (paps == null || paps.isEmpty()) { - String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAPs List is Empty."; + final String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAPs List is Empty."; LOGGER.error(message); throw new PolicyException(message); } @@ -568,16 +542,16 @@ public class PAPServices { boolean connected = false; while (papsCount < paps.size()) { try { - String fullURL = getPAP(); - fullURL = (fullURL.endsWith("/"))? fullURL+"onap/pushPolicy" : fullURL+"/onap/pushPolicy"; - URL url = new URL(fullURL); - LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---"); + String fullURL = getPAP(); + fullURL = (fullURL.endsWith("/")) ? fullURL + "onap/pushPolicy" : fullURL + "/onap/pushPolicy"; + final 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"); + connection.setRequestProperty("Content-Type", "application/json"); // Adding Authorization - connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding()); + connection.setRequestProperty("Authorization", "Basic " + getPAPEncoding()); connection.setRequestProperty("Environment", environment); connection.setRequestProperty("ClientScope", clientScope); // set the method and headers @@ -588,17 +562,14 @@ public class PAPServices { // Adding RequestID if (requestID == null) { requestID = UUID.randomUUID(); - LOGGER.info("No request ID provided, sending generated ID: " - + requestID.toString()); + LOGGER.info("No request ID provided, sending generated ID: " + requestID.toString()); } else { - LOGGER.info("Using provided request ID: " - + requestID.toString()); + LOGGER.info("Using provided request ID: " + requestID.toString()); } - connection.setRequestProperty("X-ECOMP-RequestID", - 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); + final int count = IOUtils.copy(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), os); if (LOGGER.isDebugEnabled()) { LOGGER.debug("copied to output, bytes=" + count); } @@ -611,17 +582,17 @@ public class PAPServices { connected = true; break; } else { - LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : " + connection.getResponseCode()); + LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "PAP Response Code : " + + connection.getResponseCode()); rotatePAPList(); } - } catch (Exception e) { + } catch (final Exception e) { // This means that the PAP is not working if (isJunit) { connected = true; break; } - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "PAP connection Error : " + e); + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e); rotatePAPList(); } papsCount++; @@ -630,22 +601,21 @@ public class PAPServices { // Read the Response LOGGER.debug("connected to the PAP : " + getPAP()); LOGGER.debug("--- Response: ---"); - if(connection != null){ - Map<String, List<String>> headers = connection.getHeaderFields(); - for (String key : headers.keySet()) { + if (connection != null) { + final Map<String, List<String>> headers = connection.getHeaderFields(); + for (final 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; + if (responseCode == 202) { + final 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); - } + throw new PolicyException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Decoding the result ", e); + } } return null; } else { |