From eff265962c081edb751d5d2ed99dc443cb97f3fb Mon Sep 17 00:00:00 2001 From: Krishnajinka Date: Wed, 18 Jul 2018 19:49:30 +0900 Subject: FIX SONAR ISSUE NESTED TRY BLOCKS refactor the code for nested try blocks and rework based on comments and fix nested loops complexity Issue-ID: POLICY-976 Change-Id: Ied02b7838b5e4839a4906f79ff37c4fd6afeccfe Signed-off-by: Krishnajinka --- .../components/CreateNewMicroServiceModel.java | 64 +++-- .../policy/pap/xacml/rest/components/Policy.java | 16 +- .../pap/xacml/rest/components/PolicyDBDao.java | 309 +++++++++++---------- 3 files changed, 200 insertions(+), 189 deletions(-) (limited to 'ONAP-PAP-REST/src/main/java') diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java index d6718ab81..f7f8a335c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java @@ -57,7 +57,7 @@ public class CreateNewMicroServiceModel { private HashMap classMap = new HashMap<>(); - MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); + private MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) { super(); @@ -80,31 +80,8 @@ public class CreateNewMicroServiceModel { File directory = new File("ExtractDir" + File.separator + randomID); List fileList = listModelFiles(directory.toString()); //get all the files from a director - for (File file : fileList){ - if (file.isFile()){ - int i = file.getName().lastIndexOf('.'); - String type = file.getName().substring(i+1); - - if(type != null && "yml".equalsIgnoreCase(type)){ - - processYmlModel(file.toString(), modelName); - - }else{ - - tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI); - classMap.putAll(tempMap); - } - } - } - cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip"; - try { - FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID)); - FileUtils.deleteDirectory(new File(randomID)); - File deleteFile = new File(cleanUpFile); - FileUtils.forceDelete(deleteFile); - } catch (IOException e) { - logger.error("Failed to unzip model file " + randomID, e); - } + processFiles(modelName, fileList); + doCleanUpFiles(randomID); }else { if(importFile.contains(".yml")){ @@ -122,6 +99,39 @@ public class CreateNewMicroServiceModel { } } + private void processFiles(String modelName, List fileList) { + Map tempMap; + for (File file : fileList){ + if (file.isFile()){ + int i = file.getName().lastIndexOf('.'); + String type = file.getName().substring(i+1); + + if("yml".equalsIgnoreCase(type)){ + + processYmlModel(file.toString(), modelName); + + }else{ + + tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI); + classMap.putAll(tempMap); + } + } + } + } + + private void doCleanUpFiles(String randomID) { + String cleanUpFile; + cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip"; + try { + FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID)); + FileUtils.deleteDirectory(new File(randomID)); + File deleteFile = new File(cleanUpFile); + FileUtils.forceDelete(deleteFile); + } catch (IOException e) { + logger.error("Failed to unzip model file " + randomID, e); + } + } + private void processYmlModel(String fileName, String modelName){ try { @@ -145,7 +155,7 @@ public class CreateNewMicroServiceModel { returnReferenceList.put(modelName, utils.getReferenceAttributes()); msAttributes.setRefAttribute(returnReferenceList); - if(utils.getListConstraints()!=""){ + if(!PolicyDBDao.isNullOrEmpty(utils.getListConstraints())){ LinkedHashMap enumList =new LinkedHashMap<>(); String[] listArray=utils.getListConstraints().split("#"); for(String str:listArray){ diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java index 3b3e81ee2..4c837bb18 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java @@ -231,13 +231,13 @@ public abstract class Policy { String absolutePath = parentPath.toString(); if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) { policyDir = absolutePath.substring(absolutePath.lastIndexOf('\\') + 1, absolutePath.length()); - if (policyDir == null || policyDir.equals(EMPTY_STRING)) { + if (policyDir.equals(EMPTY_STRING)) { policyDir = absolutePath.substring(absolutePath.lastIndexOf('/') + 1, absolutePath.length()); } } String fileName = "default"; - if (policyDir != null && !policyDir.equals(EMPTY_STRING)) { + if (!policyDir.equals(EMPTY_STRING)) { if("ClosedLoop_PM".equals(policyConfigType)){ fileName = policyType + "_" + "PM" + "_" +java.lang.String.format(policyFileName) + "." +version +".xml"; }else if("ClosedLoop_Fault".equals(policyConfigType)){ @@ -271,9 +271,8 @@ public abstract class Policy { // //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP //and this transaction is intercepted up stream. - InputStream inputStream = null; - try { - inputStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType) policyData); + + try(InputStream inputStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType) policyData)) { PolicyDef policyDef = DOMPolicyDef.load(inputStream); if (policyDef == null) { success.put("validation", "PolicyDef Validation Failed"); @@ -283,13 +282,6 @@ public abstract class Policy { } catch (Exception e) { LOGGER.error("PolicyDef Validation failed"+e); success.put("error", "Validation Failed"); - }finally{ - try { - if(inputStream != null) - inputStream.close(); - } catch (IOException e) { - LOGGER.error("Exception Occured while closing the input stream"+e); - } } } else { PolicyLogger.error("Unknown data type sent back."); 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 2374ac4ec..dc1287b6c 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -86,14 +86,13 @@ import org.onap.policy.xacml.std.pap.StdPDPPolicy; import org.onap.policy.xacml.util.XACMLPolicyWriter; import org.w3c.dom.Document; import org.xml.sax.InputSource; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDP; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; - public class PolicyDBDao { private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class); private List otherServers; @@ -101,31 +100,30 @@ public class PolicyDBDao { private static PolicyDBDao currentInstance = null; private PAPPolicyEngine papEngine; - public static final String JSON_CONFIG = "JSON"; - public static final String XML_CONFIG = "XML"; - public static final String PROPERTIES_CONFIG = "PROPERTIES"; - public static final String OTHER_CONFIG = "OTHER"; - public static final String AUDIT_USER = "audit"; + private static final String JSON_CONFIG = "JSON"; + private static final String XML_CONFIG = "XML"; + private static final String PROPERTIES_CONFIG = "PROPERTIES"; + private static final String OTHER_CONFIG = "OTHER"; //Declared to static variables which were repeating multiple times across the PolicyDBDao public static final String config = "Config"; public static final String action = "Action"; - public static final String groupIdVar = "groupId"; - public static final String deletedVar = "deleted"; - public static final String groupEntitySelectQuery = "SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"; - public static final String pdpEntitySelectQuery = "SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"; - public static final String groupCannotBeFound = "The group could not be found with id "; - public static final String foundInDBNotDeleted = " were found in the database that are not deleted"; - public static final String moreThanOnePDP = "Somehow, more than one pdp with the same id "; - public static final String deletedStatusFound = " and deleted status were found in the database"; - public static final String duplicateGroupId = "Somehow, more than one group with the same id "; - public static final String pdpIdVariable = "pdpId"; - public static final String queryFailedToCheckExisting = "Query failed trying to check for existing group"; - public static final String queryFailedToGetGroup = "Query failed trying to get group "; + private static final String groupIdVar = "groupId"; + private static final String deletedVar = "deleted"; + private static final String groupEntitySelectQuery = "SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"; + private static final String pdpEntitySelectQuery = "SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"; + private static final String groupCannotBeFound = "The group could not be found with id "; + private static final String foundInDBNotDeleted = " were found in the database that are not deleted"; + private static final String moreThanOnePDP = "Somehow, more than one pdp with the same id "; + private static final String deletedStatusFound = " and deleted status were found in the database"; + private static final String duplicateGroupId = "Somehow, more than one group with the same id "; + private static final String pdpIdVariable = "pdpId"; + private static final String queryFailedToCheckExisting = "Query failed trying to check for existing group"; + private static final String queryFailedToGetGroup = "Query failed trying to get group "; public static final String scope = "scope"; - public static final String policyDBDaoVar = "PolicyDBDao"; - public static final String duplicatePolicyId = "Somehow, more than one policy with the id "; - public static final String foundInDB = " were found in the database"; + private static final String policyDBDaoVar = "PolicyDBDao"; + private static final String duplicatePolicyId = "Somehow, more than one policy with the id "; + private static final String foundInDB = " were found in the database"; private static boolean isJunit = false; @@ -425,11 +423,11 @@ public class PolicyDBDao { return true; } - public void notifyOthers(long entityId,String entityType){ + private void notifyOthers(long entityId,String entityType){ notifyOthers(entityId,entityType,null); } - public void notifyOthers(long entityId, String entityType, String newGroupId){ + private void notifyOthers(long entityId, String entityType, String newGroupId){ logger.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers("+entityId+","+entityType+","+newGroupId+") called"); LinkedList notifyThreads = new LinkedList<>(); @@ -481,19 +479,18 @@ public class PolicyDBDao { URL url; String papUrl; try { - String[] papUrlUserPass = getPapUrlUserPass(); - if(papUrlUserPass == null ){ - papUrl = "undefined"; - } else { - papUrl = papUrlUserPass[0]; - } + String[] papUrlUserPass = getPapUrlUserPass(); + if(papUrlUserPass == null ){ + papUrl = "undefined"; + } else { + papUrl = papUrlUserPass[0]; + } logger.debug("We are going to try to notify "+o); //is this our own url? String ourUrl = o; try{ ourUrl = splitPapUrlUserPass((String)o)[0]; }catch(Exception e){ - ourUrl = o; logger.debug(e); } if(o == null){ @@ -617,57 +614,57 @@ public class PolicyDBDao { int pauseBetweenRetries = 1000; switch(entityType){ - case POLICY_NOTIFICATION: - for(int i=0; i 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, policyDBDaoVar, "Could not get policy to remove: "+pol.getId()); - throw new PersistenceException("Could not get policy to remove: "+pol.getId()); - } + deletePolicyInScope(username, groupToUpdateInDB, pol, scopeAndName); } } } @@ -2201,6 +2171,45 @@ public class PolicyDBDao { } } + private void deletePolicyInScope(String username, GroupEntity groupToUpdateInDB, PDPPolicy pol, String[] scopeAndName) { + PolicyEntity policyToDelete; + if (scopeAndName == null) { + return; + } + try{ + policyToDelete = getPolicy(scopeAndName[0],scopeAndName[1]); + if ("XACMLPapServlet.doDelete".equals(username)) { + Iterator dbPolicyIt = groupToUpdateInDB.getPolicies().iterator(); + String policyName = getPolicyNameAndVersionFromPolicyFileName(policyToDelete.getPolicyName())[0]; + + logger.info("PolicyDBDao: delete policy from GroupEntity"); + deletePolicyFromGroupEntity(groupToUpdateInDB, policyToDelete, dbPolicyIt, policyName); + } + }catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, policyDBDaoVar, "Could not get policy to remove: "+pol.getId()); + throw new PersistenceException("Could not get policy to remove: "+pol.getId()); + } + } + + private void deletePolicyFromGroupEntity(GroupEntity groupToUpdateInDB, PolicyEntity policyToDelete, Iterator dbPolicyIt, String policyName) { + 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()); + } + } + @Override public void addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, String username) { logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup("+pdpID+", "+groupID+", "+pdpName+", "+pdpDescription+", "+pdpJmxPort+", "+username+") called"); @@ -2654,4 +2663,4 @@ public class PolicyDBDao { } } -} +} \ No newline at end of file -- cgit 1.2.3-korg