diff options
author | Rashmi Pujar <rashmi.pujar@bell.ca> | 2019-03-28 11:53:51 -0400 |
---|---|---|
committer | Rashmi Pujar <rashmi.pujar@bell.ca> | 2019-03-28 14:43:11 -0400 |
commit | 36fc43ca0358087c512767287cbeb3038824650e (patch) | |
tree | 53e694cbd78d0a21c297cc4b47395e538521bfd5 /POLICY-SDK-APP | |
parent | 84540cb5794753f9ade18149238ccde443edac35 (diff) |
FIx Sonar Issues reported on ActionPolicyController
- code cleanup, reduce cognitive complexity, extract constants etc
Issue-ID: POLICY-1615
Change-Id: Ie0f634b1848076bba4c3ea3cbf9252b9faba0f8f
Signed-off-by: Rashmi Pujar <rashmi.pujar@bell.ca>
Diffstat (limited to 'POLICY-SDK-APP')
4 files changed, 251 insertions, 247 deletions
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java index b7fbbdd98..6aa40dacf 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java @@ -52,7 +52,7 @@ public class PolicyAdapter { policyAdapter.setConfigPolicyType(configPolicyName); } if ("Action".equalsIgnoreCase(policyAdapter.getPolicyType())) { - new ActionPolicyController().prePopulateActionPolicyData(policyAdapter, entity); + new ActionPolicyController().prePopulateActionPolicyData(policyAdapter); } if ("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())) { new DecisionPolicyController().prePopulateDecisionPolicyData(policyAdapter, entity); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java index a556beeaa..578258403 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java @@ -3,6 +3,7 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +23,6 @@ package org.onap.policy.controller; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -33,7 +33,6 @@ import javax.xml.bind.JAXBElement; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -56,132 +55,149 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @RequestMapping({ "/" }) public class ActionPolicyController extends RestrictedBaseController { private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class); + private static final String PERFORMER_ATTRIBUTE_ID = "performer"; + private static final String DYNAMIC_RULE_ALGORITHM_FIELD_1 = "dynamicRuleAlgorithmField1"; + private static final String DYNAMIC_RULE_ALGORITHM_FIELD_2 = "dynamicRuleAlgorithmField2"; + private LinkedList<Integer> ruleAlgorithmTracker; + private Map<String, String> performer = new HashMap<>(); + private List<Object> ruleAlgorithmList; public ActionPolicyController() { // Default Constructor } - private ArrayList<Object> attributeList; - protected LinkedList<Integer> ruleAlgoirthmTracker; - public static final String PERFORMER_ATTRIBUTEID = "performer"; - protected Map<String, String> performer = new HashMap<>(); - private ArrayList<Object> ruleAlgorithmList; - - public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - attributeList = new ArrayList<>(); + public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter) { ruleAlgorithmList = new ArrayList<>(); performer.put("PDP", "PDPAction"); performer.put("PEP", "PEPAction"); if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName() - .substring(policyAdapter.getPolicyName().indexOf('_') + 1); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try { - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - } catch (Exception e) { - LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy for Action. + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + + // 1. Set policy-name, policy-filename and description to Policy Adapter + setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy); + + // 2a. Get the target data under policy for Action. TargetType target = policy.getTarget(); - if (target != null) { - // under target we have AnyOFType - List<AnyOfType> anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AntOfType we have AllOfType - List<AllOfType> allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator<AllOfType> iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOfType we have Mathch. - List<MatchType> matchList = allOf.getMatch(); - if (matchList != null) { - Iterator<MatchType> iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attributevalue and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // Component attributes are saved under Target here we are fetching them back. - // One row is default so we are not adding dynamic component at index 0. - Map<String, String> attribute = new HashMap<>(); - attribute.put("key", attributeId); - attribute.put("value", value); - attributeList.add(attribute); - } - } - policyAdapter.setAttributes(attributeList); - } - } - } + if (target == null) { + return; + } + + // 2b. Set attributes to Policy Adapter + setPolicyAdapterAttributes(policyAdapter, target.getAnyOf()); + + List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + // Under rule we have Condition and obligation. + for (Object o : ruleList) { + if (!(o instanceof RuleType)) { + continue; } + // 3. Set rule-algorithm choices to Policy Adapter + setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o); - List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - // Under rule we have Condition and obligation. - for (Object o : ruleList) { - if (o instanceof RuleType) { - ConditionType condition = ((RuleType) o).getCondition(); - ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); - if (condition != null) { - int index = 0; - ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); - ruleAlgoirthmTracker = new LinkedList<>(); - // Populating Rule Algorithms starting from compound. - prePopulateCompoundRuleAlgorithm(index, actionApply); - } - policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); - // get the Obligation data under the rule for Form elements. - if (obligations != null) { - // Under the obligationExpressions we have obligationExpression. - List<ObligationExpressionType> obligationList = obligations.getObligationExpression(); - if (obligationList != null) { - Iterator<ObligationExpressionType> iterObligation = obligationList.iterator(); - while (iterObligation.hasNext()) { - ObligationExpressionType obligation = iterObligation.next(); - policyAdapter.setActionAttributeValue(obligation.getObligationId()); - // Under the obligationExpression we have attributeAssignmentExpression. - List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation - .getAttributeAssignmentExpression(); - if (attributeAssignmentExpressionList != null) { - Iterator<AttributeAssignmentExpressionType> iterAttributeAssignmentExpression = attributeAssignmentExpressionList - .iterator(); - while (iterAttributeAssignmentExpression.hasNext()) { - AttributeAssignmentExpressionType attributeAssignmentExpression = iterAttributeAssignmentExpression - .next(); - String attributeID = attributeAssignmentExpression.getAttributeId(); - AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression - .getExpression().getValue(); - if (attributeID.equals(PERFORMER_ATTRIBUTEID)) { - for ( Entry<String, String> entry: performer.entrySet()) { - String key = entry.getKey(); - String keyValue = entry.getValue(); - if (keyValue.equals(attributeValue.getContent().get(0))) { - policyAdapter.setActionPerformer(key); - } - } - } - } - } - } - } - } + // 4a. Get the Obligation data under the rule for Form elements. + ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); + + // 4b. Set action attribute-value and action-performer to Policy Adapter + setPolicyAdapterActionData(policyAdapter, obligations); + } + } + } + + private void setPolicyAdapterActionData(PolicyRestAdapter policyAdapter, ObligationExpressionsType obligations) { + if (obligations == null) { + return; + } + // Under the obligationExpressions we have obligationExpression. + List<ObligationExpressionType> obligationList = obligations.getObligationExpression(); + if (obligationList == null) { + return; + } + for (ObligationExpressionType obligation : obligationList) { + policyAdapter.setActionAttributeValue(obligation.getObligationId()); + // Under the obligationExpression we have attributeAssignmentExpression. + List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation + .getAttributeAssignmentExpression(); + if (attributeAssignmentExpressionList == null) { + continue; + } + for (AttributeAssignmentExpressionType attributeAssignmentExpression : attributeAssignmentExpressionList) { + String attributeID = attributeAssignmentExpression.getAttributeId(); + AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression + .getExpression().getValue(); + if (!attributeID.equals(PERFORMER_ATTRIBUTE_ID)) { + continue; + } + performer.forEach((key, keyValue) -> { + if (keyValue.equals(attributeValue.getContent().get(0))) { + policyAdapter.setActionPerformer(key); } + }); + } + } + } + + private void setPolicyAdapterPolicyNameAndDesc(PolicyRestAdapter policyAdapter, PolicyType policy) { + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName() + .substring(policyAdapter.getPolicyName().indexOf('_') + 1); + policyAdapter.setPolicyName(policyNameValue); + String description; + try { + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + } catch (Exception e) { + LOGGER.error("Error while collecting the description tag in ActionPolicy " + policyNameValue, e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + } + + private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType o) { + ConditionType condition = o.getCondition(); + if (condition != null) { + int index = 0; + ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); + ruleAlgorithmTracker = new LinkedList<>(); + // Populating Rule Algorithms starting from compound. + prePopulateCompoundRuleAlgorithm(index, actionApply); + } + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + } + + private void setPolicyAdapterAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) { + List<Object> attributeList = new ArrayList<>(); + if (anyOfList == null) { + return; + } + // under target we have AnyOFType + for (AnyOfType anyOf : anyOfList) { + // Under AntOfType we have AllOfType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList == null) { + continue; + } + // Under AllOfType we have Match. + for (AllOfType allOfType : allOfList) { + List<MatchType> matchList = allOfType.getMatch(); + if (matchList != null) { + // + // Under the match we have attributeValue and + // attributeDesignator. So,finally down to the actual attribute. + // + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic component at index 0. + matchList.forEach(match -> { + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + Map<String, String> attribute = new HashMap<>(); + attribute.put("key", attributeId); + attribute.put("value", value); + attributeList.add(attribute); + }); } + policyAdapter.setAttributes(attributeList); } } } @@ -197,7 +213,7 @@ public class ActionPolicyController extends RestrictedBaseController { // Check to see if Attribute Value exists, if yes then it is not a compound rule if (jaxbElement.getValue() instanceof AttributeValueType) { prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes); - ruleAlgoirthmTracker.addLast(index); + ruleAlgorithmTracker.addLast(index); isCompoundRule = false; index++; } @@ -221,11 +237,11 @@ public class ActionPolicyController extends RestrictedBaseController { } rule.put("id", "A" + (index + 1)); // Populate Key and values for Compound Rule - rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1)); - ruleAlgoirthmTracker.removeLast(); - rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); - ruleAlgoirthmTracker.removeLast(); - ruleAlgoirthmTracker.addLast(index); + rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1)); + ruleAlgorithmTracker.removeLast(); + rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1)); + ruleAlgorithmTracker.removeLast(); + ruleAlgorithmTracker.addLast(index); ruleAlgorithmList.add(rule); index++; } @@ -250,26 +266,25 @@ public class ActionPolicyController extends RestrictedBaseController { List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0) .getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId()); // Get from Attribute Value AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue(); String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue); } // Rule Attribute added as value else if ((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType) { AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue(); String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue); ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0) .getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId()); } ruleAlgorithmList.add(ruleMap); } - } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java index 346b95aff..fc25e29f0 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java @@ -3,13 +3,14 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * 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. @@ -20,7 +21,6 @@ package org.onap.policy.controller; - import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; @@ -50,77 +50,82 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Controller @RequestMapping({"/"}) -public class AdminTabController extends RestrictedBaseController{ - - private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class); - - private static CommonClassDao commonClassDao; - - public AdminTabController() { - //default constructor - } - - @Autowired - private AdminTabController(CommonClassDao commonClassDao){ - AdminTabController.commonClassDao = commonClassDao; - } - - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - AdminTabController.commonClassDao = commonClassDao; - } - - @RequestMapping(value={"/get_LockDownData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - } - } - - @RequestMapping(value={"/adminTabController/save_LockDownValue.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) throws IOException{ - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - String userId = UserUtils.getUserSession(request).getOrgUserId(); - LOGGER.info("****************************************Logging UserID for Application Lockdown Function*****************************************"); - LOGGER.info("UserId: " + userId); - LOGGER.info("*********************************************************************************************************************************"); - JsonNode root = mapper.readTree(request.getReader()); - GlobalRoleSettings globalRole = mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class); - globalRole.setRole("super-admin"); - commonClassDao.update(globalRole); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)); - JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); - - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; - } +public class AdminTabController extends RestrictedBaseController { + + private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class); + private static final String CHARACTER_ENCODING = "UTF-8"; + + private static CommonClassDao commonClassDao; + + public AdminTabController() { + //default constructor + } + + @Autowired + private AdminTabController(CommonClassDao commonClassDao) { + AdminTabController.commonClassDao = commonClassDao; + } + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + AdminTabController.commonClassDao = commonClassDao; + } + + @RequestMapping(value = {"/get_LockDownData"}, method = { + org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) + public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response) { + try { + Map<String, Object> model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + LOGGER.error("Exception Occured" + e); + } + } + + @RequestMapping(value = {"/adminTabController/save_LockDownValue.htm"}, method = { + org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) + throws IOException { + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String userId = UserUtils.getUserSession(request).getOrgUserId(); + LOGGER.info( + "****************************************Logging UserID for Application Lockdown Function*****************************************"); + LOGGER.info("UserId: " + userId); + LOGGER.info( + "*********************************************************************************************************************************"); + JsonNode root = mapper.readTree(request.getReader()); + GlobalRoleSettings globalRole = mapper + .readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class); + globalRole.setRole("super-admin"); + commonClassDao.update(globalRole); + + response.setCharacterEncoding(CHARACTER_ENCODING); + response.setContentType("application / json"); + request.setCharacterEncoding(CHARACTER_ENCODING); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)); + JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); + + out.write(j.toString()); + + return null; + } catch (Exception e) { + LOGGER.error("Exception Occured" + e); + response.setCharacterEncoding(CHARACTER_ENCODING); + request.setCharacterEncoding(CHARACTER_ENCODING); + PrintWriter out = response.getWriter(); + out.write(PolicyUtils.CATCH_EXCEPTION); + } + return null; + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java index 018668fc7..3af430f45 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java @@ -3,6 +3,7 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,6 +38,9 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -63,6 +67,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.att.research.xacml.api.pap.PAPException; @@ -82,11 +87,9 @@ public class AutoPushController extends RestrictedBaseController { CommonClassDao commonClassDao; private PDPGroupContainer container; - protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>()); - private PDPPolicyContainer policyContainer; - private PolicyController policyController; + protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>()); public PolicyController getPolicyController() { return policyController; @@ -96,8 +99,6 @@ public class AutoPushController extends RestrictedBaseController { this.policyController = policyController; } - private List<Object> data; - public synchronized void refreshGroups() { synchronized (this.groups) { this.groups.clear(); @@ -116,35 +117,26 @@ public class AutoPushController extends RestrictedBaseController { return policyController != null ? getPolicyController() : new PolicyController(); } - @RequestMapping(value = { "/get_AutoPushPoliciesContainerData" }, method = { - org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = {"/get_AutoPushPoliciesContainerData"}, method = { + RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) { try { - Set<String> scopes; - List<String> roles; - data = new ArrayList<>(); - String userId = UserUtils.getUserSession(request).getOrgUserId(); + Set<String> scopes = new HashSet<>(); + List<String> roles = new ArrayList<>(); + List<Object> data = new ArrayList<>(); Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); + + String userId = UserUtils.getUserSession(request).getOrgUserId(); + PolicyController controller = policyController != null ? getPolicyController() : new PolicyController(); List<Object> userRoles = controller.getRoles(userId); - roles = new ArrayList<>(); - scopes = new HashSet<>(); for (Object role : userRoles) { Roles userRole = (Roles) role; roles.add(userRole.getRole()); - if (userRole.getScope() != null) { - if (userRole.getScope().contains(",")) { - String[] multipleScopes = userRole.getScope().split(","); - for (int i = 0; i < multipleScopes.length; i++) { - scopes.add(multipleScopes[i].replace("[", "").replace("]", "").replace("\"", "").trim()); - } - } else { - if (!"".equals(userRole.getScope())) { - scopes.add(userRole.getScope().replace("[", "").replace("]", "").replace("\"", "").trim()); - } - } - } + scopes.addAll(Stream.of(userRole.getScope().split(",")) + .map(String::new) + .collect(Collectors.toSet()) + ); } if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) { data = commonClassDao.getData(PolicyVersion.class); @@ -157,29 +149,27 @@ public class AutoPushController extends RestrictedBaseController { params.put("scope", scope); List<Object> filterdatas = commonClassDao.getDataByQuery(query, params); if (filterdatas != null) { - for (int i = 0; i < filterdatas.size(); i++) { - data.add(filterdatas.get(i)); - } + data.addAll(filterdatas); } } } else { PolicyVersion emptyPolicyName = new PolicyVersion(); emptyPolicyName - .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); + .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); data.add(emptyPolicyName); } } + ObjectMapper mapper = new ObjectMapper(); model.put("policydatas", mapper.writeValueAsString(data)); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); JSONObject j = new JSONObject(msg); response.getWriter().write(j.toString()); } catch (Exception e) { - logger.error("Exception Occured" + e); + logger.error("Exception Occurred" + e); } } - @RequestMapping(value = { "/auto_Push/PushPolicyToPDP.htm" }, method = { - org.springframework.web.bind.annotation.RequestMethod.POST }) + @RequestMapping(value = { "/auto_Push/PushPolicyToPDP.htm" }, method = { RequestMethod.POST }) public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { @@ -224,16 +214,15 @@ public class AutoPushController extends RestrictedBaseController { // // Get the current selection - String selectedItem = policyId; // - assert selectedItem != null; + assert policyId != null; // create the id of the target file // Our standard for file naming is: // <domain>.<filename>.<version>.xml // since the file name usually has a ".xml", we need to strip // that // before adding the other parts - String name = selectedItem.replace(File.separator, "."); + String name = policyId.replace(File.separator, "."); String id = name; if (id.endsWith(".xml")) { id = id.replace(".xml", ""); @@ -265,7 +254,6 @@ public class AutoPushController extends RestrictedBaseController { bw.close(); URI selectedURI = temp.toURI(); try { - // // Create the policy selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI); } catch (IOException e) { @@ -352,8 +340,7 @@ public class AutoPushController extends RestrictedBaseController { } @SuppressWarnings("unchecked") - @RequestMapping(value = { "/auto_Push/remove_GroupPolicies.htm" }, method = { - org.springframework.web.bind.annotation.RequestMethod.POST }) + @RequestMapping(value = { "/auto_Push/remove_GroupPolicies.htm" }, method = { RequestMethod.POST }) public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { PolicyController controller = getPolicyControllerInstance(); @@ -374,12 +361,10 @@ public class AutoPushController extends RestrictedBaseController { policyContainer = new PDPPolicyContainer(group); if (removePolicyData.size() > 0) { - for (int i = 0; i < removePolicyData.size(); i++) { - String polData = removePolicyData.get(i).toString(); - this.policyContainer.removeItem(polData); - } - Set<PDPPolicy> changedPolicies = new HashSet<>(); - changedPolicies.addAll((Collection<PDPPolicy>) this.policyContainer.getItemIds()); + IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString()) + .forEach(polData -> this.policyContainer.removeItem(polData)); + Set<PDPPolicy> changedPolicies = new HashSet<>( + (Collection<PDPPolicy>) this.policyContainer.getItemIds()); StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(), null); updatedGroupObject.setPolicies(changedPolicies); @@ -411,5 +396,4 @@ public class AutoPushController extends RestrictedBaseController { } return null; } - } |