diff options
author | Michael Mokry <mm117s@att.com> | 2018-02-05 09:48:59 -0600 |
---|---|---|
committer | Michael Mokry <mm117s@att.com> | 2018-02-08 07:45:06 -0600 |
commit | c5d97e8a9a6bea71f3be329a2e44bdbe5fe50882 (patch) | |
tree | 8db57c1406d2479e7624a2778dd5d518e874f59c /ONAP-PAP-REST/src | |
parent | c9039d15e8a84a9304fba40283a332a2a65ef854 (diff) |
MS Model Input Validation
- Provides validation for MS policy input content body that matches the GUI validations when create/update MS policy from API
- Added changes to satisfy review comments and updated copywright
headers for modified and new files
Change-Id: I02bfa639bffb48520badd0e4fa34eb36418547ae
Issue-ID: POLICY-377
Signed-off-by: Michael Mokry <mm117s@att.com>
Diffstat (limited to 'ONAP-PAP-REST/src')
7 files changed, 148 insertions, 108 deletions
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java index d6c298731..b43254e51 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -1016,6 +1016,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList //This would occur if a PolicyDBDao notification was received String policyDBDaoRequestUrl = request.getParameter("policydbdaourl"); if(policyDBDaoRequestUrl != null){ + LOGGER.info("XACMLPapServlet: PolicyDBDao Notification received." ); String policyDBDaoRequestEntityId = request.getParameter("entityid"); String policyDBDaoRequestEntityType = request.getParameter("entitytype"); String policyDBDaoRequestExtraData = request.getParameter("extradata"); @@ -1026,7 +1027,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList im.endTransaction(); return; } - loggingContext.metricStarted(); + loggingContext.metricStarted(); + LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification"); policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification"); @@ -1574,8 +1576,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if(apiflag!=null){ loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy"); + LOGGER.info("PushPolicy Request From The API"); } else { loggingContext.setServiceName("AC:PAP.postPolicy"); + LOGGER.info("PushPolicy Request From The AC"); } String policyId = request.getParameter("policyId"); @@ -1607,27 +1611,28 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } - // Get new transaction to perform updateGroup() - PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction(); - try { + if(apiflag != null){ /* * If request comes from the API we need to run the PolicyDBDao updateGroup() to notify other paps of the change. * The GUI does this from the POLICY-SDK-APP code. */ - if(apiflag != null){ - - // read the inputStream into a buffer + + // Get new transaction to perform updateGroup() + PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction(); + try { + // get the request content into a String and read the inputStream into a buffer java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); scanner.useDelimiter("\\A"); String json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); - LOGGER.info("PushPolicy API request: " + json); // convert Object sent as JSON into local object ObjectMapper mapper = new ObjectMapper(); Object objectFromJSON = mapper.readValue(json, StdPDPPolicy.class); StdPDPPolicy policy = (StdPDPPolicy) objectFromJSON; + LOGGER.info("Request JSON Payload: " + json); + // Assume that this is an update of an existing PDP Group loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup"); try{ @@ -1667,27 +1672,23 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } //delete temporary policy file from the bin directory - if(policy != null) { - Files.deleteIfExists(Paths.get(policy.getId())); - } - + Files.deleteIfExists(Paths.get(policy.getId())); + + } catch (Exception e) { + acPutTransaction.rollbackTransaction(); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception occurred when updating the group from API."; + LOGGER.error(message); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error","addGroupError"); + response.addHeader("message", message); + return; } - } catch (Exception e) { - acPutTransaction.rollbackTransaction(); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception occurred when updating the group from API."; - LOGGER.error(message); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error","addGroupError"); - response.addHeader("message", message); - return; } - - // policy file copied ok and the Group was updated on the PDP response.setStatus(HttpServletResponse.SC_NO_CONTENT); response.addHeader("operation", "push"); @@ -2142,7 +2143,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory()); } try{ - acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut"); + if("delete".equals(((StdPDPGroup)objectFromJSON).getOperation())){ + acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doDelete"); + } else { + acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut"); + } } catch(Exception e){ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: " +"group="+group.getId()); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java index b2fb3e5a8..885e5e888 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -71,6 +71,7 @@ import javax.xml.xpath.XPathFactory; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; +import org.elasticsearch.common.Strings; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -537,7 +538,8 @@ public class PolicyDBDao { // // Open up the connection // - logger.debug("Connecting with url: "+url); + logger.info("PolicyDBDao: NotifyOtherThread: notifying other PAPs of an update"); + logger.info("Connecting with url: "+url); try { connection = (HttpURLConnection)url.openConnection(); } catch (Exception e) { @@ -688,7 +690,7 @@ public class PolicyDBDao { case GROUP_NOTIFICATION: for(int i=0; i<retries;i++){ try{ - handleIncomingGroupChange(url, entityId, extraData, transaction, xacmlPapServlet); + handleIncomingGroupChange(entityId, extraData, transaction, xacmlPapServlet); break; }catch(Exception e){ logger.debug(e); @@ -706,7 +708,7 @@ public class PolicyDBDao { //no changes should be being made in this function, we still need to close transaction.rollbackTransaction(); } - private void handleIncomingGroupChange(String url, String groupId, String extraData,PolicyDBDaoTransaction transaction,XACMLPapServlet xacmlPapServlet) throws PAPException, PolicyDBException{ + private void handleIncomingGroupChange(String groupId, String extraData,PolicyDBDaoTransaction transaction,XACMLPapServlet xacmlPapServlet) throws PAPException, PolicyDBException{ GroupEntity groupRecord = null; long groupIdLong = -1; try{ @@ -895,7 +897,7 @@ public class PolicyDBDao { //convert PolicyEntity object to PDPPolicy String name = pdpPolicyId.replace(".xml", ""); - name = name.substring(0, name.lastIndexOf(".")); + name = name.substring(0, name.lastIndexOf('.')); InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); pdpGroup.copyPolicyToFile(pdpPolicyId,name,policyStream); URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri(); @@ -1077,7 +1079,7 @@ public class PolicyDBDao { try { if(policy != null){ policyName = policy.getPolicyName(); - logger.debug("Deleting Policy: " + policy.getPolicyName()); + logger.info("Deleting old Policy Config File for " + policy.getPolicyName()); action = "delete"; Path subFile = null; @@ -1114,7 +1116,7 @@ public class PolicyDBDao { } private Path getPolicySubFile(String filename, String subFileType){ - logger.debug("getPolicySubFile(" + filename + ", " + subFileType + ")"); + logger.info("getPolicySubFile(" + filename + ", " + subFileType + ")"); Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS).toString(), subFileType); File file = null; @@ -1131,7 +1133,7 @@ public class PolicyDBDao { finalPath = Paths.get(file.getAbsolutePath()); } - logger.debug("end of getPolicySubFile: " + finalPath); + logger.info("end of getPolicySubFile: " + finalPath); return finalPath; } @@ -2370,7 +2372,7 @@ public class PolicyDBDao { @Override public void updateGroup(OnapPDPGroup group, String username){ - logger.debug("updateGroup(PDPGroup group) as updateGroup("+group+","+username+") called"); + logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup("+group+","+username+") called"); if(group == null){ throw new IllegalArgumentException("PDPGroup group must not be null"); } @@ -2397,12 +2399,12 @@ public class PolicyDBDao { PolicyLogger.error("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database"); throw new PersistenceException("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database"); } - GroupEntity groupToUpdate = (GroupEntity)getGroupQueryList.get(0); - if(!stringEquals(groupToUpdate.getModifiedBy(), username)){ - groupToUpdate.setModifiedBy(username); + GroupEntity groupToUpdateInDB = (GroupEntity)getGroupQueryList.get(0); + if(!stringEquals(groupToUpdateInDB.getModifiedBy(), username)){ + groupToUpdateInDB.setModifiedBy(username); } - if(group.getDescription() != null && !stringEquals(group.getDescription(),groupToUpdate.getDescription())){ - groupToUpdate.setDescription(group.getDescription()); + if(group.getDescription() != null && !stringEquals(group.getDescription(),groupToUpdateInDB.getDescription())){ + groupToUpdateInDB.setDescription(group.getDescription()); } //let's find out what policies have been deleted StdPDPGroup oldGroup = null; @@ -2414,7 +2416,6 @@ public class PolicyDBDao { if(oldGroup == null){ PolicyLogger.error("We cannot get the group from the papEngine to delete policies"); } else { - Set<String> newPolicySet = new HashSet<>(group.getPolicies().size()); //a multiple of n runtime is faster than n^2, so I am using a hashset to do the comparison for(PDPPolicy pol: group.getPolicies()){ @@ -2424,19 +2425,45 @@ public class PolicyDBDao { //should be fast since getPolicies uses a HashSet in StdPDPGroup if(!newPolicySet.contains(pol.getId())){ String[] scopeAndName = getNameScopeAndVersionFromPdpPolicy(pol.getId()); - PolicyEntity policyToDelete; + PolicyEntity policyToDelete = null; try{ - policyToDelete = getPolicy(scopeAndName[0],scopeAndName[1]); + if(scopeAndName!=null){ + policyToDelete = getPolicy(scopeAndName[0],scopeAndName[1]); + + if ("XACMLPapServlet.doDelete".equals(username)) { + + Iterator<PolicyEntity> dbPolicyIt = groupToUpdateInDB.getPolicies().iterator(); + String policyName = getPolicyNameAndVersionFromPolicyFileName(policyToDelete.getPolicyName())[0]; + + logger.info("PolicyDBDao: delete policy from GroupEntity"); + try{ + while(dbPolicyIt.hasNext()){ + PolicyEntity dbpolicy = dbPolicyIt.next(); + if(policyToDelete.getScope().equals(dbpolicy.getScope()) && + getPolicyNameAndVersionFromPolicyFileName(dbpolicy.getPolicyName())[0].equals(policyName)) { + dbPolicyIt.remove(); + + logger.info("PolicyDBDao: deleting policy from the existing group:\n " + + "policyName is " + policyToDelete.getScope()+"."+policyToDelete.getPolicyName() + "\n" + + "group is " + groupToUpdateInDB.getGroupId()); + } + } + }catch(Exception e){ + logger.debug(e); + PolicyLogger.error("Could not delete policy with name: "+ policyToDelete.getScope()+"."+policyToDelete.getPolicyName()+"\n ID: "+ policyToDelete.getPolicyId()); + } + } + } + }catch(Exception e){ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not get policy to remove: "+pol.getId()); throw new PersistenceException("Could not get policy to remove: "+pol.getId()); } - groupToUpdate.getPolicies().remove(policyToDelete); - } } } - if(group.getName() != null && !stringEquals(group.getName(),groupToUpdate.getgroupName())){ + + if(group.getName() != null && !stringEquals(group.getName(),groupToUpdateInDB.getgroupName())){ //we need to check if the new id exists in the database String newGroupId = createNewPDPGroupId(group.getName()); Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); @@ -2453,13 +2480,13 @@ public class PolicyDBDao { PolicyLogger.error("The new group name already exists, group id "+newGroupId); throw new PersistenceException("The new group name already exists, group id "+newGroupId); } - groupToUpdate.setGroupId(newGroupId); - groupToUpdate.setGroupName(group.getName()); + groupToUpdateInDB.setGroupId(newGroupId); + groupToUpdateInDB.setGroupName(group.getName()); this.newGroupId = group.getId(); } em.flush(); - this.groupId = groupToUpdate.getGroupKey(); + this.groupId = groupToUpdateInDB.getGroupKey(); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java index 2eca73ea5..ff62080e2 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -856,11 +856,11 @@ public class MicroServiceDictionaryController { this.newModel.setSub_attributes(value); String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); int equalsIndexForAttributes= attributes.indexOf("="); - String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1); + String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1, attributes.length()-1); this.newModel.setAttributes(atttributesAfterFirstEquals); String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); int equalsIndex= refAttributes.indexOf("="); - String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1); + String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1, refAttributes.length()-1); this.newModel.setRef_attributes(refAttributesAfterFirstEquals); this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java index 9091d79ed..59bf50071 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -349,13 +349,13 @@ public class ElkConnectorImpl implements ElkConnector{ if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) - LOGGER.info("OK: PUT operation of " + "->" + ": " + + LOGGER.info("ElkConnector: OK: PUT operation of " + "->" + ": " + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" + System.lineSeparator() + result.getJsonString()); } else { if (LOGGER.isWarnEnabled()) - LOGGER.warn("FAILURE: PUT operation of "+ "->" + ": " + + LOGGER.warn("ElkConnector: FAILURE: PUT operation of "+ "->" + ": " + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" + System.lineSeparator() + result.getJsonString()); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java index 3b254b005..a031ac647 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -78,7 +78,7 @@ public class APIRequestHandler { public void doDelete(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext, String apiflag) throws IOException, SQLException{ DeleteHandler deleteHandler = DeleteHandler.getInstance(); if ("deletePapApi".equalsIgnoreCase(apiflag)) { - deleteHandler.doAPIDeleteFromPAP(request, response, loggingContext); + deleteHandler.doAPIDeleteFromPAP(request, response); return; } else if ("deletePdpApi".equalsIgnoreCase(apiflag)) { deleteHandler.doAPIDeleteFromPDP(request, response, loggingContext); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java index 7f612a57e..85b6e24a1 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -61,15 +61,19 @@ public class DeleteHandler { private OnapPDPGroup newgroup; private static Logger logger = FlexLogger.getLogger(DeleteHandler.class); + public static final String POLICY_IN_PDP = "PolicyInPDP"; + public static final String ERROR = "error"; + public static final String UNKNOWN = "unknown"; - public void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext) throws IOException, SQLException { + + public void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException { // get the request content into a String String json = null; java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); scanner.useDelimiter("\\A"); json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); - PolicyLogger.info("JSON request from API: " + json); + PolicyLogger.info("JSON request from API to Delete Policy from the PAP: " + json); // convert Object sent as JSON into local object StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class); String policyName = policy.getPolicyName(); @@ -79,7 +83,7 @@ public class DeleteHandler { String removeVersionExtension; String splitPolicyName = null; String[] split = null; - String status = "error"; + String status = ERROR; PolicyEntity policyEntity = null; JPAUtils jpaUtils = null; @@ -93,7 +97,7 @@ public class DeleteHandler { jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf()); } catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP"); - response.addHeader("error", "jpautils"); + response.addHeader(ERROR, "jpautils"); response.addHeader("operation", "delete"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; @@ -110,8 +114,8 @@ public class DeleteHandler { try{ if(policyName.endsWith(".xml")){ removeXMLExtension = policyName.replace(".xml", ""); - currentVersion = Integer.parseInt(removeXMLExtension.substring(removeXMLExtension.lastIndexOf(".")+1)); - removeVersionExtension = removeXMLExtension.substring(0, removeXMLExtension.lastIndexOf(".")); + currentVersion = Integer.parseInt(removeXMLExtension.substring(removeXMLExtension.lastIndexOf('.')+1)); + removeVersionExtension = removeXMLExtension.substring(0, removeXMLExtension.lastIndexOf('.')); boolean queryCheck = true; if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){ if(policyName.contains("Config_")){ @@ -125,7 +129,7 @@ public class DeleteHandler { split = splitPolicyName.split(":"); }else{ PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy. Please, provide the valid policyname."); - response.addHeader("error", "unknown"); + response.addHeader(ERROR, UNKNOWN); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); return; } @@ -162,23 +166,23 @@ public class DeleteHandler { con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword); if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){ - boolean groupCheck = checkPolicyGroupEntity(em, con, peResult); + boolean groupCheck = checkPolicyGroupEntity(con, peResult); if(!groupCheck){ for(Object peData : peResult){ policyEntity = (PolicyEntity) peData; status = deletePolicyEntityData(em, policyEntity); } }else{ - status = "PolicyInPDP"; + status = POLICY_IN_PDP; } - if(status.equals("error")){ + if(status.equals(ERROR)){ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database."); - response.addHeader("error", "unknown"); + response.addHeader(ERROR, UNKNOWN); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); return; - }else if(status.equals("PolicyInPDP")){ + }else if(status.equals(POLICY_IN_PDP)){ PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups."); - response.addHeader("error", "PolicyInPDP"); + response.addHeader(ERROR, POLICY_IN_PDP); response.setStatus(HttpServletResponse.SC_CONFLICT); return; }else{ @@ -191,22 +195,22 @@ public class DeleteHandler { } } }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")){ - boolean groupCheck = checkPolicyGroupEntity(em, con, peResult); + boolean groupCheck = checkPolicyGroupEntity(con, peResult); if(!groupCheck){ policyEntity = (PolicyEntity) peResult.get(0); status = deletePolicyEntityData(em, policyEntity); }else{ - status = "PolicyInPDP"; + status = POLICY_IN_PDP; } - if(status.equals("error")){ + if(ERROR.equals(status)){ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database."); - response.addHeader("error", "unknown"); + response.addHeader(ERROR, UNKNOWN); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); return; - }else if(status.equals("PolicyInPDP")){ + }else if(POLICY_IN_PDP.equals(status)){ PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups."); - response.addHeader("error", "unknown"); + response.addHeader(ERROR, POLICY_IN_PDP); response.setStatus(HttpServletResponse.SC_CONFLICT); return; }else{ @@ -215,7 +219,7 @@ public class DeleteHandler { for(Object object : peResult){ policyEntity = (PolicyEntity) object; String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); - int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1)); + int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1)); if(policyEntityVersion > newVersion){ newVersion = policyEntityVersion-1; } @@ -243,7 +247,7 @@ public class DeleteHandler { } }else{ PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); - response.addHeader("error", "unknown"); + response.addHeader(ERROR, UNKNOWN); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); return; } @@ -252,7 +256,7 @@ public class DeleteHandler { }catch(Exception e){ em.getTransaction().rollback(); PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR"); - response.addHeader("error", "deleteDB"); + response.addHeader(ERROR, "deleteDB"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } finally { @@ -269,7 +273,7 @@ public class DeleteHandler { return; } else { PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); - response.addHeader("error", "unknown"); + response.addHeader(ERROR, UNKNOWN); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); return; } @@ -291,37 +295,33 @@ public class DeleteHandler { em.remove(policyEntity); }catch(Exception e){ logger.error(e.getMessage(),e); - return "error"; + return ERROR; } return "success"; } - public static boolean checkPolicyGroupEntity(EntityManager em, Connection con, List<?> peResult) throws SQLException{ + public static boolean checkPolicyGroupEntity(Connection con, List<?> peResult) throws SQLException{ for(Object peData : peResult){ PolicyEntity policyEntity = (PolicyEntity) peData; - Statement st = null; - ResultSet rs = null; - try{ - st = con.createStatement(); - rs = st.executeQuery("Select * from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"); + try(Statement st = con.createStatement(); + ResultSet rs = st.executeQuery("Select * from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'")){ boolean gEntityList = rs.next(); - rs.close(); if(gEntityList){ return true; } - }finally{ - if(st != null){ - st.close(); - } } } return false; } public void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext) throws IOException { + String policyName = request.getParameter("policyName"); String groupId = request.getParameter("groupId"); String responseString = null; + + PolicyLogger.info("JSON request from API to Delete Policy from the PDP: " + policyName); + // for PUT operations the group may or may not need to exist before the operation can be done OnapPDPGroup group = null; try { @@ -330,12 +330,13 @@ public class DeleteHandler { PolicyLogger.error("Exception occured While PUT operation is performing for PDP Group"+e); } if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; + String message = "Unknown groupId '" + groupId + "'."; PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - response.addHeader("error", "UnknownGroup"); - response.sendError(HttpServletResponse.SC_NOT_FOUND, message); + response.addHeader(ERROR, "UnknownGroup"); + response.addHeader("message", message); + response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } else { loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup"); @@ -346,7 +347,7 @@ public class DeleteHandler { + "policyName must be the full name of the file to be deleted including version and extension"; PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... " + "policyName must be the full name of the file to be deleted including version and extension"); - response.addHeader("error", message); + response.addHeader(ERROR, message); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } @@ -359,7 +360,7 @@ public class DeleteHandler { PolicyLogger.debug("Precheck Successful."); } } - + PolicyLogger.info("Preparing to remove policy from group: " + group.getId()); removePolicy.prepareToRemove(policy); OnapPDPGroup updatedGroup = removePolicy.getUpdatedObject(); responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext); @@ -367,7 +368,7 @@ public class DeleteHandler { String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP."; PolicyLogger.error(message); PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP."); - response.addHeader("error", message); + response.addHeader(ERROR, message); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } @@ -384,17 +385,17 @@ public class DeleteHandler { String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input."; PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input."); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "groupUpdate"); + response.addHeader(ERROR, "groupUpdate"); response.addHeader("message", message); return; } else if (responseString.equals("DB Error")) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "deleteDB"); + response.addHeader(ERROR, "deleteDB"); return; } else { PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); - response.addHeader("error", "unknown"); + response.addHeader(ERROR, UNKNOWN); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); return; } @@ -410,7 +411,7 @@ public class DeleteHandler { } catch (PAPException e1) { PolicyLogger.error("Exception occured While Deleting Policy From PDP Group"+e1); } - if (group == null || ! (group instanceof StdPDPGroup) || existingGroup == null || ! (group.getId().equals(existingGroup.getId()))) { + if (!(group instanceof StdPDPGroup) || existingGroup == null || !(group.getId().equals(existingGroup.getId()))) { String existingID = null; if(existingGroup != null){ existingID = existingGroup.getId(); @@ -426,7 +427,7 @@ public class DeleteHandler { // so we need to fill that in before submitting the group for update ((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory()); try{ - acPutTransaction.updateGroup(group, "XACMLPapServlet.doAPIDelete"); + acPutTransaction.updateGroup(group, "XACMLPapServlet.doDelete"); } catch(Exception e){ PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: " +"group="+existingGroup.getId()); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java index 9be4b0342..6606d383b 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -63,11 +63,18 @@ public class SavePolicyHandler { scanner.useDelimiter("\\A"); json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); - PolicyLogger.info("JSON request from API: " + json); + + if(policyAdapter.isEditPolicy()){ + PolicyLogger.info("SavePolicyHandler: JSON request from API to update a policy: " + json); + } else { + PolicyLogger.info("SavePolicyHandler: JSON request from API to create a policy: " + json); + } + // convert Object sent as JSON into local object StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class); //Set policyAdapter values including parentPath (Common to all policy types) try { + PolicyLogger.info("SavePolicyHandler: Setting parameter values to PolicyAdapter"); policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag); if(!extendedPolicyOptions(policyAdapter, response)){ |