From: Jorge Hernandez Date: Wed, 27 Mar 2019 22:11:12 +0000 (+0000) Subject: Merge "Model enhancement to support embedded JSON" X-Git-Tag: 1.4.0~34 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=policy%2Fengine.git;a=commitdiff_plain;h=2cc2acb29f4d7f925bb922a99e672844f2948260;hp=89040c3632ffb584a502316054012b827f79ae17 Merge "Model enhancement to support embedded JSON" --- 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 abb425131..86455aa30 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -333,7 +333,7 @@ public class CreateNewMicroServiceModel { Map successMap = new HashMap<>(); CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); List result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+version); - if(result.isEmpty()){ + if(result == null || result.isEmpty()){ MicroServiceModels model = new MicroServiceModels(); model.setModelName(modelName); model.setVersion(version); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java index a0044d26b..d6ebed2b8 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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,15 +20,16 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.io.IOUtils; import org.onap.policy.api.PEDependency; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -50,15 +51,11 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller -public class BRMSDictionaryController{ +public class BRMSDictionaryController { - private static final Logger LOGGER = FlexLogger.getLogger(BRMSDictionaryController.class); + private static final Logger LOGGER = FlexLogger.getLogger(BRMSDictionaryController.class); private static final String VALIDATIONRESPONSE = "Validation"; @@ -67,9 +64,9 @@ public class BRMSDictionaryController{ private static String successMsg = "Success"; private static String duplicateResponseString = "Duplicate"; private static String ruleName = "ruleName"; - private static String errorMessage = "Error"; + private static String errorMessage = "Error"; private static String operation = "operation"; - private static String dictionaryFields ="dictionaryFields"; + private static String dictionaryFields = "dictionaryFields"; private static String userid = "userid"; private static String dependencyName = "dependencyName"; private static String controllerName = "controllerName"; @@ -78,7 +75,7 @@ public class BRMSDictionaryController{ private static String brmsControllerDatas = "brmsControllerDictionaryDatas"; @Autowired - public BRMSDictionaryController(CommonClassDao commonClassDao){ + public BRMSDictionaryController(CommonClassDao commonClassDao) { BRMSDictionaryController.commonClassDao = commonClassDao; } @@ -90,32 +87,36 @@ public class BRMSDictionaryController{ super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_BRMSParamDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSParamDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_BRMSParamDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getBRMSParamDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, brmsParamDatas, ruleName, BRMSParamTemplate.class); } - @RequestMapping(value={"/get_BRMSParamData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSParamDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_BRMSParamData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getBRMSParamDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, brmsParamDatas, BRMSParamTemplate.class); } - @RequestMapping(value={"/brms_dictionary/set_BRMSParamData"}, method={RequestMethod.POST}) - public static void setRuleData(HttpServletRequest request) throws IOException{ + @RequestMapping(value = {"/brms_dictionary/set_BRMSParamData"}, method = {RequestMethod.POST}) + public static void setRuleData(HttpServletRequest request) throws IOException { StringWriter writer = new StringWriter(); - IOUtils.copy(request.getInputStream() , writer, StandardCharsets.UTF_8); - String cleanStreamBoundary = writer.toString().replaceFirst("------(.*)(?s).*octet-stream", ""); - rule = cleanStreamBoundary.substring(0, cleanStreamBoundary.lastIndexOf("end")+4); + IOUtils.copy(request.getInputStream(), writer, StandardCharsets.UTF_8); + String cleanStreamBoundary = + writer.toString().replaceFirst("------(.*)(?s).*octet-stream", ""); + rule = cleanStreamBoundary.substring(0, cleanStreamBoundary.lastIndexOf("end") + 4); } - @RequestMapping(value={"/brms_dictionary/save_BRMSParam"}, method={RequestMethod.POST}) - public ModelAndView saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/brms_dictionary/save_BRMSParam"}, method = {RequestMethod.POST}) + public ModelAndView saveBRMSParamDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -125,83 +126,96 @@ public class BRMSDictionaryController{ BRMSParamTemplate bRMSParamTemplateData; String userId = null; - if(fromAPI){ - bRMSParamTemplateData = mapper.readValue(root.get(dictionaryFields).toString(), BRMSParamTemplate.class); + if (fromAPI) { + bRMSParamTemplateData = mapper.readValue(root.get(dictionaryFields).toString(), + BRMSParamTemplate.class); userId = "API"; - }else{ - bRMSParamTemplateData = mapper.readValue(root.get("brmsParamDictionaryData").toString(), BRMSParamTemplate.class); + } else { + bRMSParamTemplateData = mapper.readValue( + root.get("brmsParamDictionaryData").toString(), BRMSParamTemplate.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(bRMSParamTemplateData.getRuleName(), ruleName, BRMSParamTemplate.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + bRMSParamTemplateData.getRuleName(), ruleName, BRMSParamTemplate.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { BRMSParamTemplate data = (BRMSParamTemplate) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { bRMSParamTemplateData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != bRMSParamTemplateData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != bRMSParamTemplateData.getId()))) { duplicateflag = true; } } String responseString = null; boolean validation = false; - if(rule != null && CreateBRMSRuleTemplate.validateRuleParams(rule)){ + if (rule != null && CreateBRMSRuleTemplate.validateRuleParams(rule)) { bRMSParamTemplateData.setRule(rule); validation = true; - if(!duplicateflag){ - if(bRMSParamTemplateData.getId() == 0){ + if (!duplicateflag) { + if (bRMSParamTemplateData.getId() == 0) { bRMSParamTemplateData.setUserCreatedBy(userInfo); commonClassDao.save(bRMSParamTemplateData); - }else{ + } else { commonClassDao.update(bRMSParamTemplateData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class)); - }else{ + responseString = mapper + .writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class)); + } else { responseString = duplicateResponseString; } } - if(!validation){ + if (!validation) { responseString = VALIDATIONRESPONSE; } - if(fromAPI){ - if (responseString!=null && !(duplicateResponseString).equals(responseString) && !VALIDATIONRESPONSE.equals(responseString)) { + if (fromAPI) { + if (responseString != null && !(duplicateResponseString).equals(responseString) + && !VALIDATIONRESPONSE.equals(responseString)) { responseString = successMsg; } ModelAndView result = new ModelAndView(); result.setViewName(responseString); return result; - }else{ + } else { utils.setResponseData(response, brmsParamDatas, responseString); } - }catch(Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/brms_dictionary/remove_brmsParam"}, method={RequestMethod.POST}) - public void removeBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response)throws IOException { + @RequestMapping(value = {"/brms_dictionary/remove_brmsParam"}, method = {RequestMethod.POST}) + public void removeBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, brmsParamDatas, BRMSParamTemplate.class); } - @RequestMapping(value={"/get_BRMSDependencyDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSDependencyDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_BRMSDependencyDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getBRMSDependencyDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, brmsDependencyDatas, dependencyName, BRMSDependency.class); } - - @RequestMapping(value={"/get_BRMSDependencyData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSDependencyDictionaryEntityData(HttpServletResponse response){ + + @RequestMapping(value = {"/get_BRMSDependencyData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getBRMSDependencyDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, brmsDependencyDatas, BRMSDependency.class); } - - @RequestMapping(value={"/brms_dictionary/save_BRMSDependencyData"}, method={RequestMethod.POST}) - public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + + @RequestMapping(value = {"/brms_dictionary/save_BRMSDependencyData"}, + method = {RequestMethod.POST}) + public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { LOGGER.debug("DictionaryController: saveBRMSDependencyDictionary() is called"); @@ -212,91 +226,109 @@ public class BRMSDictionaryController{ BRMSDependency brmsDependency; String userId = null; - if(fromAPI){ - brmsDependency = mapper.readValue(root.get(dictionaryFields).toString(), BRMSDependency.class); + if (fromAPI) { + brmsDependency = mapper.readValue(root.get(dictionaryFields).toString(), + BRMSDependency.class); userId = "API"; - }else{ - brmsDependency = mapper.readValue(root.get("brmsDependencyDictionaryData").toString(), BRMSDependency.class); + } else { + brmsDependency = mapper.readValue( + root.get("brmsDependencyDictionaryData").toString(), BRMSDependency.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(brmsDependency.getDependencyName(), dependencyName, BRMSDependency.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + brmsDependency.getDependencyName(), dependencyName, BRMSDependency.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { BRMSDependency data = (BRMSDependency) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { brmsDependency.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != brmsDependency.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != brmsDependency.getId()))) { duplicateflag = true; } } LOGGER.audit("the userId from the onap portal is: " + userId); String responseString = null; - if(brmsDependency.getDependency()!=null && !("").equals(brmsDependency.getDependency().trim())){ + if (brmsDependency.getDependency() != null + && !("").equals(brmsDependency.getDependency().trim())) { PEDependency dependency = null; - try{ - dependency = PolicyUtils.jsonStringToObject(brmsDependency.getDependency(), PEDependency.class); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "wrong data given for BRMS PEDependency Dictionary : " + brmsDependency.getDependency(),e); + try { + dependency = PolicyUtils.jsonStringToObject(brmsDependency.getDependency(), + PEDependency.class); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + + "wrong data given for BRMS PEDependency Dictionary : " + + brmsDependency.getDependency(), e); } - if(dependency==null){ + if (dependency == null) { responseString = errorMessage; - }else{ - if(!duplicateflag){ + } else { + if (!duplicateflag) { brmsDependency.setUserModifiedBy(userInfo); - if(brmsDependency.getId() == 0){ + if (brmsDependency.getId() == 0) { brmsDependency.setUserCreatedBy(userInfo); commonClassDao.save(brmsDependency); - }else{ + } else { brmsDependency.setModifiedDate(new Date()); commonClassDao.update(brmsDependency); } - responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class)); - }else{ + responseString = mapper + .writeValueAsString(commonClassDao.getData(BRMSDependency.class)); + } else { responseString = duplicateResponseString; } } } - if(fromAPI){ - if(responseString!=null && !duplicateResponseString.equals(responseString) && !errorMessage.equals(responseString)){ + if (fromAPI) { + if (responseString != null && !duplicateResponseString.equals(responseString) + && !errorMessage.equals(responseString)) { responseString = successMsg; } ModelAndView result = new ModelAndView(); result.setViewName(responseString); return result; - }else{ + } else { utils.setResponseData(response, brmsDependencyDatas, responseString); } - } catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - - @RequestMapping(value={"/brms_dictionary/remove_brmsDependency"}, method={RequestMethod.POST}) - public void removeBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + + @RequestMapping(value = {"/brms_dictionary/remove_brmsDependency"}, + method = {RequestMethod.POST}) + public void removeBRMSDependencyDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, brmsDependencyDatas, BRMSDependency.class); } - - - @RequestMapping(value={"/get_BRMSControllerDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSControllerDictionaryByNameEntityData(HttpServletResponse response){ + + + @RequestMapping(value = {"/get_BRMSControllerDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getBRMSControllerDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, brmsControllerDatas, controllerName, BRMSController.class); } - - @RequestMapping(value={"/get_BRMSControllerData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSControllerDictionaryEntityData(HttpServletResponse response){ + + @RequestMapping(value = {"/get_BRMSControllerData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getBRMSControllerDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, brmsControllerDatas, BRMSController.class); } - - @RequestMapping(value={"/brms_dictionary/save_BRMSControllerData"}, method={RequestMethod.POST}) - public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + @RequestMapping(value = {"/brms_dictionary/save_BRMSControllerData"}, + method = {RequestMethod.POST}) + public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { LOGGER.debug("DictionaryController: saveBRMSControllerDictionary() is called"); @@ -306,79 +338,95 @@ public class BRMSDictionaryController{ JsonNode root = mapper.readTree(request.getReader()); BRMSController brmsController; String userId = null; - if(fromAPI){ - brmsController = mapper.readValue(root.get(dictionaryFields).toString(), BRMSController.class); + if (fromAPI) { + brmsController = mapper.readValue(root.get(dictionaryFields).toString(), + BRMSController.class); userId = "API"; - }else{ - brmsController = mapper.readValue(root.get("brmsControllerDictionaryData").toString(), BRMSController.class); + } else { + brmsController = mapper.readValue( + root.get("brmsControllerDictionaryData").toString(), BRMSController.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(brmsController.getControllerName(), controllerName, BRMSController.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + brmsController.getControllerName(), controllerName, BRMSController.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { BRMSController data = (BRMSController) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { brmsController.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != brmsController.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != brmsController.getId()))) { duplicateflag = true; } } String responseString = null; - if(brmsController.getController()!=null && !("").equals(brmsController.getController().trim())){ + if (brmsController.getController() != null + && !("").equals(brmsController.getController().trim())) { PEDependency dependency = null; - try{ - dependency = PolicyUtils.jsonStringToObject(brmsController.getController(), PEDependency.class); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "wrong data given for BRMS Controller Dictionary : " + brmsController.getController(),e); + try { + dependency = PolicyUtils.jsonStringToObject(brmsController.getController(), + PEDependency.class); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + + "wrong data given for BRMS Controller Dictionary : " + + brmsController.getController(), e); } - if(dependency==null){ + if (dependency == null) { responseString = errorMessage; - }else{ - if(!duplicateflag){ + } else { + if (!duplicateflag) { brmsController.setUserModifiedBy(userInfo); - if(brmsController.getId() == 0){ + if (brmsController.getId() == 0) { brmsController.setUserCreatedBy(userInfo); commonClassDao.save(brmsController); - }else{ + } else { brmsController.setModifiedDate(new Date()); commonClassDao.update(brmsController); } - responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); + } else { responseString = duplicateResponseString; } } } - if(fromAPI){ - if (responseString!=null && !(duplicateResponseString).equals(responseString) && !(errorMessage).equals(responseString)) { + if (fromAPI) { + if (responseString != null && !(duplicateResponseString).equals(responseString) + && !(errorMessage).equals(responseString)) { responseString = successMsg; } ModelAndView result = new ModelAndView(); result.setViewName(responseString); return result; - }else{ + } else { utils.setResponseData(response, brmsControllerDatas, responseString); } - } catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - - @RequestMapping(value={"/brms_dictionary/remove_brmsController"}, method={RequestMethod.POST}) - public void removeBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + @RequestMapping(value = {"/brms_dictionary/remove_brmsController"}, + method = {RequestMethod.POST}) + public void removeBRMSControllerDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, brmsControllerDatas, BRMSController.class); } - - public BRMSDependency getDependencyDataByID(String dependencyName){ - return (BRMSDependency) commonClassDao.getEntityItem(BRMSDependency.class, BRMSDictionaryController.dependencyName, dependencyName); + + public BRMSDependency getDependencyDataByID(String dependencyName) { + return (BRMSDependency) commonClassDao.getEntityItem(BRMSDependency.class, + BRMSDictionaryController.dependencyName, dependencyName); + } + + public BRMSController getControllerDataByID(String controllerName) { + return (BRMSController) commonClassDao.getEntityItem(BRMSController.class, + BRMSDictionaryController.controllerName, controllerName); } - - public BRMSController getControllerDataByID(String controllerName){ - return (BRMSController) commonClassDao.getEntityItem(BRMSController.class, BRMSDictionaryController.controllerName, controllerName); - } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java index 5e7113ad8..2aec0cc0d 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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,13 +20,14 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.policy.pap.xacml.rest.adapters.GridData; import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; @@ -46,12 +47,8 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller -public class ClosedLoopDictionaryController{ +public class ClosedLoopDictionaryController { private static CommonClassDao commonClassDao; private static String vsclaction = "vsclaction"; @@ -72,11 +69,11 @@ public class ClosedLoopDictionaryController{ private static String closedLoopSiteDatas = "closedLoopSiteDictionaryDatas"; @Autowired - public ClosedLoopDictionaryController(CommonClassDao commonClassDao){ + public ClosedLoopDictionaryController(CommonClassDao commonClassDao) { ClosedLoopDictionaryController.commonClassDao = commonClassDao; } - public void setCommonClassDao(CommonClassDao commonClassDao){ + public void setCommonClassDao(CommonClassDao commonClassDao) { ClosedLoopDictionaryController.commonClassDao = commonClassDao; } @@ -84,89 +81,102 @@ public class ClosedLoopDictionaryController{ commonClassDao = commonClassDaoImpl; } - public ClosedLoopDictionaryController(){ + public ClosedLoopDictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_VSCLActionDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVSCLActionDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_VSCLActionDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getVSCLActionDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, vsclActionDatas, vsclaction, VSCLAction.class); } - @RequestMapping(value={"/get_VSCLActionData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVSCLActionDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_VSCLActionData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getVSCLActionDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, vsclActionDatas, VSCLAction.class); } - @RequestMapping(value={"/get_VNFTypeDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVNFTypeDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_VNFTypeDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getVNFTypeDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, vnfTypeDatas, vnftype, VNFType.class); } - @RequestMapping(value={"/get_VNFTypeData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVNFTypeDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_VNFTypeData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getVNFTypeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, vnfTypeDatas, VNFType.class); } - @RequestMapping(value={"/get_PEPOptionsDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPEPOptionsDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PEPOptionsDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPEPOptionsDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, pepOptionDatas, pepName, PEPOptions.class); } - @RequestMapping(value={"/get_PEPOptionsData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPEPOptionsDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PEPOptionsData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPEPOptionsDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, pepOptionDatas, PEPOptions.class); } - @RequestMapping(value={"/get_VarbindDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVarbindDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_VarbindDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getVarbindDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, varbindDatas, varbindName, VarbindDictionary.class); } - @RequestMapping(value={"/get_VarbindDictionaryData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVarbindDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_VarbindDictionaryData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getVarbindDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, varbindDatas, VarbindDictionary.class); } - @RequestMapping(value={"/get_ClosedLoopServicesDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getClosedLoopServiceDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ClosedLoopServicesDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getClosedLoopServiceDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, closedLoopDatas, serviceName, ClosedLoopD2Services.class); } - @RequestMapping(value={"/get_ClosedLoopServicesData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getClosedLoopServiceDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ClosedLoopServicesData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getClosedLoopServiceDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, closedLoopDatas, ClosedLoopD2Services.class); } - @RequestMapping(value={"/get_ClosedLoopSiteDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getClosedLoopSiteDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ClosedLoopSiteDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getClosedLoopSiteDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, closedLoopSiteDatas, siteName, ClosedLoopSite.class); } - @RequestMapping(value={"/get_ClosedLoopSiteData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getClosedLoopSiteDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ClosedLoopSiteData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getClosedLoopSiteDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, closedLoopSiteDatas, ClosedLoopSite.class); } - @RequestMapping(value={"/cl_dictionary/save_vsclAction"}, method={RequestMethod.POST}) - public ModelAndView saveVSCLAction(HttpServletRequest request, HttpServletResponse response)throws IOException{ + @RequestMapping(value = {"/cl_dictionary/save_vsclAction"}, method = {RequestMethod.POST}) + public ModelAndView saveVSCLAction(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -176,59 +186,68 @@ public class ClosedLoopDictionaryController{ VSCLAction vSCLAction; String userId = null; if (fromAPI) { - vSCLAction = mapper.readValue(root.get(dictionaryFields).toString(), VSCLAction.class); + vSCLAction = + mapper.readValue(root.get(dictionaryFields).toString(), VSCLAction.class); userId = "API"; } else { - vSCLAction = mapper.readValue(root.get("vsclActionDictionaryData").toString(), VSCLAction.class); + vSCLAction = mapper.readValue(root.get("vsclActionDictionaryData").toString(), + VSCLAction.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(vSCLAction.getVsclaction(), vsclaction, VSCLAction.class); + List duplicateData = commonClassDao + .checkDuplicateEntry(vSCLAction.getVsclaction(), vsclaction, VSCLAction.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { VSCLAction data = (VSCLAction) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { vSCLAction.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != vSCLAction.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != vSCLAction.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { vSCLAction.setUserModifiedBy(userInfo); - if(vSCLAction.getId() == 0){ + if (vSCLAction.getId() == 0) { vSCLAction.setUserCreatedBy(userInfo); commonClassDao.save(vSCLAction); - }else{ + } else { vSCLAction.setModifiedDate(new Date()); commonClassDao.update(vSCLAction); } - responseString = mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, vsclActionDatas, responseString); } - }catch(Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_VsclAction"}, method={RequestMethod.POST}) - public void removeVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/cl_dictionary/remove_VsclAction"}, method = {RequestMethod.POST}) + public void removeVSCLAction(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, vsclActionDatas, OnapName.class); } - @RequestMapping(value={"/cl_dictionary/save_vnfType"}, method={RequestMethod.POST}) - public ModelAndView saveVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/cl_dictionary/save_vnfType"}, method = {RequestMethod.POST}) + public ModelAndView saveVnfType(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -241,56 +260,63 @@ public class ClosedLoopDictionaryController{ vNFType = mapper.readValue(root.get(dictionaryFields).toString(), VNFType.class); userId = "API"; } else { - vNFType = mapper.readValue(root.get("vnfTypeDictionaryData").toString(), VNFType.class); + vNFType = mapper.readValue(root.get("vnfTypeDictionaryData").toString(), + VNFType.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), vnftype, VNFType.class); + List duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), + vnftype, VNFType.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { VNFType data = (VNFType) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { vNFType.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != vNFType.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != vNFType.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { vNFType.setUserModifiedBy(userInfo); - if(vNFType.getId() == 0){ + if (vNFType.getId() == 0) { vNFType.setUserCreatedBy(userInfo); commonClassDao.save(vNFType); - }else{ + } else { vNFType.setModifiedDate(new Date()); commonClassDao.update(vNFType); } responseString = mapper.writeValueAsString(commonClassDao.getData(VNFType.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, vnfTypeDatas, responseString); } - }catch(Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_vnfType"}, method={RequestMethod.POST}) - public void removeVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/cl_dictionary/remove_vnfType"}, method = {RequestMethod.POST}) + public void removeVnfType(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, vnfTypeDatas, VNFType.class); } - @RequestMapping(value={"/cl_dictionary/save_pepOptions"}, method={RequestMethod.POST}) - public ModelAndView savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/cl_dictionary/save_pepOptions"}, method = {RequestMethod.POST}) + public ModelAndView savePEPOptions(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -300,66 +326,76 @@ public class ClosedLoopDictionaryController{ PEPOptions pEPOptions; GridData gridData; String userId = null; - if(fromAPI){ - pEPOptions = mapper.readValue(root.get(dictionaryFields).toString(), PEPOptions.class); + if (fromAPI) { + pEPOptions = + mapper.readValue(root.get(dictionaryFields).toString(), PEPOptions.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); userId = "API"; - }else{ - pEPOptions = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), PEPOptions.class); - gridData = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), GridData.class); + } else { + pEPOptions = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), + PEPOptions.class); + gridData = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), + GridData.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - - if(!gridData.getAttributes().isEmpty()){ + + if (!gridData.getAttributes().isEmpty()) { pEPOptions.setActions(utils.appendKeyValue(gridData.getAttributes(), ":#@", "=#@")); } - List duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), pepName, PEPOptions.class); + List duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), + pepName, PEPOptions.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PEPOptions data = (PEPOptions) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { pEPOptions.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != pEPOptions.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != pEPOptions.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { pEPOptions.setUserModifiedBy(userInfo); - if(pEPOptions.getId() == 0){ + if (pEPOptions.getId() == 0) { pEPOptions.setUserCreatedBy(userInfo); commonClassDao.save(pEPOptions); - }else{ + } else { pEPOptions.setModifiedDate(new Date()); commonClassDao.update(pEPOptions); } - responseString = mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, pepOptionDatas, responseString); } - }catch(Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_pepOptions"}, method={RequestMethod.POST}) - public void removePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/cl_dictionary/remove_pepOptions"}, method = {RequestMethod.POST}) + public void removePEPOptions(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, pepOptionDatas, VNFType.class); } - @RequestMapping(value={"/cl_dictionary/save_service"}, method={RequestMethod.POST}) - public ModelAndView saveServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/cl_dictionary/save_service"}, method = {RequestMethod.POST}) + public ModelAndView saveServiceType(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -368,59 +404,69 @@ public class ClosedLoopDictionaryController{ JsonNode root = mapper.readTree(request.getReader()); ClosedLoopD2Services serviceData; String userId = null; - if(fromAPI){ - serviceData = mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopD2Services.class); + if (fromAPI) { + serviceData = mapper.readValue(root.get(dictionaryFields).toString(), + ClosedLoopD2Services.class); userId = "API"; } else { - serviceData = mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(), ClosedLoopD2Services.class); + serviceData = + mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(), + ClosedLoopD2Services.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(serviceData.getServiceName(), serviceName, ClosedLoopD2Services.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + serviceData.getServiceName(), serviceName, ClosedLoopD2Services.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { ClosedLoopD2Services data = (ClosedLoopD2Services) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { serviceData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != serviceData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != serviceData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { serviceData.setUserModifiedBy(userInfo); - if(serviceData.getId() == 0){ + if (serviceData.getId() == 0) { serviceData.setUserCreatedBy(userInfo); commonClassDao.save(serviceData); - }else{ + } else { serviceData.setModifiedDate(new Date()); commonClassDao.update(serviceData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); - }else{ + responseString = mapper + .writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, closedLoopDatas, responseString); } - }catch(Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_Service"}, method={RequestMethod.POST}) - public void removeServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/cl_dictionary/remove_Service"}, method = {RequestMethod.POST}) + public void removeServiceType(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, closedLoopDatas, VNFType.class); } - @RequestMapping(value={"/cl_dictionary/save_siteName"}, method={RequestMethod.POST}) - public ModelAndView saveSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/cl_dictionary/save_siteName"}, method = {RequestMethod.POST}) + public ModelAndView saveSiteType(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -429,59 +475,68 @@ public class ClosedLoopDictionaryController{ JsonNode root = mapper.readTree(request.getReader()); ClosedLoopSite siteData; String userId = null; - if(fromAPI){ - siteData = mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopSite.class); + if (fromAPI) { + siteData = mapper.readValue(root.get(dictionaryFields).toString(), + ClosedLoopSite.class); userId = "API"; - }else{ - siteData = mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), ClosedLoopSite.class); + } else { + siteData = mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), + ClosedLoopSite.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - - List duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), siteName, ClosedLoopSite.class); + + List duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), + siteName, ClosedLoopSite.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { ClosedLoopSite data = (ClosedLoopSite) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { siteData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != siteData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != siteData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { siteData.setUserModifiedBy(userInfo); - if(siteData.getId() == 0){ + if (siteData.getId() == 0) { siteData.setUserCreatedBy(userInfo); commonClassDao.save(siteData); - }else{ + } else { siteData.setModifiedDate(new Date()); commonClassDao.update(siteData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, closedLoopSiteDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_site"}, method={RequestMethod.POST}) - public void removeSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/cl_dictionary/remove_site"}, method = {RequestMethod.POST}) + public void removeSiteType(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, closedLoopSiteDatas, VNFType.class); } - @RequestMapping(value={"/cl_dictionary/save_varbind"}, method={RequestMethod.POST}) - public ModelAndView saveVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/cl_dictionary/save_varbind"}, method = {RequestMethod.POST}) + public ModelAndView saveVarbind(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -490,55 +545,63 @@ public class ClosedLoopDictionaryController{ JsonNode root = mapper.readTree(request.getReader()); VarbindDictionary varbindDictionary; String userId = null; - if(fromAPI){ - varbindDictionary = mapper.readValue(root.get(dictionaryFields).toString(), VarbindDictionary.class); + if (fromAPI) { + varbindDictionary = mapper.readValue(root.get(dictionaryFields).toString(), + VarbindDictionary.class); userId = "API"; - }else{ - varbindDictionary = mapper.readValue(root.get("varbindDictionaryData").toString(), VarbindDictionary.class); + } else { + varbindDictionary = mapper.readValue(root.get("varbindDictionaryData").toString(), + VarbindDictionary.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(varbindDictionary.getVarbindName(), varbindName, VarbindDictionary.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + varbindDictionary.getVarbindName(), varbindName, VarbindDictionary.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { VarbindDictionary data = (VarbindDictionary) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { varbindDictionary.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != varbindDictionary.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != varbindDictionary.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { varbindDictionary.setUserModifiedBy(userInfo); - if(varbindDictionary.getId() == 0){ + if (varbindDictionary.getId() == 0) { varbindDictionary.setUserCreatedBy(userInfo); commonClassDao.save(varbindDictionary); - }else{ + } else { varbindDictionary.setModifiedDate(new Date()); commonClassDao.update(varbindDictionary); } - responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, varbindDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_varbindDict"}, method={RequestMethod.POST}) - public void removeVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/cl_dictionary/remove_varbindDict"}, method = {RequestMethod.POST}) + public void removeVarbind(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, varbindDatas, VNFType.class); } -} \ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java index 738a808f6..c89d21e91 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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,14 +20,15 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.DecisionSettings; @@ -40,10 +41,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class DecisionPolicyDictionaryController { @@ -54,36 +51,40 @@ public class DecisionPolicyDictionaryController { private static String duplicateResponseString = "Duplicate"; private static String settingDatas = "settingsDictionaryDatas"; private static String rainDayDatas = "rainyDayDictionaryDatas"; - private static String dictionaryFields ="dictionaryFields"; + private static String dictionaryFields = "dictionaryFields"; @Autowired - public DecisionPolicyDictionaryController(CommonClassDao commonClassDao){ + public DecisionPolicyDictionaryController(CommonClassDao commonClassDao) { DecisionPolicyDictionaryController.commonClassDao = commonClassDao; } - public DecisionPolicyDictionaryController(){ + public DecisionPolicyDictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_SettingsDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + @RequestMapping(value = {"/get_SettingsDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, + HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, settingDatas, xacmlId, DecisionSettings.class); } - @RequestMapping(value={"/get_SettingsDictionaryData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSettingsDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_SettingsDictionaryData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getSettingsDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, settingDatas, DecisionSettings.class); } - @RequestMapping(value={"/decision_dictionary/save_Settings"}, method={RequestMethod.POST}) - public ModelAndView saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/decision_dictionary/save_Settings"}, method = {RequestMethod.POST}) + public ModelAndView saveSettingsDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -93,74 +94,86 @@ public class DecisionPolicyDictionaryController { DecisionSettings decisionSettings; String userId = null; - if(fromAPI){ - decisionSettings = mapper.readValue(root.get(dictionaryFields).toString(), DecisionSettings.class); + if (fromAPI) { + decisionSettings = mapper.readValue(root.get(dictionaryFields).toString(), + DecisionSettings.class); userId = "API"; - }else{ - decisionSettings = mapper.readValue(root.get("settingsDictionaryData").toString(), DecisionSettings.class); + } else { + decisionSettings = mapper.readValue(root.get("settingsDictionaryData").toString(), + DecisionSettings.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), xacmlId, DecisionSettings.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + decisionSettings.getXacmlId(), xacmlId, DecisionSettings.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { DecisionSettings data = (DecisionSettings) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { decisionSettings.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != decisionSettings.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != decisionSettings.getId()))) { duplicateflag = true; } } - if(decisionSettings.getDatatypeBean().getShortName() != null){ + if (decisionSettings.getDatatypeBean().getShortName() != null) { String datatype = decisionSettings.getDatatypeBean().getShortName(); decisionSettings.setDatatypeBean(utils.getDataType(datatype)); } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { decisionSettings.setUserModifiedBy(userInfo); - if(decisionSettings.getId() == 0){ + if (decisionSettings.getId() == 0) { decisionSettings.setUserCreatedBy(userInfo); commonClassDao.save(decisionSettings); - }else{ + } else { decisionSettings.setModifiedDate(new Date()); commonClassDao.update(decisionSettings); } - responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, settingDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/settings_dictionary/remove_settings"}, method={RequestMethod.POST}) - public void removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/settings_dictionary/remove_settings"}, method = {RequestMethod.POST}) + public void removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, settingDatas, DecisionSettings.class); } - @RequestMapping(value={"/get_RainyDayDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + @RequestMapping(value = {"/get_RainyDayDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, + HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, rainDayDatas, bbID, RainyDayTreatments.class); } - @RequestMapping(value={"/get_RainyDayDictionaryData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getRainyDayDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_RainyDayDictionaryData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getRainyDayDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, rainDayDatas, RainyDayTreatments.class); } - @RequestMapping(value={"/decision_dictionary/save_RainyDay"}, method={RequestMethod.POST}) - public ModelAndView saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/decision_dictionary/save_RainyDay"}, method = {RequestMethod.POST}) + public ModelAndView saveRainyDayDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -169,57 +182,70 @@ public class DecisionPolicyDictionaryController { JsonNode root = mapper.readTree(request.getReader()); RainyDayTreatments decisionRainyDay; TreatmentValues treatmentsData = null; - if(fromAPI){ - decisionRainyDay = mapper.readValue(root.get(dictionaryFields).toString(), RainyDayTreatments.class); - treatmentsData = mapper.readValue(root.get(dictionaryFields).toString(), TreatmentValues.class); - }else{ - decisionRainyDay = mapper.readValue(root.get("rainyDayDictionaryData").toString(), RainyDayTreatments.class); - treatmentsData = mapper.readValue(root.get("rainyDayDictionaryData").toString(), TreatmentValues.class); + if (fromAPI) { + decisionRainyDay = mapper.readValue(root.get(dictionaryFields).toString(), + RainyDayTreatments.class); + treatmentsData = mapper.readValue(root.get(dictionaryFields).toString(), + TreatmentValues.class); + } else { + decisionRainyDay = mapper.readValue(root.get("rainyDayDictionaryData").toString(), + RainyDayTreatments.class); + treatmentsData = mapper.readValue(root.get("rainyDayDictionaryData").toString(), + TreatmentValues.class); } - decisionRainyDay.setTreatments(utils.appendKey(treatmentsData.getUserDataTypeValues(), "treatment", ",")); + decisionRainyDay.setTreatments( + utils.appendKey(treatmentsData.getUserDataTypeValues(), "treatment", ",")); - List duplicateData = commonClassDao.checkDuplicateEntry(decisionRainyDay.getBbid()+":"+decisionRainyDay.getWorkstep(), "bbid:workstep", RainyDayTreatments.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + decisionRainyDay.getBbid() + ":" + decisionRainyDay.getWorkstep(), + "bbid:workstep", RainyDayTreatments.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { RainyDayTreatments data = (RainyDayTreatments) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { decisionRainyDay.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != decisionRainyDay.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != decisionRainyDay.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(decisionRainyDay.getId() == 0){ + if (!duplicateflag) { + if (decisionRainyDay.getId() == 0) { commonClassDao.save(decisionRainyDay); - }else{ + } else { commonClassDao.update(decisionRainyDay); } - responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, rainDayDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/decision_dictionary/remove_rainyDay"}, method={RequestMethod.POST}) - public void removeRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/decision_dictionary/remove_rainyDay"}, method = {RequestMethod.POST}) + public void removeRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, rainDayDatas, RainyDayTreatments.class); } } -class TreatmentValues { + +class TreatmentValues { private List userDataTypeValues = new ArrayList<>(); public List getUserDataTypeValues() { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java index a1d1bc8ff..51c8a1d91 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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,13 +20,14 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.policy.pap.xacml.rest.adapters.GridData; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; @@ -39,10 +40,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class DescriptiveDictionaryController { @@ -52,36 +49,40 @@ public class DescriptiveDictionaryController { private static String descriptiveDatas = "descriptiveScopeDictionaryDatas"; @Autowired - public DescriptiveDictionaryController(CommonClassDao commonClassDao){ + public DescriptiveDictionaryController(CommonClassDao commonClassDao) { DescriptiveDictionaryController.commonClassDao = commonClassDao; } - public void setCommonClassDao(CommonClassDao commonClassDao){ + public void setCommonClassDao(CommonClassDao commonClassDao) { DescriptiveDictionaryController.commonClassDao = commonClassDao; } - public DescriptiveDictionaryController(){ + public DescriptiveDictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_DescriptiveScopeByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getDescriptiveDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_DescriptiveScopeByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getDescriptiveDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, descriptiveDatas, dScopeName, DescriptiveScope.class); } - @RequestMapping(value={"/get_DescriptiveScope"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getDescriptiveDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_DescriptiveScope"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getDescriptiveDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, descriptiveDatas, DescriptiveScope.class); } - @RequestMapping(value={"/descriptive_dictionary/save_descriptive"}, method={RequestMethod.POST}) - public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response)throws IOException{ + @RequestMapping(value = {"/descriptive_dictionary/save_descriptive"}, + method = {RequestMethod.POST}) + public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -91,56 +92,67 @@ public class DescriptiveDictionaryController { DescriptiveScope descriptiveScope; GridData data; String userId = null; - if(fromAPI){ - descriptiveScope = mapper.readValue(root.get("dictionaryFields").toString(), DescriptiveScope.class); + if (fromAPI) { + descriptiveScope = mapper.readValue(root.get("dictionaryFields").toString(), + DescriptiveScope.class); data = mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); userId = "API"; - }else{ - descriptiveScope = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), DescriptiveScope.class); - data = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), GridData.class); + } else { + descriptiveScope = + mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), + DescriptiveScope.class); + data = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), + GridData.class); userId = root.get("userid").textValue(); } descriptiveScope.setSearch(utils.appendKeyValue(data.getAttributes(), "AND", ":")); UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), dScopeName, DescriptiveScope.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + descriptiveScope.getScopeName(), dScopeName, DescriptiveScope.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { DescriptiveScope data1 = (DescriptiveScope) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { descriptiveScope.setId(data1.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data1.getId() != descriptiveScope.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data1.getId() != descriptiveScope.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { descriptiveScope.setUserModifiedBy(userInfo); - if(descriptiveScope.getId() == 0){ + if (descriptiveScope.getId() == 0) { descriptiveScope.setUserCreatedBy(userInfo); commonClassDao.save(descriptiveScope); - }else{ + } else { descriptiveScope.setModifiedDate(new Date()); commonClassDao.update(descriptiveScope); } - responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); + } else { responseString = "Duplicate"; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, descriptiveDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/descriptive_dictionary/remove_descriptiveScope"}, method={RequestMethod.POST}) - public void removeDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/descriptive_dictionary/remove_descriptiveScope"}, + method = {RequestMethod.POST}) + public void removeDescriptiveDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, descriptiveDatas, DescriptiveScope.class); } -} \ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java index 72539880c..94275e7c1 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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,13 +20,14 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; @@ -41,52 +42,51 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class DictionaryController { - private static final Log LOGGER = LogFactory.getLog(DictionaryController.class); + private static final Log LOGGER = LogFactory.getLog(DictionaryController.class); private static CommonClassDao commonClassDao; private static String xacmlId = "xacmlId"; private static String operation = "operation"; - private static String dictionaryFields ="dictionaryFields"; + private static String dictionaryFields = "dictionaryFields"; private static String duplicateResponseString = "Duplicate"; private static String onapName = "onapName"; private static String attributeDatas = "attributeDictionaryDatas"; private static String onapNameDatas = "onapNameDictionaryDatas"; @Autowired - public DictionaryController(CommonClassDao commonClassDao){ + public DictionaryController(CommonClassDao commonClassDao) { DictionaryController.commonClassDao = commonClassDao; } - public DictionaryController(){ + public DictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_AttributeDatabyAttributeName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAttributeDictionaryEntityDatabyAttributeName(HttpServletResponse response){ + @RequestMapping(value = {"/get_AttributeDatabyAttributeName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getAttributeDictionaryEntityDatabyAttributeName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, attributeDatas, xacmlId, Attribute.class); } - //Attribute Dictionary - @RequestMapping(value="/get_AttributeData", method= RequestMethod.GET , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAttributeDictionaryEntityData(HttpServletResponse response){ + // Attribute Dictionary + @RequestMapping(value = "/get_AttributeData", method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getAttributeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, attributeDatas, Attribute.class); } - @RequestMapping(value={"/attribute_dictionary/save_attribute"}, method={RequestMethod.POST}) - public ModelAndView saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/attribute_dictionary/save_attribute"}, method = {RequestMethod.POST}) + public ModelAndView saveAttributeDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -96,84 +96,99 @@ public class DictionaryController { Attribute attributeData = null; AttributeValues attributeValueData = null; String userId = null; - if(fromAPI){ - attributeData = mapper.readValue(root.get(dictionaryFields).toString(), Attribute.class); - attributeValueData = mapper.readValue(root.get(dictionaryFields).toString(), AttributeValues.class); + if (fromAPI) { + attributeData = + mapper.readValue(root.get(dictionaryFields).toString(), Attribute.class); + attributeValueData = mapper.readValue(root.get(dictionaryFields).toString(), + AttributeValues.class); userId = "API"; - }else{ - attributeData = mapper.readValue(root.get("attributeDictionaryData").toString(), Attribute.class); - attributeValueData = mapper.readValue(root.get("attributeDictionaryData").toString(), AttributeValues.class); + } else { + attributeData = mapper.readValue(root.get("attributeDictionaryData").toString(), + Attribute.class); + attributeValueData = mapper.readValue( + root.get("attributeDictionaryData").toString(), AttributeValues.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class); + List duplicateData = commonClassDao + .checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { Attribute data = (Attribute) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { attributeData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != attributeData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != attributeData.getId()))) { duplicateflag = true; } } - if(attributeValueData.getUserDataTypeValues() != null && !attributeValueData.getUserDataTypeValues().isEmpty()){ - attributeData.setAttributeValue(utils.appendKey(attributeValueData.getUserDataTypeValues(), "attributeValues", ",")); + if (attributeValueData.getUserDataTypeValues() != null + && !attributeValueData.getUserDataTypeValues().isEmpty()) { + attributeData.setAttributeValue(utils.appendKey( + attributeValueData.getUserDataTypeValues(), "attributeValues", ",")); } - if(attributeData.getDatatypeBean().getShortName() != null){ + if (attributeData.getDatatypeBean().getShortName() != null) { String datatype = attributeData.getDatatypeBean().getShortName(); attributeData.setDatatypeBean(utils.getDataType(datatype)); } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { attributeData.setUserModifiedBy(userInfo); - if(attributeData.getId() == 0){ + if (attributeData.getId() == 0) { attributeData.setCategoryBean(utils.getCategory()); attributeData.setUserCreatedBy(userInfo); commonClassDao.save(attributeData); - }else{ + } else { attributeData.setModifiedDate(new Date()); commonClassDao.update(attributeData); } responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, attributeDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/attribute_dictionary/remove_attribute"}, method={RequestMethod.POST}) - public void removeAttributeDictionary(HttpServletRequest request, HttpServletResponse response)throws IOException { + @RequestMapping(value = {"/attribute_dictionary/remove_attribute"}, + method = {RequestMethod.POST}) + public void removeAttributeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, attributeDatas, Attribute.class); } - //OnapName Dictionary - @RequestMapping(value={"/get_OnapNameDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getOnapNameDictionaryByNameEntityData(HttpServletResponse response){ + // OnapName Dictionary + @RequestMapping(value = {"/get_OnapNameDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getOnapNameDictionaryByNameEntityData(HttpServletResponse response) { LOGGER.info("get_OnapNameDataByName is called"); DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, onapNameDatas, onapName, OnapName.class); } - @RequestMapping(value={"/get_OnapNameData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getOnapNameDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_OnapNameData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getOnapNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, onapNameDatas, OnapName.class); } - @RequestMapping(value={"/onap_dictionary/save_onapName"}, method={RequestMethod.POST}) - public ModelAndView saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/onap_dictionary/save_onapName"}, method = {RequestMethod.POST}) + public ModelAndView saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -182,59 +197,66 @@ public class DictionaryController { JsonNode root = mapper.readTree(request.getReader()); OnapName onapData; String userId = null; - if(fromAPI){ + if (fromAPI) { onapData = mapper.readValue(root.get(dictionaryFields).toString(), OnapName.class); userId = "API"; - }else{ - onapData = mapper.readValue(root.get("onapNameDictionaryData").toString(), OnapName.class); + } else { + onapData = mapper.readValue(root.get("onapNameDictionaryData").toString(), + OnapName.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getOnapName(), onapName, OnapName.class); + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getOnapName(), + onapName, OnapName.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { OnapName data = (OnapName) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != onapData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != onapData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { onapData.setUserModifiedBy(userInfo); - if(onapData.getId() == 0){ + if (onapData.getId() == 0) { onapData.setUserCreatedBy(userInfo); commonClassDao.save(onapData); - }else{ + } else { onapData.setModifiedDate(new Date()); commonClassDao.update(onapData); } responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, onapNameDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/onap_dictionary/remove_onap"}, method={RequestMethod.POST}) - public void removeOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/onap_dictionary/remove_onap"}, method = {RequestMethod.POST}) + public void removeOnapDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, onapNameDatas, OnapName.class); } } -class AttributeValues{ + +class AttributeValues { private List userDataTypeValues; public List getUserDataTypeValues() { @@ -244,4 +266,4 @@ class AttributeValues{ public void setUserDataTypeValues(List userDataTypeValues) { this.userDataTypeValues = userDataTypeValues; } -} \ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java index 7093cd514..b42731d61 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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,16 +20,17 @@ package org.onap.policy.pap.xacml.rest.controller; +import au.com.bytecode.opencsv.CSVReader; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.compress.utils.IOUtils; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -67,23 +68,18 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - -import au.com.bytecode.opencsv.CSVReader; - @Controller public class DictionaryImportController { - private static final Logger LOGGER = FlexLogger.getLogger(DictionaryImportController.class); + private static final Logger LOGGER = FlexLogger.getLogger(DictionaryImportController.class); private static CommonClassDao commonClassDao; - private static final String DESCRIPTION= "description"; - private static final String ERROR= "Error"; - private static final String DEPENDENCY= "dependency"; + private static final String DESCRIPTION = "description"; + private static final String ERROR = "Error"; + private static final String DEPENDENCY = "dependency"; @Autowired - public DictionaryImportController(CommonClassDao commonClassDao){ + public DictionaryImportController(CommonClassDao commonClassDao) { setCommonClassDao(commonClassDao); } @@ -91,18 +87,19 @@ public class DictionaryImportController { DictionaryImportController.commonClassDao = commonClassDao; } - public DictionaryImportController(){ + public DictionaryImportController() { super(); } - @RequestMapping(value={"/dictionary/import_dictionary"}, method={RequestMethod.POST}) - public void importDictionaryData(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/dictionary/import_dictionary"}, method = {RequestMethod.POST}) + public void importDictionaryData(HttpServletRequest request, HttpServletResponse response) + throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String userId = request.getParameter("userId"); String dictionaryName = request.getParameter("dictionaryName"); - if(dictionaryName == null || dictionaryName.isEmpty()){ + if (dictionaryName == null || dictionaryName.isEmpty()) { LOGGER.error("dictionaryName is null/empty"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write(ERROR); @@ -110,46 +107,49 @@ public class DictionaryImportController { } // fix Fortify Path Manipulation issue - if(!isValidDictionaryName(dictionaryName)){ + if (!isValidDictionaryName(dictionaryName)) { LOGGER.error("dictionaryName is invalid"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write(ERROR); return; } File file = new File(dictionaryName); - try(OutputStream outputStream = new FileOutputStream(file); FileReader fileReader = new FileReader(file.toString())){ + try (OutputStream outputStream = new FileOutputStream(file); + FileReader fileReader = new FileReader(file.toString())) { IOUtils.copy(request.getInputStream(), outputStream); CSVReader csvReader = new CSVReader(fileReader); List dictSheet = csvReader.readAll(); - if(dictionaryName.startsWith("Attribute")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("Attribute")) { + for (int i = 1; i < dictSheet.size(); i++) { Attribute attribute = new Attribute(""); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j duplicateData = commonClassDao.checkDuplicateEntry(prefixList.getPrefixListName(), prefixListName, PrefixList.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + prefixList.getPrefixListName(), prefixListName, PrefixList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PrefixList data = (PrefixList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { prefixList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != prefixList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != prefixList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(prefixList.getId() == 0){ + if (!duplicateflag) { + if (prefixList.getId() == 0) { commonClassDao.save(prefixList); - }else{ + } else { commonClassDao.update(prefixList); } - responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, pfListDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_PrefixList"}, method={RequestMethod.POST}) - public void removePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_PrefixList"}, method = {RequestMethod.POST}) + public void removePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, pfListDatas, PrefixList.class); } - @RequestMapping(value={"/fw_dictionary/validate_prefixList"}, method={RequestMethod.POST}) - public void validatePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/validate_prefixList"}, method = {RequestMethod.POST}) + public void validatePrefixListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - PrefixList prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); + PrefixList prefixList = mapper + .readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); String responseValidation = successMessage; - try{ + try { CIDR.newCIDR(prefixList.getPrefixListValue()); - }catch(UnknownHostException e){ + } catch (UnknownHostException e) { LOGGER.error(e); responseValidation = errorMsg; } @@ -204,20 +214,21 @@ public class FirewallDictionaryController { PrintWriter out = response.getWriter(); JSONObject j = new JSONObject("{result: " + responseValidation + "}"); out.write(j.toString()); - } - catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } } - @RequestMapping(value={"/get_PortListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPortListDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PortListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPortListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, portListDatas, PortList.class); } - @RequestMapping(value={"/fw_dictionary/save_portName"}, method={RequestMethod.POST}) - public ModelAndView savePortListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_portName"}, method = {RequestMethod.POST}) + public ModelAndView savePortListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -225,64 +236,73 @@ public class FirewallDictionaryController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); PortList portList; - if(fromAPI){ + if (fromAPI) { portList = mapper.readValue(root.get(dictionaryFields).toString(), PortList.class); - }else{ - portList = mapper.readValue(root.get("portListDictionaryData").toString(), PortList.class); + } else { + portList = mapper.readValue(root.get("portListDictionaryData").toString(), + PortList.class); } - List duplicateData = commonClassDao.checkDuplicateEntry(portList.getPortName(), "portName", PortList.class); + List duplicateData = commonClassDao.checkDuplicateEntry(portList.getPortName(), + "portName", PortList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PortList data = (PortList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { portList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != portList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != portList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(portList.getId() == 0){ + if (!duplicateflag) { + if (portList.getId() == 0) { commonClassDao.save(portList); - }else{ + } else { commonClassDao.update(portList); } responseString = mapper.writeValueAsString(commonClassDao.getData(PortList.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, portListDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_PortList"}, method={RequestMethod.POST}) - public void removePortListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_PortList"}, method = {RequestMethod.POST}) + public void removePortListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, portListDatas, PortList.class); } - @RequestMapping(value={"/get_ProtocolListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getProtocolListDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ProtocolListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getProtocolListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, protocolListDatas, ProtocolList.class); } - @RequestMapping(value={"/get_ProtocolListDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getProtocolListDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_ProtocolListDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getProtocolListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, protocolListDatas, protocolName, ProtocolList.class); } - @RequestMapping(value={"/fw_dictionary/save_protocolList"}, method={RequestMethod.POST}) - public ModelAndView saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_protocolList"}, method = {RequestMethod.POST}) + public ModelAndView saveProtocolListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -290,64 +310,75 @@ public class FirewallDictionaryController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); ProtocolList protocolList; - if(fromAPI){ - protocolList = mapper.readValue(root.get(dictionaryFields).toString(), ProtocolList.class); - }else{ - protocolList = mapper.readValue(root.get("protocolListDictionaryData").toString(), ProtocolList.class); + if (fromAPI) { + protocolList = + mapper.readValue(root.get(dictionaryFields).toString(), ProtocolList.class); + } else { + protocolList = mapper.readValue(root.get("protocolListDictionaryData").toString(), + ProtocolList.class); } - List duplicateData = commonClassDao.checkDuplicateEntry(protocolList.getProtocolName(), protocolName, ProtocolList.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + protocolList.getProtocolName(), protocolName, ProtocolList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { ProtocolList data = (ProtocolList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { protocolList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != protocolList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != protocolList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(protocolList.getId() == 0){ + if (!duplicateflag) { + if (protocolList.getId() == 0) { commonClassDao.save(protocolList); - }else{ + } else { commonClassDao.update(protocolList); } - responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, protocolListDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_protocol"}, method={RequestMethod.POST}) - public void removeProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_protocol"}, method = {RequestMethod.POST}) + public void removeProtocolListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, protocolListDatas, ProtocolList.class); } - @RequestMapping(value={"/get_AddressGroupDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAddressGroupDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_AddressGroupDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getAddressGroupDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, addressGroupDatas, "name", AddressGroup.class); } - @RequestMapping(value={"/get_AddressGroupData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAddressGroupDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_AddressGroupData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getAddressGroupDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, addressGroupDatas, AddressGroup.class); } - @RequestMapping(value={"/fw_dictionary/save_addressGroup"}, method={RequestMethod.POST}) - public ModelAndView saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_addressGroup"}, method = {RequestMethod.POST}) + public ModelAndView saveAddressGroupDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -356,71 +387,83 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); AddressGroup addressGroup; GridData gridData; - if(fromAPI){ - addressGroup = mapper.readValue(root.get(dictionaryFields).toString(), AddressGroup.class); + if (fromAPI) { + addressGroup = + mapper.readValue(root.get(dictionaryFields).toString(), AddressGroup.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); - }else{ - addressGroup = mapper.readValue(root.get("addressGroupDictionaryData").toString(), AddressGroup.class); - gridData = mapper.readValue(root.get("addressGroupDictionaryData").toString(), GridData.class); + } else { + addressGroup = mapper.readValue(root.get("addressGroupDictionaryData").toString(), + AddressGroup.class); + gridData = mapper.readValue(root.get("addressGroupDictionaryData").toString(), + GridData.class); } - if(!addressGroup.getGroupName().startsWith(groupNameStart)){ - String groupName = groupNameStart+addressGroup.getGroupName(); + if (!addressGroup.getGroupName().startsWith(groupNameStart)) { + String groupName = groupNameStart + addressGroup.getGroupName(); addressGroup.setGroupName(groupName); } addressGroup.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); - List duplicateData = commonClassDao.checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); + List duplicateData = commonClassDao + .checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { AddressGroup data = (AddressGroup) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { addressGroup.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != addressGroup.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != addressGroup.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(addressGroup.getId() == 0){ + if (!duplicateflag) { + if (addressGroup.getId() == 0) { commonClassDao.save(addressGroup); - }else{ + } else { commonClassDao.update(addressGroup); } - responseString = mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, addressGroupDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_AddressGroup"}, method={RequestMethod.POST}) - public void removeAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_AddressGroup"}, method = {RequestMethod.POST}) + public void removeAddressGroupDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, addressGroupDatas, AddressGroup.class); } - @RequestMapping(value={"/get_ActionListDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getActionListDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_ActionListDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getActionListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, actionListDatas, "actionName", ActionList.class); } - @RequestMapping(value={"/get_ActionListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getActionListDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ActionListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getActionListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, actionListDatas, ActionList.class); } - @RequestMapping(value={"/fw_dictionary/save_ActionList"}, method={RequestMethod.POST}) - public ModelAndView saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_ActionList"}, method = {RequestMethod.POST}) + public ModelAndView saveActionListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -429,63 +472,74 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); ActionList actionList; if (fromAPI) { - actionList = mapper.readValue(root.get(dictionaryFields).toString(), ActionList.class); + actionList = + mapper.readValue(root.get(dictionaryFields).toString(), ActionList.class); } else { - actionList = mapper.readValue(root.get("actionListDictionaryData").toString(), ActionList.class); + actionList = mapper.readValue(root.get("actionListDictionaryData").toString(), + ActionList.class); } - List duplicateData = commonClassDao.checkDuplicateEntry(actionList.getActionName(), "actionName", ActionList.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + actionList.getActionName(), "actionName", ActionList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { ActionList data = (ActionList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { actionList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != actionList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != actionList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(actionList.getId() == 0){ + if (!duplicateflag) { + if (actionList.getId() == 0) { commonClassDao.save(actionList); - }else{ + } else { commonClassDao.update(actionList); } - responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, actionListDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_ActionList"}, method={RequestMethod.POST}) - public void removeActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_ActionList"}, method = {RequestMethod.POST}) + public void removeActionListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, actionListDatas, ActionList.class); } - @RequestMapping(value={"/get_ServiceGroupData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getServiceGroupDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ServiceGroupData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getServiceGroupDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, serviceGroupDatas, GroupServiceList.class); } - @RequestMapping(value={"/get_ServiceGroupDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getServiceGroupDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_ServiceGroupDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getServiceGroupDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, serviceGroupDatas, "name", GroupServiceList.class); } - @RequestMapping(value={"/fw_dictionary/save_serviceGroup"}, method={RequestMethod.POST}) - public ModelAndView saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_serviceGroup"}, method = {RequestMethod.POST}) + public ModelAndView saveServiceGroupDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -494,71 +548,83 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); GroupServiceList groupServiceList; GridData gridData; - if(fromAPI){ - groupServiceList = mapper.readValue(root.get(dictionaryFields).toString(), GroupServiceList.class); + if (fromAPI) { + groupServiceList = mapper.readValue(root.get(dictionaryFields).toString(), + GroupServiceList.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); - }else{ - groupServiceList = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class); - gridData = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GridData.class); + } else { + groupServiceList = mapper.readValue( + root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class); + gridData = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), + GridData.class); } - if(!groupServiceList.getGroupName().startsWith(groupNameStart)){ - String groupName = groupNameStart+groupServiceList.getGroupName(); + if (!groupServiceList.getGroupName().startsWith(groupNameStart)) { + String groupName = groupNameStart + groupServiceList.getGroupName(); groupServiceList.setGroupName(groupName); } groupServiceList.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); - List duplicateData = commonClassDao.checkDuplicateEntry(groupServiceList.getGroupName(), "name", GroupServiceList.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + groupServiceList.getGroupName(), "name", GroupServiceList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { GroupServiceList data = (GroupServiceList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { groupServiceList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != groupServiceList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != groupServiceList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(groupServiceList.getId() == 0){ + if (!duplicateflag) { + if (groupServiceList.getId() == 0) { commonClassDao.save(groupServiceList); - }else{ + } else { commonClassDao.update(groupServiceList); } - responseString = mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, serviceGroupDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_serviceGroup"}, method={RequestMethod.POST}) - public void removeServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_serviceGroup"}, method = {RequestMethod.POST}) + public void removeServiceGroupDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, serviceGroupDatas, GroupServiceList.class); } - @RequestMapping(value={"/get_SecurityZoneDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSecurityZoneDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_SecurityZoneDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getSecurityZoneDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, securityZoneDatas, zoneName, SecurityZone.class); } - @RequestMapping(value={"/get_SecurityZoneData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSecurityZoneDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_SecurityZoneData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getSecurityZoneDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, securityZoneDatas, SecurityZone.class); } - @RequestMapping(value={"/fw_dictionary/save_securityZone"}, method={RequestMethod.POST}) - public ModelAndView saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_securityZone"}, method = {RequestMethod.POST}) + public ModelAndView saveSecurityZoneDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -566,65 +632,76 @@ public class FirewallDictionaryController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); SecurityZone securityZone; - if(fromAPI){ - securityZone = mapper.readValue(root.get(dictionaryFields).toString(), SecurityZone.class); - }else{ - securityZone = mapper.readValue(root.get("securityZoneDictionaryData").toString(), SecurityZone.class); + if (fromAPI) { + securityZone = + mapper.readValue(root.get(dictionaryFields).toString(), SecurityZone.class); + } else { + securityZone = mapper.readValue(root.get("securityZoneDictionaryData").toString(), + SecurityZone.class); } - List duplicateData = commonClassDao.checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class); + List duplicateData = commonClassDao + .checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { SecurityZone data = (SecurityZone) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { securityZone.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != securityZone.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != securityZone.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(securityZone.getId() == 0){ + if (!duplicateflag) { + if (securityZone.getId() == 0) { commonClassDao.save(securityZone); - }else{ + } else { commonClassDao.update(securityZone); } - responseString = mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, securityZoneDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_securityZone"}, method={RequestMethod.POST}) - public void removeSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/fw_dictionary/remove_securityZone"}, method = {RequestMethod.POST}) + public void removeSecurityZoneDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, securityZoneDatas, SecurityZone.class); } - @RequestMapping(value={"/get_ServiceListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getServiceListDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ServiceListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getServiceListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, serviceListDatas, ServiceList.class); } - @RequestMapping(value={"/get_ServiceListDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getServiceListDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_ServiceListDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getServiceListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, serviceListDatas, serviceName, ServiceList.class); } - @RequestMapping(value={"/fw_dictionary/save_serviceList"}, method={RequestMethod.POST}) - public ModelAndView saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_serviceList"}, method = {RequestMethod.POST}) + public ModelAndView saveServiceListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -633,69 +710,84 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); ServiceList serviceList; GridData serviceListGridData; - if(fromAPI){ - serviceList = mapper.readValue(root.get(dictionaryFields).toString(), ServiceList.class); - serviceListGridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); - }else{ - serviceList = mapper.readValue(root.get("serviceListDictionaryData").toString(), ServiceList.class); - serviceListGridData = mapper.readValue(root.get("serviceListDictionaryData").toString(), GridData.class); + if (fromAPI) { + serviceList = + mapper.readValue(root.get(dictionaryFields).toString(), ServiceList.class); + serviceListGridData = + mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); + } else { + serviceList = mapper.readValue(root.get("serviceListDictionaryData").toString(), + ServiceList.class); + serviceListGridData = mapper.readValue( + root.get("serviceListDictionaryData").toString(), GridData.class); } - serviceList.setServiceTransProtocol(utils.appendKey(serviceListGridData.getTransportProtocols(), option, ",")); - serviceList.setServiceAppProtocol(utils.appendKey(serviceListGridData.getAppProtocols(), option, ",")); + serviceList.setServiceTransProtocol( + utils.appendKey(serviceListGridData.getTransportProtocols(), option, ",")); + serviceList.setServiceAppProtocol( + utils.appendKey(serviceListGridData.getAppProtocols(), option, ",")); serviceList.setServiceType("SERVICE"); - List duplicateData = commonClassDao.checkDuplicateEntry(serviceList.getServiceName(), serviceName, ServiceList.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + serviceList.getServiceName(), serviceName, ServiceList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { ServiceList data = (ServiceList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { serviceList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != serviceList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != serviceList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(serviceList.getId() == 0){ + if (!duplicateflag) { + if (serviceList.getId() == 0) { commonClassDao.save(serviceList); - }else{ + } else { commonClassDao.update(serviceList); } - responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, serviceListDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_serviceList"}, method={RequestMethod.POST}) - public void removeServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/fw_dictionary/remove_serviceList"}, method = {RequestMethod.POST}) + public void removeServiceListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, serviceListDatas, ServiceList.class); } - @RequestMapping(value={"/get_ZoneData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getZoneDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ZoneData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getZoneDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, zoneDatas, Zone.class); } - @RequestMapping(value={"/get_ZoneDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getZoneDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_ZoneDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getZoneDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, zoneDatas, zoneName, Zone.class); } - @RequestMapping(value={"/fw_dictionary/save_zoneName"}, method={RequestMethod.POST}) - public ModelAndView saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_zoneName"}, method = {RequestMethod.POST}) + public ModelAndView saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -708,59 +800,67 @@ public class FirewallDictionaryController { } else { zone = mapper.readValue(root.get("zoneDictionaryData").toString(), Zone.class); } - List duplicateData = commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class); + List duplicateData = + commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { Zone data = (Zone) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { zone.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != zone.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != zone.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(zone.getId() == 0){ + if (!duplicateflag) { + if (zone.getId() == 0) { commonClassDao.save(zone); - }else{ + } else { commonClassDao.update(zone); } responseString = mapper.writeValueAsString(commonClassDao.getData(Zone.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, zoneDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_zone"}, method={RequestMethod.POST}) - public void removeZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_zone"}, method = {RequestMethod.POST}) + public void removeZoneDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, zoneDatas, Zone.class); } - @RequestMapping(value={"/get_TermListDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTermListDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_TermListDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getTermListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, termListDictDatas, termName, TermList.class); } - @RequestMapping(value={"/get_TermListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTermListDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_TermListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getTermListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, termListDictDatas, TermList.class); } - @RequestMapping(value={"/fw_dictionary/save_termList"}, method={RequestMethod.POST}) - public ModelAndView saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_termList"}, method = {RequestMethod.POST}) + public ModelAndView saveTermListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -770,82 +870,97 @@ public class FirewallDictionaryController { TermList termList; TermListData termListDatas; String userId = null; - if(fromAPI){ + if (fromAPI) { termList = mapper.readValue(root.get(dictionaryFields).toString(), TermList.class); - termListDatas = mapper.readValue(root.get(dictionaryFields).toString(), TermListData.class); + termListDatas = + mapper.readValue(root.get(dictionaryFields).toString(), TermListData.class); userId = "API"; - }else{ - termList = mapper.readValue(root.get("termListDictionaryData").toString(), TermList.class); - termListDatas = mapper.readValue(root.get("termListDictionaryData").toString(), TermListData.class); + } else { + termList = mapper.readValue(root.get("termListDictionaryData").toString(), + TermList.class); + termListDatas = mapper.readValue(root.get("termListDictionaryData").toString(), + TermListData.class); userId = root.get(userid).textValue(); } termList.setFromZones(utils.appendKey(termListDatas.getFromZoneDatas(), option, ",")); termList.setToZones(utils.appendKey(termListDatas.getToZoneDatas(), option, ",")); termList.setSrcIPList(utils.appendKey(termListDatas.getSourceListDatas(), option, ",")); - termList.setDestIPList(utils.appendKey(termListDatas.getDestinationListDatas(), option, ",")); - termList.setSrcPortList(utils.appendKey(termListDatas.getSourceServiceDatas(), option, ",")); - termList.setDestPortList(utils.appendKey(termListDatas.getDestinationServiceDatas(), option, ",")); + termList.setDestIPList( + utils.appendKey(termListDatas.getDestinationListDatas(), option, ",")); + termList.setSrcPortList( + utils.appendKey(termListDatas.getSourceServiceDatas(), option, ",")); + termList.setDestPortList( + utils.appendKey(termListDatas.getDestinationServiceDatas(), option, ",")); termList.setAction(utils.appendKey(termListDatas.getActionListDatas(), option, ",")); UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), termName, TermList.class); + List duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), + termName, TermList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { TermList data = (TermList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { termList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != termList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != termList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { termList.setUserModifiedBy(userInfo); - if(termList.getId() == 0){ + if (termList.getId() == 0) { termList.setUserCreatedBy(userInfo); commonClassDao.save(termList); - }else{ + } else { termList.setModifiedDate(new Date()); commonClassDao.update(termList); } responseString = mapper.writeValueAsString(commonClassDao.getData(TermList.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, termListDictDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_termList"}, method={RequestMethod.POST}) - public void removeTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_termList"}, method = {RequestMethod.POST}) + public void removeTermListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, termListDictDatas, TermList.class); } - //ParentList Dictionary Data - @RequestMapping(value={"/get_FWDictionaryListDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getFWDictListDictionaryEntityDataByName(HttpServletResponse response){ + // ParentList Dictionary Data + @RequestMapping(value = {"/get_FWDictionaryListDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getFWDictListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, fwDictListDatas, "parentItemName", FirewallDictionaryList.class); + utils.getDataByEntity(response, fwDictListDatas, "parentItemName", + FirewallDictionaryList.class); } - @RequestMapping(value={"/get_FWDictionaryListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getFWDictionaryListEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_FWDictionaryListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getFWDictionaryListEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, fwDictListDatas, FirewallDictionaryList.class); } - @RequestMapping(value={"/fw_dictionary/save_FWDictionaryList"}, method={RequestMethod.POST}) - public ModelAndView saveFWDictionaryList(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_FWDictionaryList"}, method = {RequestMethod.POST}) + public ModelAndView saveFWDictionaryList(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -855,71 +970,83 @@ public class FirewallDictionaryController { FirewallDictionaryList fwDictList; GridData gridData; if (fromAPI) { - fwDictList = mapper.readValue(root.get(dictionaryFields).toString(), FirewallDictionaryList.class); + fwDictList = mapper.readValue(root.get(dictionaryFields).toString(), + FirewallDictionaryList.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); } else { - fwDictList = mapper.readValue(root.get("fwDictListDictionaryData").toString(), FirewallDictionaryList.class); - gridData = mapper.readValue(root.get("fwDictListDictionaryData").toString(), GridData.class); + fwDictList = mapper.readValue(root.get("fwDictListDictionaryData").toString(), + FirewallDictionaryList.class); + gridData = mapper.readValue(root.get("fwDictListDictionaryData").toString(), + GridData.class); } fwDictList.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); fwDictList.setAddressList(utils.appendKey(gridData.getAlAttributes(), option, ",")); - List duplicateData = commonClassDao.checkDuplicateEntry(fwDictList.getParentItemName(), "parentItemName", FirewallDictionaryList.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + fwDictList.getParentItemName(), "parentItemName", FirewallDictionaryList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { FirewallDictionaryList data = (FirewallDictionaryList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { fwDictList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != fwDictList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != fwDictList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(fwDictList.getId() == 0){ + if (!duplicateflag) { + if (fwDictList.getId() == 0) { commonClassDao.save(fwDictList); - }else{ + } else { commonClassDao.update(fwDictList); } - responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); - }else{ + responseString = mapper + .writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, fwDictListDatas, responseString); } - } - catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_FWDictionaryList"}, method={RequestMethod.POST}) - public void removeFWDictionaryList(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/fw_dictionary/remove_FWDictionaryList"}, + method = {RequestMethod.POST}) + public void removeFWDictionaryList(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, fwDictListDatas, FirewallDictionaryList.class); } - @RequestMapping(value={"/get_TagPickerNameByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTagPickerNameEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_TagPickerNameByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getTagPickerNameEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, fwTagPickerDatas, tagPickerName, FWTagPicker.class); } - @RequestMapping(value={"/get_TagPickerListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTagPickerDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_TagPickerListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getTagPickerDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, fwTagPickerDatas, FWTagPicker.class); } - @RequestMapping(value={"/fw_dictionary/save_fwTagPicker"}, method={RequestMethod.POST}) - public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_fwTagPicker"}, method = {RequestMethod.POST}) + public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -930,76 +1057,87 @@ public class FirewallDictionaryController { TagGridValues data; String userId = ""; if (fromAPI) { - fwTagPicker = mapper.readValue(root.get(dictionaryFields).toString(), FWTagPicker.class); + fwTagPicker = + mapper.readValue(root.get(dictionaryFields).toString(), FWTagPicker.class); data = mapper.readValue(root.get(dictionaryFields).toString(), TagGridValues.class); userId = "API"; } else { - fwTagPicker = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), FWTagPicker.class); - data = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), TagGridValues.class); + fwTagPicker = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), + FWTagPicker.class); + data = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), + TagGridValues.class); userId = root.get(userid).textValue(); } fwTagPicker.setTagValues(utils.appendKeyValue(data.getTags(), "#", ":")); UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(fwTagPicker.getTagPickerName(), tagPickerName, FWTagPicker.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + fwTagPicker.getTagPickerName(), tagPickerName, FWTagPicker.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { FWTagPicker data1 = (FWTagPicker) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { fwTagPicker.setId(data1.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data1.getId() != fwTagPicker.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data1.getId() != fwTagPicker.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { fwTagPicker.setUserModifiedBy(userInfo); - if(fwTagPicker.getId() == 0){ + if (fwTagPicker.getId() == 0) { fwTagPicker.setUserCreatedBy(userInfo); commonClassDao.save(fwTagPicker); - }else{ + } else { fwTagPicker.setModifiedDate(new Date()); commonClassDao.update(fwTagPicker); } - responseString = mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, fwTagPickerDatas, responseString); } - } - catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_tagPicker"}, method={RequestMethod.POST}) - public void removeFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/fw_dictionary/remove_tagPicker"}, method = {RequestMethod.POST}) + public void removeFirewallTagPickerDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, fwTagPickerDatas, FWTagPicker.class); } - @RequestMapping(value={"/get_TagListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTagDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_TagListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getTagDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, fwTagDatas, FWTag.class); } - @RequestMapping(value={"/get_TagNameByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTagNameEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_TagNameByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getTagNameEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, fwTagDatas, "fwTagName", FWTag.class); } - @RequestMapping(value={"/fw_dictionary/save_fwTag"}, method={RequestMethod.POST}) - public ModelAndView saveFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_fwTag"}, method = {RequestMethod.POST}) + public ModelAndView saveFirewallTagDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -1008,64 +1146,71 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); FWTag fwTag; TagGridValues tagGridValues; - String userId=""; - if(fromAPI){ + String userId = ""; + if (fromAPI) { fwTag = mapper.readValue(root.get(dictionaryFields).toString(), FWTag.class); - tagGridValues = mapper.readValue(root.get(dictionaryFields).toString(), TagGridValues.class); + tagGridValues = mapper.readValue(root.get(dictionaryFields).toString(), + TagGridValues.class); userId = "API"; - }else{ + } else { fwTag = mapper.readValue(root.get("fwTagDictionaryData").toString(), FWTag.class); - tagGridValues = mapper.readValue(root.get("fwTagDictionaryData").toString(), TagGridValues.class); + tagGridValues = mapper.readValue(root.get("fwTagDictionaryData").toString(), + TagGridValues.class); userId = root.get(userid).textValue(); } fwTag.setTagValues(utils.appendKey(tagGridValues.getTags(), "tags", ",")); UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), "fwTagName", FWTag.class); + List duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), + "fwTagName", FWTag.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { FWTag data = (FWTag) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { fwTag.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != fwTag.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != fwTag.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { fwTag.setUserModifiedBy(userInfo); - if(fwTag.getId() == 0){ + if (fwTag.getId() == 0) { fwTag.setUserCreatedBy(userInfo); commonClassDao.save(fwTag); - }else{ + } else { fwTag.setModifiedDate(new Date()); commonClassDao.update(fwTag); } responseString = mapper.writeValueAsString(commonClassDao.getData(FWTag.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, fwTagDatas, responseString); } - } - catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_tagList"}, method={RequestMethod.POST}) - public void removeFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_tagList"}, method = {RequestMethod.POST}) + public void removeFirewallTagDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, fwTagDatas, FWTag.class); } } -class TagGridValues{ + +class TagGridValues { private List tags; public List getTags() { @@ -1077,7 +1222,8 @@ class TagGridValues{ } } -class AGGridData{ + +class AGGridData { private List attributes; public List getAttributes() { @@ -1089,7 +1235,8 @@ class AGGridData{ } } -class TermListData{ + +class TermListData { private List fromZoneDatas; private List toZoneDatas; private List sourceListDatas; @@ -1097,46 +1244,60 @@ class TermListData{ private List sourceServiceDatas; private List destinationServiceDatas; private List actionListDatas; + public List getFromZoneDatas() { return fromZoneDatas; } + public void setFromZoneDatas(List fromZoneDatas) { this.fromZoneDatas = fromZoneDatas; } + public List getToZoneDatas() { return toZoneDatas; } + public void setToZoneDatas(List toZoneDatas) { this.toZoneDatas = toZoneDatas; } + public List getSourceListDatas() { return sourceListDatas; } + public void setSourceListDatas(List sourceListDatas) { this.sourceListDatas = sourceListDatas; } + public List getDestinationListDatas() { return destinationListDatas; } + public void setDestinationListDatas(List destinationListDatas) { this.destinationListDatas = destinationListDatas; } + public List getSourceServiceDatas() { return sourceServiceDatas; } + public void setSourceServiceDatas(List sourceServiceDatas) { this.sourceServiceDatas = sourceServiceDatas; } + public List getDestinationServiceDatas() { return destinationServiceDatas; } + public void setDestinationServiceDatas(List destinationServiceDatas) { this.destinationServiceDatas = destinationServiceDatas; } + public List getActionListDatas() { return actionListDatas; } + public void setActionListDatas(List actionListDatas) { this.actionListDatas = actionListDatas; } -} \ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java index 965235cce..c0e7729db 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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,13 +20,14 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.lang.StringUtils; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -45,19 +46,16 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class PolicyScopeDictionaryController { - private static final Logger LOGGER = FlexLogger.getLogger(PolicyScopeDictionaryController.class); + private static final Logger LOGGER = + FlexLogger.getLogger(PolicyScopeDictionaryController.class); private static CommonClassDao commonClassDao; private static String operation = "operation"; private static String groupPolicyScopeListData1 = "groupPolicyScopeListData1"; - private static String policyScope= "PolicyScope"; + private static String policyScope = "PolicyScope"; private static String duplicateResponseString = "Duplicate"; private static String groupPolicyScopeDatas = "groupPolicyScopeListDatas"; private static String dictionaryFields = "dictionaryFields"; @@ -66,37 +64,41 @@ public class PolicyScopeDictionaryController { private static String psTypeDatas = "psTypeDictionaryDatas"; private static String psResourceDatas = "psResourceDictionaryDatas"; - public PolicyScopeDictionaryController(){ + public PolicyScopeDictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } @Autowired - public PolicyScopeDictionaryController(CommonClassDao commonClassDao){ + public PolicyScopeDictionaryController(CommonClassDao commonClassDao) { PolicyScopeDictionaryController.commonClassDao = commonClassDao; } - public void setCommonClassDao(CommonClassDao commonClassDao){ + public void setCommonClassDao(CommonClassDao commonClassDao) { PolicyScopeDictionaryController.commonClassDao = commonClassDao; } - @RequestMapping(value={"/get_GroupPolicyScopeDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getGroupPolicyScopeEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_GroupPolicyScopeDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getGroupPolicyScopeEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, groupPolicyScopeDatas, "name", GroupPolicyScopeList.class); } - @RequestMapping(value={"/get_GroupPolicyScopeData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getGroupPolicyScopeEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_GroupPolicyScopeData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getGroupPolicyScopeEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, groupPolicyScopeDatas, GroupPolicyScopeList.class); } - @RequestMapping(value={"/ps_dictionary/save_psGroupPolicyScope"}, method={RequestMethod.POST}) - public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/ps_dictionary/save_psGroupPolicyScope"}, + method = {RequestMethod.POST}) + public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -107,31 +109,43 @@ public class PolicyScopeDictionaryController { GroupPolicyScope groupData = null; boolean duplicateGroupFlag = false; if (fromAPI) { - gpdata = mapper.readValue(root.get(dictionaryFields).toString(), GroupPolicyScopeList.class); - try{ - groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), GroupPolicyScope.class); - }catch(Exception e){ + gpdata = mapper.readValue(root.get(dictionaryFields).toString(), + GroupPolicyScopeList.class); + try { + groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), + GroupPolicyScope.class); + } catch (Exception e) { groupData = new GroupPolicyScope(); - groupData.setResource(root.get(dictionaryFields).get("resource").toString().replace("\"", "")); - groupData.setClosedloop(root.get(dictionaryFields).get("closedloop").toString().replace("\"", "")); - groupData.setService(root.get(dictionaryFields).get("service").toString().replace("\"", "")); - groupData.setType(root.get(dictionaryFields).get("type").toString().replace("\"", "")); + groupData.setResource(root.get(dictionaryFields).get("resource").toString() + .replace("\"", "")); + groupData.setClosedloop(root.get(dictionaryFields).get("closedloop").toString() + .replace("\"", "")); + groupData.setService( + root.get(dictionaryFields).get("service").toString().replace("\"", "")); + groupData.setType( + root.get(dictionaryFields).get("type").toString().replace("\"", "")); LOGGER.error(e); } } else { - gpdata = mapper.readValue(root.get("groupPolicyScopeListData").toString(), GroupPolicyScopeList.class); - try{ - groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), GroupPolicyScope.class); - }catch(Exception e){ + gpdata = mapper.readValue(root.get("groupPolicyScopeListData").toString(), + GroupPolicyScopeList.class); + try { + groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), + GroupPolicyScope.class); + } catch (Exception e) { LOGGER.error(e); groupData = new GroupPolicyScope(); - groupData.setResource(root.get(groupPolicyScopeListData1).get("resource").toString().replace("\"", "")); - groupData.setClosedloop(root.get(groupPolicyScopeListData1).get("closedloop").toString().replace("\"", "")); - groupData.setService(root.get(groupPolicyScopeListData1).get("service").toString().replace("\"", "")); - groupData.setType(root.get(groupPolicyScopeListData1).get("type").toString().replace("\"", "")); + groupData.setResource(root.get(groupPolicyScopeListData1).get("resource") + .toString().replace("\"", "")); + groupData.setClosedloop(root.get(groupPolicyScopeListData1).get("closedloop") + .toString().replace("\"", "")); + groupData.setService(root.get(groupPolicyScopeListData1).get("service") + .toString().replace("\"", "")); + groupData.setType(root.get(groupPolicyScopeListData1).get("type").toString() + .replace("\"", "")); } } - if(!gpdata.getGroupName().startsWith(policyScope)){ + if (!gpdata.getGroupName().startsWith(policyScope)) { String name = "PolicyScope_" + gpdata.getGroupName(); gpdata.setGroupName(name); } @@ -143,71 +157,83 @@ public class PolicyScopeDictionaryController { valueList.add("resource=" + resourceValue); valueList.add("service=" + serviceValue); valueList.add("type=" + typeValue); - valueList.add("closedLoopControlName=" + closedLoopValue); - String list = StringUtils.replaceEach(valueList.toString(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); + valueList.add("closedLoopControlName=" + closedLoopValue); + String list = StringUtils.replaceEach(valueList.toString(), + new String[] {"[", "]", " "}, new String[] {"", "", ""}); gpdata.setGroupList(list); - List duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), "name", GroupPolicyScopeList.class); - if(duplicateData.isEmpty()){ - duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(), "groupList", GroupPolicyScopeList.class); - if(duplicateData.isEmpty()){ + List duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), + "name", GroupPolicyScopeList.class); + if (duplicateData.isEmpty()) { + duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(), + "groupList", GroupPolicyScopeList.class); + if (duplicateData.isEmpty()) { duplicateGroupFlag = true; } } boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { GroupPolicyScopeList data = (GroupPolicyScopeList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { gpdata.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != gpdata.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != gpdata.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag && !duplicateGroupFlag){ - if(gpdata.getId() == 0){ + if (!duplicateflag && !duplicateGroupFlag) { + if (gpdata.getId() == 0) { commonClassDao.save(gpdata); - }else{ + } else { commonClassDao.update(gpdata); } - responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); - }else if(duplicateGroupFlag){ + responseString = mapper + .writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); + } else if (duplicateGroupFlag) { responseString = "DuplicateGroup"; - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, groupPolicyScopeDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_GroupPolicyScope"}, method={RequestMethod.POST}) - public void removePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/ps_dictionary/remove_GroupPolicyScope"}, + method = {RequestMethod.POST}) + public void removePSGroupScopeDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, groupPolicyScopeDatas, GroupPolicyScopeList.class); } - @RequestMapping(value={"/get_PSClosedLoopDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSClosedLoopEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSClosedLoopDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSClosedLoopEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psCLDatas, "name", OnapName.class); } - @RequestMapping(value={"/get_PSClosedLoopData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSClosedLoopEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSClosedLoopData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSClosedLoopEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, psCLDatas, PolicyScopeClosedLoop.class); } - @RequestMapping(value={"/ps_dictionary/save_psClosedLoop"}, method={RequestMethod.POST}) - public ModelAndView savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/ps_dictionary/save_psClosedLoop"}, method = {RequestMethod.POST}) + public ModelAndView savePSClosedLoopDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -215,65 +241,76 @@ public class PolicyScopeDictionaryController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); PolicyScopeClosedLoop onapData; - if(fromAPI){ - onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeClosedLoop.class); - }else{ - onapData = mapper.readValue(root.get("psClosedLoopDictionaryData").toString(), PolicyScopeClosedLoop.class); + if (fromAPI) { + onapData = mapper.readValue(root.get(dictionaryFields).toString(), + PolicyScopeClosedLoop.class); + } else { + onapData = mapper.readValue(root.get("psClosedLoopDictionaryData").toString(), + PolicyScopeClosedLoop.class); } - List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeClosedLoop.class); + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), + "name", PolicyScopeClosedLoop.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PolicyScopeClosedLoop data = (PolicyScopeClosedLoop) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != onapData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != onapData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(onapData.getId() == 0){ + if (!duplicateflag) { + if (onapData.getId() == 0) { commonClassDao.save(onapData); - }else{ + } else { commonClassDao.update(onapData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); - }else{ + responseString = mapper + .writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, psCLDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_PSClosedLoop"}, method={RequestMethod.POST}) - public void removePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/ps_dictionary/remove_PSClosedLoop"}, method = {RequestMethod.POST}) + public void removePSClosedLoopDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psCLDatas, PolicyScopeClosedLoop.class); } - @RequestMapping(value={"/get_PSServiceDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSServiceEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSServiceDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSServiceEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psServiceDatas, "name", PolicyScopeService.class); } - @RequestMapping(value={"/get_PSServiceData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSServiceEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSServiceData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSServiceEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, psServiceDatas, PolicyScopeService.class); } - @RequestMapping(value={"/ps_dictionary/save_psService"}, method={RequestMethod.POST}) - public ModelAndView savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/ps_dictionary/save_psService"}, method = {RequestMethod.POST}) + public ModelAndView savePSServiceDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -282,64 +319,75 @@ public class PolicyScopeDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PolicyScopeService onapData; if (fromAPI) { - onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeService.class); + onapData = mapper.readValue(root.get(dictionaryFields).toString(), + PolicyScopeService.class); } else { - onapData = mapper.readValue(root.get("psServiceDictionaryData").toString(), PolicyScopeService.class); + onapData = mapper.readValue(root.get("psServiceDictionaryData").toString(), + PolicyScopeService.class); } - List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeService.class); + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), + "name", PolicyScopeService.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PolicyScopeService data = (PolicyScopeService) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != onapData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != onapData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(onapData.getId() == 0){ + if (!duplicateflag) { + if (onapData.getId() == 0) { commonClassDao.save(onapData); - }else{ + } else { commonClassDao.update(onapData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, psServiceDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_PSService"}, method={RequestMethod.POST}) - public void removePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/ps_dictionary/remove_PSService"}, method = {RequestMethod.POST}) + public void removePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psServiceDatas, PolicyScopeService.class); } - @RequestMapping(value={"/get_PSTypeDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSTypeEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSTypeDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSTypeEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psTypeDatas, "name", PolicyScopeType.class); } - @RequestMapping(value={"/get_PSTypeData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSTypeEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSTypeData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSTypeEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, psTypeDatas, PolicyScopeType.class); } - @RequestMapping(value={"/ps_dictionary/save_psType"}, method={RequestMethod.POST}) - public ModelAndView savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/ps_dictionary/save_psType"}, method = {RequestMethod.POST}) + public ModelAndView savePSTypeDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -347,65 +395,76 @@ public class PolicyScopeDictionaryController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); PolicyScopeType onapData; - if(fromAPI){ - onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeType.class); - }else{ - onapData = mapper.readValue(root.get("psTypeDictionaryData").toString(), PolicyScopeType.class); + if (fromAPI) { + onapData = mapper.readValue(root.get(dictionaryFields).toString(), + PolicyScopeType.class); + } else { + onapData = mapper.readValue(root.get("psTypeDictionaryData").toString(), + PolicyScopeType.class); } - List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeType.class); + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), + "name", PolicyScopeType.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PolicyScopeType data = (PolicyScopeType) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != onapData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != onapData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(onapData.getId() == 0){ + if (!duplicateflag) { + if (onapData.getId() == 0) { commonClassDao.save(onapData); - }else{ + } else { commonClassDao.update(onapData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, psTypeDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_PSType"}, method={RequestMethod.POST}) - public void removePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/ps_dictionary/remove_PSType"}, method = {RequestMethod.POST}) + public void removePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psTypeDatas, PolicyScopeType.class); } - @RequestMapping(value={"/get_PSResourceDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSResourceEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSResourceDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSResourceEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psResourceDatas, "name", PolicyScopeResource.class); } - @RequestMapping(value={"/get_PSResourceData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSResourceEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSResourceData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSResourceEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, psResourceDatas, PolicyScopeResource.class); } - @RequestMapping(value={"/ps_dictionary/save_psResource"}, method={RequestMethod.POST}) - public ModelAndView savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/ps_dictionary/save_psResource"}, method = {RequestMethod.POST}) + public ModelAndView savePSResourceDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -414,77 +473,94 @@ public class PolicyScopeDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PolicyScopeResource onapData; if (fromAPI) { - onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeResource.class); + onapData = mapper.readValue(root.get(dictionaryFields).toString(), + PolicyScopeResource.class); } else { - onapData = mapper.readValue(root.get("psResourceDictionaryData").toString(), PolicyScopeResource.class); + onapData = mapper.readValue(root.get("psResourceDictionaryData").toString(), + PolicyScopeResource.class); } - List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeResource.class); + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), + "name", PolicyScopeResource.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PolicyScopeResource data = (PolicyScopeResource) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != onapData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != onapData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(onapData.getId() == 0){ + if (!duplicateflag) { + if (onapData.getId() == 0) { commonClassDao.save(onapData); - }else{ + } else { commonClassDao.update(onapData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); - }else{ + responseString = mapper + .writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, psResourceDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_PSResource"}, method={RequestMethod.POST}) - public void removePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/ps_dictionary/remove_PSResource"}, method = {RequestMethod.POST}) + public void removePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psResourceDatas, PolicyScopeResource.class); } } -class GroupPolicyScope{ + +class GroupPolicyScope { String resource; String type; String service; String closedloop; + public String getResource() { return resource; } + public void setResource(String resource) { this.resource = resource; } + public String getType() { return type; } + public void setType(String type) { this.type = type; } + public String getService() { return service; } + public void setService(String service) { this.service = service; } + public String getClosedloop() { return closedloop; } + public void setClosedloop(String closedloop) { this.closedloop = closedloop; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java index fe49e3478..6e794d966 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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,13 +20,14 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.RiskType; @@ -39,10 +40,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class SafePolicyController { @@ -53,36 +50,39 @@ public class SafePolicyController { private static String safePolicyWarningDatas = "safePolicyWarningDatas"; @Autowired - public SafePolicyController(CommonClassDao commonClassDao){ + public SafePolicyController(CommonClassDao commonClassDao) { SafePolicyController.commonClassDao = commonClassDao; } - public void setCommonClassDao(CommonClassDao commonClassDao){ + public void setCommonClassDao(CommonClassDao commonClassDao) { SafePolicyController.commonClassDao = commonClassDao; } - public SafePolicyController(){ + public SafePolicyController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = { "/get_RiskTypeDataByName" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = {"/get_RiskTypeDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) public void getRiskTypeDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, riskTypeDatas, "name", RiskType.class); } - @RequestMapping(value = { "/get_RiskTypeData" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = {"/get_RiskTypeData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) public void getRiskTypeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, riskTypeDatas, RiskType.class); } - @RequestMapping(value = { "/sp_dictionary/save_riskType" }, method = {RequestMethod.POST }) - public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/sp_dictionary/save_riskType"}, method = {RequestMethod.POST}) + public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -92,69 +92,80 @@ public class SafePolicyController { RiskType riskTypeData; String userId = null; if (fromAPI) { - riskTypeData = mapper.readValue(root.get("dictionaryFields").toString(), RiskType.class); + riskTypeData = + mapper.readValue(root.get("dictionaryFields").toString(), RiskType.class); userId = "API"; } else { - riskTypeData = mapper.readValue(root.get("riskTypeDictionaryData").toString(), RiskType.class); + riskTypeData = mapper.readValue(root.get("riskTypeDictionaryData").toString(), + RiskType.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List duplicateData = commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); + List duplicateData = commonClassDao + .checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { RiskType data = (RiskType) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { riskTypeData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != riskTypeData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != riskTypeData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { riskTypeData.setUserModifiedBy(userInfo); - if(riskTypeData.getId() == 0){ + if (riskTypeData.getId() == 0) { riskTypeData.setUserCreatedBy(userInfo); commonClassDao.save(riskTypeData); - }else{ + } else { riskTypeData.setModifiedDate(new Date()); commonClassDao.update(riskTypeData); } responseString = mapper.writeValueAsString(commonClassDao.getData(RiskType.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, riskTypeDatas, responseString); } - }catch (Exception e) { + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value = { "/sp_dictionary/remove_riskType" }, method = {RequestMethod.POST }) - public void removeRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/sp_dictionary/remove_riskType"}, method = {RequestMethod.POST}) + public void removeRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, riskTypeDatas, RiskType.class); } - @RequestMapping(value = { "/get_SafePolicyWarningDataByName" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = {"/get_SafePolicyWarningDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) public void getSafePolicyWarningEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, safePolicyWarningDatas, "name", SafePolicyWarning.class); } - @RequestMapping(value = { "/get_SafePolicyWarningData" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = {"/get_SafePolicyWarningData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) public void getSafePolicyWarningeEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, safePolicyWarningDatas, SafePolicyWarning.class); } - @RequestMapping(value = { "/sp_dictionary/save_safePolicyWarning" }, method = {RequestMethod.POST }) - public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/sp_dictionary/save_safePolicyWarning"}, + method = {RequestMethod.POST}) + public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -163,46 +174,55 @@ public class SafePolicyController { JsonNode root = mapper.readTree(request.getReader()); SafePolicyWarning safePolicyWarning; if (fromAPI) { - safePolicyWarning = mapper.readValue(root.get("dictionaryFields").toString(), SafePolicyWarning.class); + safePolicyWarning = mapper.readValue(root.get("dictionaryFields").toString(), + SafePolicyWarning.class); } else { - safePolicyWarning = mapper.readValue(root.get("safePolicyWarningData").toString(), SafePolicyWarning.class); + safePolicyWarning = mapper.readValue(root.get("safePolicyWarningData").toString(), + SafePolicyWarning.class); } - List duplicateData = commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class); + List duplicateData = commonClassDao.checkDuplicateEntry( + safePolicyWarning.getName(), "name", SafePolicyWarning.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { SafePolicyWarning data = (SafePolicyWarning) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { safePolicyWarning.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != safePolicyWarning.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != safePolicyWarning.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(safePolicyWarning.getId() == 0){ + if (!duplicateflag) { + if (safePolicyWarning.getId() == 0) { commonClassDao.save(safePolicyWarning); - }else{ + } else { commonClassDao.update(safePolicyWarning); } - responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, safePolicyWarningDatas, responseString); } - }catch (Exception e) { + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value = { "/sp_dictionary/remove_SafePolicyWarning" }, method = {RequestMethod.POST }) - public void removeSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/sp_dictionary/remove_SafePolicyWarning"}, + method = {RequestMethod.POST}) + public void removeSafePolicyWarningDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, safePolicyWarningDatas, SafePolicyWarning.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java index e5b6915bd..2688d7d3c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017,2019 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. * 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. @@ -22,9 +22,7 @@ package org.onap.policy.pap.xacml.rest.daoimpl; import java.util.List; import java.util.Map; - import javax.script.SimpleBindings; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Criteria; @@ -49,7 +47,7 @@ import org.springframework.stereotype.Service; @Service("CommonClassDao") @Primary -public class CommonClassDaoImpl implements CommonClassDao{ +public class CommonClassDaoImpl implements CommonClassDao { private static final Log LOGGER = LogFactory.getLog(CommonClassDaoImpl.class); @@ -58,80 +56,83 @@ public class CommonClassDaoImpl implements CommonClassDao{ @Autowired - private CommonClassDaoImpl(SessionFactory sessionFactory){ + private CommonClassDaoImpl(SessionFactory sessionFactory) { CommonClassDaoImpl.sessionFactory = sessionFactory; } - public CommonClassDaoImpl(){ - //Default Constructor + public CommonClassDaoImpl() { + // Default Constructor } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Override public List getData(Class className) { Session session = sessionFactory.openSession(); List data = null; - try{ + try { Criteria cr = session.createCriteria(className); data = cr.list(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" + e); + } finally { + try { session.close(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e); } } return data; } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) @Override public List getDataById(Class className, String columnName, String key) { Session session = sessionFactory.openSession(); List data = null; try { Criteria cr = session.createCriteria(className); - if(columnName.contains(":") && key.contains(":")){ + if (columnName.contains(":") && key.contains(":")) { String[] columns = columnName.split(":"); String[] keys = key.split(":"); - for(int i=0; i < columns.length; i++){ + for (int i = 0; i < columns.length; i++) { cr.add(Restrictions.eq(columns[i], keys[i])); } - }else{ + } else { cr.add(Restrictions.eq(columnName, key)); } data = cr.list(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } return data; } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Override public List getDataByColumn(Class className, String columnName) { Session session = sessionFactory.openSession(); List data = null; - try{ + try { Criteria cr = session.createCriteria(className); cr.setProjection(Projections.property(columnName)); data = cr.list(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" + e); + } finally { + try { session.close(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e); } } return data; @@ -144,13 +145,15 @@ public class CommonClassDaoImpl implements CommonClassDao{ try { session.persist(entity); tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table"+e); - }finally{ - try{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Saving data to Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } @@ -163,13 +166,15 @@ public class CommonClassDaoImpl implements CommonClassDao{ try { session.delete(entity); tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table"+e); - }finally{ - try{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Deleting data from Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } @@ -183,20 +188,22 @@ public class CommonClassDaoImpl implements CommonClassDao{ try { session.update(entity); tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table"+e); - }finally{ - try{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Updating data to Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Override public List checkDuplicateEntry(String value, String columnName, Class className) { Session session = sessionFactory.openSession(); @@ -204,32 +211,34 @@ public class CommonClassDaoImpl implements CommonClassDao{ List data = null; String[] columnNames = null; - if(columnName != null && columnName.contains(":")){ + if (columnName != null && columnName.contains(":")) { columnNames = columnName.split(":"); } String[] values = null; - if(value != null && value.contains(":")){ + if (value != null && value.contains(":")) { values = value.split(":"); } try { Criteria cr = session.createCriteria(className); - if(columnNames != null && values != null && columnNames.length == values.length){ - for (int i = 0; i < columnNames.length; i++){ - cr.add(Restrictions.eq(columnNames[i],values[i])); + if (columnNames != null && values != null && columnNames.length == values.length) { + for (int i = 0; i < columnNames.length; i++) { + cr.add(Restrictions.eq(columnNames[i], values[i])); } - }else{ - cr.add(Restrictions.eq(columnName,value)); + } else { + cr.add(Restrictions.eq(columnName, value)); } data = cr.list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table"+e + className); - }finally{ - try{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Querying for Duplicate Entries for Table" + e + className); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } return data; @@ -245,23 +254,24 @@ public class CommonClassDaoImpl implements CommonClassDao{ try { Query hbquery = session.createQuery(query); for (Map.Entry paramPair : params.entrySet()) { - if(paramPair.getValue() instanceof java.lang.Long){ + if (paramPair.getValue() instanceof java.lang.Long) { hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue()); - } - else{ + } else { hbquery.setParameter(paramPair.getKey(), paramPair.getValue()); } } data = hbquery.list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Querying Database Table" + e); throw e; - }finally{ - try{ + } finally { + try { session.close(); - }catch(HibernateException e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement",e1); + } catch (HibernateException e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement", e1); } } return data; @@ -277,12 +287,14 @@ public class CommonClassDaoImpl implements CommonClassDao{ hbquery.executeUpdate(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table"+e); - }finally{ - try{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Updating Database Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } } @@ -296,24 +308,26 @@ public class CommonClassDaoImpl implements CommonClassDao{ Object data = null; try { Criteria cr = session.createCriteria(className); - if(columnName.contains(":") && key.contains(":")){ + if (columnName.contains(":") && key.contains(":")) { String[] columns = columnName.split(":"); String[] keys = key.split(":"); - for(int i=0; i < columns.length; i++){ + for (int i = 0; i < columns.length; i++) { cr.add(Restrictions.eq(columns[i], keys[i])); } - }else{ + } else { cr.add(Restrictions.eq(columnName, key)); } data = cr.list().get(0); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); - }finally{ - try{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Querying Database Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } return data; @@ -329,11 +343,11 @@ public class CommonClassDaoImpl implements CommonClassDao{ try { Criteria cr = session.createCriteria(PolicyRoles.class); Disjunction disjunction = Restrictions.disjunction(); - Conjunction conjunction1 = Restrictions.conjunction(); + Conjunction conjunction1 = Restrictions.conjunction(); conjunction1.add(Restrictions.eq("role", "admin")); - Conjunction conjunction2 = Restrictions.conjunction(); + Conjunction conjunction2 = Restrictions.conjunction(); conjunction2.add(Restrictions.eq("role", "editor")); - Conjunction conjunction3 = Restrictions.conjunction(); + Conjunction conjunction3 = Restrictions.conjunction(); conjunction3.add(Restrictions.eq("role", "guest")); disjunction.add(conjunction1); disjunction.add(conjunction2); @@ -341,12 +355,14 @@ public class CommonClassDaoImpl implements CommonClassDao{ rolesData = cr.add(disjunction).list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e); - }finally{ - try{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Querying PolicyRoles Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } return rolesData; @@ -361,15 +377,16 @@ public class CommonClassDaoImpl implements CommonClassDao{ Transaction tx = session.beginTransaction(); try { Criteria cr = session.createCriteria(ClosedLoops.class); - cr.add(Restrictions.eq("closedLoopControlName",clName)); + cr.add(Restrictions.eq("closedLoopControlName", clName)); closedloopsdata = cr.list(); ClosedLoops closedloop = closedloopsdata.get(0); closedloop.setAlarmConditions(alarms); session.update(closedloop); tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e); - }finally{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Updating ClosedLoops Table" + e); + } finally { session.close(); } } @@ -383,15 +400,16 @@ public class CommonClassDaoImpl implements CommonClassDao{ Transaction tx = session.beginTransaction(); try { Criteria cr = session.createCriteria(ClosedLoops.class); - cr.add(Restrictions.eq("closedLoopControlName",clName)); + cr.add(Restrictions.eq("closedLoopControlName", clName)); closedloopsdata = cr.list(); ClosedLoops closedloop = closedloopsdata.get(0); closedloop.setYaml(yaml); session.update(closedloop); tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e); - }finally{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Updating ClosedLoops Table" + e); + } finally { session.close(); } } @@ -407,9 +425,10 @@ public class CommonClassDaoImpl implements CommonClassDao{ Criteria cr = session.createCriteria(ClosedLoops.class); closedloopsdata = cr.list(); - if(closedloopsdata!=null && !closedloopsdata.isEmpty()) { - LOGGER.info("ClosedLoops exist in the database, we need to delete them in our first step to buildCache()."); - for(int i=0; i < closedloopsdata.size(); i++) { + if (closedloopsdata != null && !closedloopsdata.isEmpty()) { + LOGGER.info( + "ClosedLoops exist in the database, we need to delete them in our first step to buildCache()."); + for (int i = 0; i < closedloopsdata.size(); i++) { ClosedLoops cl = closedloopsdata.get(i); session.delete(cl); } @@ -418,33 +437,38 @@ public class CommonClassDaoImpl implements CommonClassDao{ } tx.commit(); - }catch(Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while deleting ClosedLoops from the table"+e); - }finally{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error while deleting ClosedLoops from the table" + e); + } finally { session.close(); } } - @SuppressWarnings({ "unchecked"}) + @SuppressWarnings({"unchecked"}) @Override - public List checkExistingGroupListforUpdate(String groupListValue, String groupNameValue) { + public List checkExistingGroupListforUpdate(String groupListValue, + String groupNameValue) { Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); List data = null; try { Criteria cr = session.createCriteria(GroupPolicyScopeList.class); - cr.add(Restrictions.eq("groupList",groupListValue)); + cr.add(Restrictions.eq("groupList", groupListValue)); Criterion expression = Restrictions.eq("name", groupNameValue); cr.add(Restrictions.not(expression)); data = cr.list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for GroupPolicyScopeList Table"+e); - }finally{ - try{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Querying for Duplicate Entries for GroupPolicyScopeList Table" + + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } return data; @@ -452,7 +476,8 @@ public class CommonClassDaoImpl implements CommonClassDao{ @Override - public List getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List data) { + public List getMultipleDataOnAddingConjunction( + @SuppressWarnings("rawtypes") Class className, String columnName, List data) { return null; } @@ -460,4 +485,4 @@ public class CommonClassDaoImpl implements CommonClassDao{ sessionFactory = sessionfactory; } -} \ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java index e895b6336..d64b71763 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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. @@ -17,57 +17,38 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk.client; +import io.searchbox.client.JestResult; import java.util.Map; - import org.onap.policy.rest.adapter.PolicyRestAdapter; -import io.searchbox.client.JestResult; - public interface ElkConnector { public static final String ELK_URL = "http://localhost:9200"; public static final String ELK_INDEX_POLICY = "policy"; public enum PolicyIndexType { - config, - action, - decision, - closedloop, - all, + config, action, decision, closedloop, all, } public enum PolicyType { - Config, - Action, - Decision, - Config_Fault, - Config_PM, - Config_FW, - Config_MS, - Config_OOF, - none, + Config, Action, Decision, Config_Fault, Config_PM, Config_FW, Config_MS, Config_OOF, none, } public enum PolicyBodyType { - json, - xml, - properties, - txt, - none, + json, xml, properties, txt, none, } - public boolean delete(PolicyRestAdapter policyData) - throws IllegalStateException; + public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException; public JestResult search(PolicyIndexType type, String text) - throws IllegalStateException, IllegalArgumentException; + throws IllegalStateException, IllegalArgumentException; - public JestResult search(PolicyIndexType type, String text, - Map searchKeyValue) - throws IllegalStateException, IllegalArgumentException; + public JestResult search(PolicyIndexType type, String text, Map searchKeyValue) + throws IllegalStateException, IllegalArgumentException; public boolean update(PolicyRestAdapter policyData) throws IllegalStateException; @@ -88,16 +69,15 @@ public interface ElkConnector { return PolicyIndexType.config; } else if (policyName.startsWith("Config_OOF")) { return PolicyIndexType.config; - }else if (policyName.startsWith("Action")) { + } else if (policyName.startsWith("Action")) { return PolicyIndexType.action; } else if (policyName.startsWith("Decision")) { return PolicyIndexType.decision; } else if (policyName.startsWith("Config")) { return PolicyIndexType.config; } else { - throw new IllegalArgumentException - ("Unsupported policy name conversion to index: " + - policyName); + throw new IllegalArgumentException( + "Unsupported policy name conversion to index: " + policyName); } } 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 19a7ed294..6bbe033a3 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,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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. @@ -17,20 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.policy.pap.xacml.rest.elk.client; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.index.query.QueryStringQueryBuilder; -import org.elasticsearch.search.builder.SearchSourceBuilder; -import org.json.JSONObject; -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.xacml.api.XACMLErrorConstants; +package org.onap.policy.pap.xacml.rest.elk.client; import io.searchbox.action.Action; import io.searchbox.client.JestClient; @@ -44,8 +32,19 @@ import io.searchbox.core.Search.Builder; import io.searchbox.indices.IndicesExists; import io.searchbox.indices.type.TypeExist; import io.searchbox.params.Parameters; +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.index.query.QueryStringQueryBuilder; +import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.json.JSONObject; +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.xacml.api.XACMLErrorConstants; -public class ElkConnectorImpl implements ElkConnector{ +public class ElkConnectorImpl implements ElkConnector { private static final Logger LOGGER = FlexLogger.getLogger(ElkConnector.class); @@ -54,21 +53,23 @@ public class ElkConnectorImpl implements ElkConnector{ protected static int QUERY_MAXRECORDS = 1000; public ElkConnectorImpl() { - if (LOGGER.isDebugEnabled()){ + if (LOGGER.isDebugEnabled()) { LOGGER.debug("ENTER: -"); } - HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); + HttpClientConfig jestClientConfig = + new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); jestFactory.setHttpClientConfig(jestClientConfig); jestClient = jestFactory.getObject(); } protected boolean isType(PolicyIndexType type) throws IOException { - if (LOGGER.isDebugEnabled()){ + if (LOGGER.isDebugEnabled()) { LOGGER.debug("ENTER: -"); } try { - Action typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build(); + Action typeQuery = + new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build(); JestResult result = jestClient.execute(typeQuery); if (LOGGER.isInfoEnabled()) { @@ -79,7 +80,9 @@ public class ElkConnectorImpl implements ElkConnector{ } return result.isSucceeded(); } catch (IOException e) { - LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e); + LOGGER.warn( + "Error checking type existance of " + type.toString() + ": " + e.getMessage(), + e); throw e; } } @@ -97,17 +100,21 @@ public class ElkConnectorImpl implements ElkConnector{ } return result.isSucceeded(); } catch (IOException e) { - LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e); + LOGGER.warn( + "Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), + e); throw e; } } - private boolean isAlphaNumeric(String query){ + + private boolean isAlphaNumeric(String query) { return query.matches("[a-zA-Z_0-9]+"); } @Override - public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException { - if (LOGGER.isTraceEnabled()){ + public JestResult search(PolicyIndexType type, String text) + throws IllegalStateException, IllegalArgumentException { + if (LOGGER.isTraceEnabled()) { LOGGER.trace("ENTER: " + text); } @@ -115,20 +122,19 @@ public class ElkConnectorImpl implements ElkConnector{ throw new IllegalArgumentException("No search string provided"); } - if(!isAlphaNumeric(text)){ + if (!isAlphaNumeric(text)) { throw new IllegalArgumentException("Search must be alpha numeric"); } - QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*"+text+"*"); - SearchSourceBuilder searchSourceBuilder = - new SearchSourceBuilder().query(mQ); + QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*" + text + "*"); + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(mQ); - Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()). - addIndex(ELK_INDEX_POLICY). - setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); + Builder searchBuilder = + new Search.Builder(searchSourceBuilder.toString()).addIndex(ELK_INDEX_POLICY) + .setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); if (type == null || type == PolicyIndexType.all) { - for (PolicyIndexType pT: PolicyIndexType.values()) { + for (PolicyIndexType pT : PolicyIndexType.values()) { if (pT != PolicyIndexType.all) { searchBuilder.addType(pT.toString()); } @@ -142,26 +148,24 @@ public class ElkConnectorImpl implements ElkConnector{ try { result = jestClient.execute(search); } catch (IOException ioe) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + - search + ": " + ioe.getMessage(), ioe); + LOGGER.warn( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(), + ioe); throw new IllegalStateException(ioe); } if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()){ - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + - result.getPathToResult() + ":" + System.lineSeparator() + - result.getJsonString()); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); } } else { /* Unsuccessful search */ - if (LOGGER.isWarnEnabled()){ - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + - result.getResponseCode() + ": " + - search.getURI() + ":" + - result.getPathToResult() + ":" + - result.getJsonString() + ":" + - result.getErrorMessage()); + if (LOGGER.isWarnEnabled()) { + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() + + ": " + search.getURI() + ":" + result.getPathToResult() + ":" + + result.getJsonString() + ":" + result.getErrorMessage()); } String errorMessage = result.getErrorMessage(); @@ -169,19 +173,24 @@ public class ElkConnectorImpl implements ElkConnector{ String xMessage; if (errorMessage.contains("TokenMgrError")) { int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("QueryParsingException")) { int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("JsonParseException")) { int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("Parse Failure")) { int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("SearchParseException")) { int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else { xMessage = result.getErrorMessage(); } @@ -194,10 +203,9 @@ public class ElkConnectorImpl implements ElkConnector{ @Override - public JestResult search(PolicyIndexType type, String text, - Map filter_s) - throws IllegalStateException, IllegalArgumentException { - if (LOGGER.isTraceEnabled()){ + public JestResult search(PolicyIndexType type, String text, Map filter_s) + throws IllegalStateException, IllegalArgumentException { + if (LOGGER.isTraceEnabled()) { LOGGER.trace("ENTER: " + text); } @@ -205,52 +213,50 @@ public class ElkConnectorImpl implements ElkConnector{ return search(type, text); } - if(!isAlphaNumeric(text)){ + if (!isAlphaNumeric(text)) { throw new IllegalArgumentException("Search must be alpha numeric"); } String matches_s = ""; - matches_s = "{\n" + - " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + - " \"query\": {\n" + - " \"bool\" : {\n" + - " \"must\" : ["; + matches_s = "{\n" + " \"size\" : " + ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + + " \"query\": {\n" + " \"bool\" : {\n" + " \"must\" : ["; String match_params = ""; boolean first = true; - for(Entry entry : filter_s.entrySet()){ + for (Entry entry : filter_s.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); - if(first){ - match_params = "\"match\" : {\""+key+"\" : \""+value+"\" }},"; + if (first) { + match_params = "\"match\" : {\"" + key + "\" : \"" + value + "\" }},"; first = false; - }else{ - match_params = match_params + "{\"match\" : { \""+key+"\" : \""+value+"\" } },"; + } else { + match_params = + match_params + "{\"match\" : { \"" + key + "\" : \"" + value + "\" } },"; } } - if(match_params.endsWith(",")){ - match_params = match_params.substring(0, match_params.length()-2); + if (match_params.endsWith(",")) { + match_params = match_params.substring(0, match_params.length() - 2); } - matches_s = matches_s + "{\n" + match_params + "\n}" ; + matches_s = matches_s + "{\n" + match_params + "\n}"; boolean query = false; String query_String = ""; - if(text != null){ + if (text != null) { query = true; - query_String = "{\n \"query_string\" : {\n \"query\" : \"*"+text+"*\"\n} \n}"; + query_String = "{\n \"query_string\" : {\n \"query\" : \"*" + text + "*\"\n} \n}"; } - if(query){ - matches_s = matches_s + "," + query_String + "]\n}\n}\n}"; - }else{ + if (query) { + matches_s = matches_s + "," + query_String + "]\n}\n}\n}"; + } else { matches_s = matches_s + "]\n}\n}\n}"; } Builder searchBuilder = new Search.Builder(matches_s).addIndex(ELK_INDEX_POLICY); if (type == null || type == PolicyIndexType.all) { - for (PolicyIndexType pT: PolicyIndexType.values()) { + for (PolicyIndexType pT : PolicyIndexType.values()) { if (pT != PolicyIndexType.all) { searchBuilder.addType(pT.toString()); } @@ -265,26 +271,24 @@ public class ElkConnectorImpl implements ElkConnector{ try { result = jestClient.execute(search); } catch (IOException ioe) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + - search + ": " + ioe.getMessage(), ioe); + LOGGER.warn( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(), + ioe); throw new IllegalStateException(ioe); } if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()){ - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + - result.getPathToResult() + ":" + System.lineSeparator() + - result.getJsonString()); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); } } else { /* Unsuccessful search */ - if (LOGGER.isWarnEnabled()){ - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + - result.getResponseCode() + ": " + - search.getURI() + ":" + - result.getPathToResult() + ":" + - result.getJsonString() + ":" + - result.getErrorMessage()); + if (LOGGER.isWarnEnabled()) { + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() + + ": " + search.getURI() + ":" + result.getPathToResult() + ":" + + result.getJsonString() + ":" + result.getErrorMessage()); } String errorMessage = result.getErrorMessage(); @@ -292,19 +296,24 @@ public class ElkConnectorImpl implements ElkConnector{ String xMessage = errorMessage; if (errorMessage.contains("TokenMgrError")) { int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("QueryParsingException")) { int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("JsonParseException")) { int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("Parse Failure")) { int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("SearchParseException")) { int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else { xMessage = result.getErrorMessage(); } @@ -315,18 +324,18 @@ public class ElkConnectorImpl implements ElkConnector{ return result; } - public boolean put(PolicyRestAdapter policyData) - throws IOException, IllegalStateException { - if (LOGGER.isTraceEnabled()) LOGGER.trace("ENTER"); + public boolean put(PolicyRestAdapter policyData) throws IOException, IllegalStateException { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); PolicyIndexType indexType; try { String policyName = policyData.getNewFileName(); - if(policyName.contains("Config_")){ + if (policyName.contains("Config_")) { policyName = policyName.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ + } else if (policyName.contains("Action_")) { policyName = policyName.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ + } else if (policyName.contains("Decision_")) { policyName = policyName.replace(".Decision_", ":Decision_"); } @@ -338,27 +347,23 @@ public class ElkConnectorImpl implements ElkConnector{ } PolicyElasticData elasticData = new PolicyElasticData(policyData); JSONObject jsonObj = new JSONObject(elasticData); - Index elkPut = new Index.Builder(jsonObj.toString()). - index(ELK_INDEX_POLICY). - type(indexType.name()). - id(elasticData.getPolicyName()). - refresh(true). - build(); + Index elkPut = new Index.Builder(jsonObj.toString()).index(ELK_INDEX_POLICY) + .type(indexType.name()).id(elasticData.getPolicyName()).refresh(true).build(); JestResult result = jestClient.execute(elkPut); if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) - LOGGER.info("ElkConnector: OK: PUT operation of " + "->" + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); + LOGGER.info("ElkConnector: OK: PUT operation of " + "->" + ": " + "success=" + + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); } else { if (LOGGER.isWarnEnabled()) - LOGGER.warn("ElkConnector: FAILURE: PUT operation of "+ "->" + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); + LOGGER.warn("ElkConnector: FAILURE: PUT operation of " + "->" + ": " + "success=" + + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); } @@ -366,57 +371,55 @@ public class ElkConnectorImpl implements ElkConnector{ } @Override - public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException { + public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException { PolicyIndexType indexType = null; JestResult result; try { String policyName = policyData.getNewFileName(); - if(policyName.contains("Config_")){ + if (policyName.contains("Config_")) { policyName = policyName.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ + } else if (policyName.contains("Action_")) { policyName = policyName.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ + } else if (policyName.contains("Decision_")) { policyName = policyName.replace(".Decision_", ":Decision_"); } String[] splitPolicyName = policyName.split(":"); indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]); if (!isType(indexType)) { - throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + - " Type: " + indexType + - " is not configured"); + throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + " Type: " + + indexType + " is not configured"); } PolicyElasticData elasticData = new PolicyElasticData(policyData); - Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()).index(ELK_INDEX_POLICY). - type(indexType.name()).build(); + Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()) + .index(ELK_INDEX_POLICY).type(indexType.name()).build(); result = jestClient.execute(deleteRequest); } catch (IllegalArgumentException | IOException e) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + - indexType + ": null" + ":" + policyData.getNewFileName() + ": " + - e.getMessage(), e); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + indexType + ": null" + + ":" + policyData.getNewFileName() + ": " + e.getMessage(), e); throw new IllegalStateException(e); } if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) - LOGGER.info("OK: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); + LOGGER.info("OK: DELETE operation of " + indexType + ":" + + policyData.getNewFileName() + ": " + "success=" + result.isSucceeded() + + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" + + System.lineSeparator() + result.getJsonString()); } else { if (LOGGER.isWarnEnabled()) - LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); + LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + + policyData.getNewFileName() + ": " + "success=" + result.isSucceeded() + + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" + + System.lineSeparator() + result.getJsonString()); } return result.isSucceeded(); } @Override - public boolean update(PolicyRestAdapter policyData) throws IllegalStateException { - if (LOGGER.isDebugEnabled()){ + public boolean update(PolicyRestAdapter policyData) throws IllegalStateException { + if (LOGGER.isDebugEnabled()) { LOGGER.debug("ENTER"); } try { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java index e965356be..dd24aafc9 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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. @@ -17,13 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.service; import java.io.IOException; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.policy.pap.xacml.rest.controller.ActionPolicyDictionaryController; import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; import org.onap.policy.pap.xacml.rest.controller.ClosedLoopDictionaryController; @@ -45,250 +44,284 @@ public class DictionaryService { /* * Methods that call the controller method directly to Save and Update dictionary data */ - public String saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + public String saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryController dictionary = new DictionaryController(); - ModelAndView result = dictionary.saveOnapDictionary(request, response); + ModelAndView result = dictionary.saveOnapDictionary(request, response); return result.getViewName(); } - public String saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryController dictionary = new DictionaryController(); - ModelAndView result = dictionary.saveAttributeDictionary(request, response); + ModelAndView result = dictionary.saveAttributeDictionary(request, response); return result.getViewName(); - } + } - public String saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + public String saveActionPolicyDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { ActionPolicyDictionaryController action = new ActionPolicyDictionaryController(); - ModelAndView result = action.saveActionPolicyDictionary(request, response); + ModelAndView result = action.saveActionPolicyDictionary(request, response); return result.getViewName(); } - public String saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + public String saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { BRMSDictionaryController dictionary = new BRMSDictionaryController(); - ModelAndView result = dictionary.saveBRMSParamDictionary(request, response); + ModelAndView result = dictionary.saveBRMSParamDictionary(request, response); return result.getViewName(); } - public String saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveVSCLAction(HttpServletRequest request, HttpServletResponse response) + throws IOException { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveVSCLAction(request, response); + ModelAndView result = dictionary.saveVSCLAction(request, response); return result.getViewName(); } - public String saveVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveVnfType(HttpServletRequest request, HttpServletResponse response) + throws IOException { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveVnfType(request, response); + ModelAndView result = dictionary.saveVnfType(request, response); return result.getViewName(); } - public String savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePEPOptions(HttpServletRequest request, HttpServletResponse response) + throws IOException { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.savePEPOptions(request, response); + ModelAndView result = dictionary.savePEPOptions(request, response); return result.getViewName(); } - public String saveVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveVarbind(HttpServletRequest request, HttpServletResponse response) + throws IOException { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveVarbind(request, response); + ModelAndView result = dictionary.saveVarbind(request, response); return result.getViewName(); } - public String saveServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveServiceType(HttpServletRequest request, HttpServletResponse response) + throws IOException { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveServiceType(request, response); + ModelAndView result = dictionary.saveServiceType(request, response); return result.getViewName(); } - public String saveSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveSiteType(HttpServletRequest request, HttpServletResponse response) + throws IOException { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveSiteType(request, response); + ModelAndView result = dictionary.saveSiteType(request, response); return result.getViewName(); } - public String saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - ModelAndView result = dictionary.saveSettingsDictionary(request, response); + ModelAndView result = dictionary.saveSettingsDictionary(request, response); return result.getViewName(); } - public String saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - ModelAndView result = dictionary.saveRainyDayDictionary(request, response); + ModelAndView result = dictionary.saveRainyDayDictionary(request, response); return result.getViewName(); } - public String saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveDescriptiveDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController(); - ModelAndView result = dictionary.saveDescriptiveDictionary(request, response); + ModelAndView result = dictionary.saveDescriptiveDictionary(request, response); return result.getViewName(); } - public String saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveActionListDictionary(request, response); + ModelAndView result = dictionary.saveActionListDictionary(request, response); return result.getViewName(); } - public String saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveProtocolListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveProtocolListDictionary(request, response); + ModelAndView result = dictionary.saveProtocolListDictionary(request, response); return result.getViewName(); } - public String saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveZoneDictionary(request, response); + ModelAndView result = dictionary.saveZoneDictionary(request, response); return result.getViewName(); } - public String saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveSecurityZoneDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveSecurityZoneDictionary(request, response); + ModelAndView result = dictionary.saveSecurityZoneDictionary(request, response); return result.getViewName(); } - public String savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.savePrefixListDictionary(request, response); + ModelAndView result = dictionary.savePrefixListDictionary(request, response); return result.getViewName(); } - public String saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveAddressGroupDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveAddressGroupDictionary(request, response); + ModelAndView result = dictionary.saveAddressGroupDictionary(request, response); return result.getViewName(); } - public String saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveServiceGroupDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveServiceGroupDictionary(request, response); + ModelAndView result = dictionary.saveServiceGroupDictionary(request, response); return result.getViewName(); } - public String saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveServiceListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveServiceListDictionary(request, response); + ModelAndView result = dictionary.saveServiceListDictionary(request, response); return result.getViewName(); } - public String saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveTermListDictionary(request, response); + ModelAndView result = dictionary.saveTermListDictionary(request, response); return result.getViewName(); } - - public String saveMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveMicroServiceLocationDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveMicroServiceLocationDictionary(request, response); + ModelAndView result = dictionary.saveMicroServiceLocationDictionary(request, response); return result.getViewName(); } - public String saveMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveMicroServiceConfigNameDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveMicroServiceConfigNameDictionary(request, response); + ModelAndView result = dictionary.saveMicroServiceConfigNameDictionary(request, response); return result.getViewName(); } - public String saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveDCAEUUIDDictionary(request, response); + ModelAndView result = dictionary.saveDCAEUUIDDictionary(request, response); return result.getViewName(); } - public String saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveMicroServiceModelsDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveMicroServiceModelsDictionary(request, response); + ModelAndView result = dictionary.saveMicroServiceModelsDictionary(request, response); return result.getViewName(); } - public String saveMicroServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveMicroServiceDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveMicroServiceAttributeDictionary(request, response); + ModelAndView result = dictionary.saveMicroServiceAttributeDictionary(request, response); return result.getViewName(); } - public String saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveOptimizationModelsDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { OptimizationDictionaryController dictionary = new OptimizationDictionaryController(); - ModelAndView result = dictionary.saveOptimizationModelsDictionary(request, response); + ModelAndView result = dictionary.saveOptimizationModelsDictionary(request, response); return result.getViewName(); } - public String savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSServiceDictionary(request, response); + ModelAndView result = dictionary.savePSServiceDictionary(request, response); return result.getViewName(); } - public String savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSResourceDictionary(request, response); + ModelAndView result = dictionary.savePSResourceDictionary(request, response); return result.getViewName(); } - public String savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSTypeDictionary(request, response); + ModelAndView result = dictionary.savePSTypeDictionary(request, response); return result.getViewName(); } - public String savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePSClosedLoopDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSClosedLoopDictionary(request, response); + ModelAndView result = dictionary.savePSClosedLoopDictionary(request, response); return result.getViewName(); } - public String savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePSGroupScopeDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSGroupScopeDictionary(request, response); + ModelAndView result = dictionary.savePSGroupScopeDictionary(request, response); return result.getViewName(); } - public String saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { SafePolicyController dictionary = new SafePolicyController(); - ModelAndView result = dictionary.saveRiskTypeDictionary(request, response); + ModelAndView result = dictionary.saveRiskTypeDictionary(request, response); return result.getViewName(); } - public String saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveSafePolicyWarningDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { SafePolicyController dictionary = new SafePolicyController(); - ModelAndView result = dictionary.saveSafePolicyWarningDictionary(request, response); + ModelAndView result = dictionary.saveSafePolicyWarningDictionary(request, response); return result.getViewName(); } @@ -296,179 +329,179 @@ public class DictionaryService { /* * Methods that call the controller get methods directly to get dictionary data */ - public void getOnapDictionary(HttpServletResponse response){ + public void getOnapDictionary(HttpServletResponse response) { DictionaryController dictionary = new DictionaryController(); - dictionary.getOnapNameDictionaryEntityData(response); + dictionary.getOnapNameDictionaryEntityData(response); } - public void getAttributeDictionary(HttpServletResponse response){ + public void getAttributeDictionary(HttpServletResponse response) { DictionaryController dictionary = new DictionaryController(); - dictionary.getAttributeDictionaryEntityData(response); + dictionary.getAttributeDictionaryEntityData(response); } - public void getActionPolicyDictionary(HttpServletResponse response){ + public void getActionPolicyDictionary(HttpServletResponse response) { ActionPolicyDictionaryController action = new ActionPolicyDictionaryController(); - action.getActionPolicyDictionaryEntityData(response); + action.getActionPolicyDictionaryEntityData(response); } - public void getBRMSParamDictionary(HttpServletResponse response){ + public void getBRMSParamDictionary(HttpServletResponse response) { BRMSDictionaryController dictionary = new BRMSDictionaryController(); - dictionary.getBRMSParamDictionaryEntityData(response); + dictionary.getBRMSParamDictionaryEntityData(response); } - public void getVSCLAction(HttpServletResponse response){ + public void getVSCLAction(HttpServletResponse response) { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getVSCLActionDictionaryEntityData(response); + dictionary.getVSCLActionDictionaryEntityData(response); } - public void getVnfType(HttpServletResponse response){ + public void getVnfType(HttpServletResponse response) { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getVNFTypeDictionaryEntityData(response); + dictionary.getVNFTypeDictionaryEntityData(response); } - public void getPEPOptions(HttpServletResponse response){ + public void getPEPOptions(HttpServletResponse response) { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getPEPOptionsDictionaryEntityData(response); + dictionary.getPEPOptionsDictionaryEntityData(response); } - public void getVarbind(HttpServletResponse response){ + public void getVarbind(HttpServletResponse response) { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getVarbindDictionaryEntityData(response); + dictionary.getVarbindDictionaryEntityData(response); } - public void getServiceType(HttpServletResponse response){ + public void getServiceType(HttpServletResponse response) { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getClosedLoopServiceDictionaryEntityData(response); + dictionary.getClosedLoopServiceDictionaryEntityData(response); } - public void getSiteType(HttpServletResponse response){ + public void getSiteType(HttpServletResponse response) { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getClosedLoopSiteDictionaryEntityData(response); + dictionary.getClosedLoopSiteDictionaryEntityData(response); } - public void getSettingsDictionary(HttpServletResponse response){ + public void getSettingsDictionary(HttpServletResponse response) { DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - dictionary.getSettingsDictionaryEntityData(response); + dictionary.getSettingsDictionaryEntityData(response); } - public void getRainyDayDictionary(HttpServletResponse response){ + public void getRainyDayDictionary(HttpServletResponse response) { DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - dictionary.getRainyDayDictionaryEntityData(response); + dictionary.getRainyDayDictionaryEntityData(response); } - public void getDescriptiveDictionary(HttpServletResponse response){ + public void getDescriptiveDictionary(HttpServletResponse response) { DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController(); - dictionary.getDescriptiveDictionaryEntityData(response); + dictionary.getDescriptiveDictionaryEntityData(response); } - public void getActionListDictionary(HttpServletResponse response){ + public void getActionListDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getActionListDictionaryEntityData(response); + dictionary.getActionListDictionaryEntityData(response); } - public void getProtocolListDictionary(HttpServletResponse response){ + public void getProtocolListDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getProtocolListDictionaryEntityData(response); + dictionary.getProtocolListDictionaryEntityData(response); } - public void getZoneDictionary(HttpServletResponse response){ + public void getZoneDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getZoneDictionaryEntityData(response); + dictionary.getZoneDictionaryEntityData(response); } - public void getSecurityZoneDictionary(HttpServletResponse response){ + public void getSecurityZoneDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getSecurityZoneDictionaryEntityData(response); + dictionary.getSecurityZoneDictionaryEntityData(response); } - public void getPrefixListDictionary(HttpServletResponse response){ + public void getPrefixListDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getPrefixListDictionaryEntityData(response); + dictionary.getPrefixListDictionaryEntityData(response); } - public void getAddressGroupDictionary(HttpServletResponse response){ + public void getAddressGroupDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getAddressGroupDictionaryEntityData(response); + dictionary.getAddressGroupDictionaryEntityData(response); } - public void getServiceGroupDictionary(HttpServletResponse response){ + public void getServiceGroupDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getServiceGroupDictionaryEntityData(response); + dictionary.getServiceGroupDictionaryEntityData(response); } - public void getServiceListDictionary(HttpServletResponse response){ + public void getServiceListDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getServiceListDictionaryEntityData(response); + dictionary.getServiceListDictionaryEntityData(response); } - public void getTermListDictionary(HttpServletResponse response){ + public void getTermListDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getTermListDictionaryEntityData(response); + dictionary.getTermListDictionaryEntityData(response); } - public void getMicroServiceLocationDictionary(HttpServletResponse response){ + public void getMicroServiceLocationDictionary(HttpServletResponse response) { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getMicroServiceLocationDictionaryEntityData(response); + dictionary.getMicroServiceLocationDictionaryEntityData(response); } - public void getMicroServiceConfigNameDictionary(HttpServletResponse response){ + public void getMicroServiceConfigNameDictionary(HttpServletResponse response) { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getMicroServiceConfigNameDictionaryEntityData(response); + dictionary.getMicroServiceConfigNameDictionaryEntityData(response); } - public void getDCAEUUIDDictionary(HttpServletResponse response){ + public void getDCAEUUIDDictionary(HttpServletResponse response) { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getDCAEUUIDDictionaryEntityData(response); + dictionary.getDCAEUUIDDictionaryEntityData(response); } - public void getMicroServiceModelsDictionary(HttpServletResponse response){ + public void getMicroServiceModelsDictionary(HttpServletResponse response) { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getMicroServiceModelsDictionaryEntityData(response); + dictionary.getMicroServiceModelsDictionaryEntityData(response); } - public void getMicroServiceDictionary(HttpServletResponse response){ + public void getMicroServiceDictionary(HttpServletResponse response) { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getMicroServiceModelsDictionaryEntityData(response); + dictionary.getMicroServiceModelsDictionaryEntityData(response); } - public void getOptimizationModelsDictionary(HttpServletResponse response){ + public void getOptimizationModelsDictionary(HttpServletResponse response) { OptimizationDictionaryController dictionary = new OptimizationDictionaryController(); - dictionary.getOptimizationModelsDictionaryEntityData(response); + dictionary.getOptimizationModelsDictionaryEntityData(response); } - public void getPSServiceDictionary(HttpServletResponse response){ + public void getPSServiceDictionary(HttpServletResponse response) { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getPSServiceEntityData(response); + dictionary.getPSServiceEntityData(response); } - public void getPSResourceDictionary(HttpServletResponse response){ + public void getPSResourceDictionary(HttpServletResponse response) { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getPSResourceEntityData(response); + dictionary.getPSResourceEntityData(response); } - public void getPSTypeDictionary(HttpServletResponse response){ + public void getPSTypeDictionary(HttpServletResponse response) { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getPSTypeEntityData(response); + dictionary.getPSTypeEntityData(response); } - public void getPSClosedLoopDictionary(HttpServletResponse response){ + public void getPSClosedLoopDictionary(HttpServletResponse response) { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getPSClosedLoopEntityData(response); + dictionary.getPSClosedLoopEntityData(response); } - public void getPSGroupScopeDictionary(HttpServletResponse response){ + public void getPSGroupScopeDictionary(HttpServletResponse response) { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getGroupPolicyScopeEntityData(response); + dictionary.getGroupPolicyScopeEntityData(response); } - public void getRiskTypeDictionary(HttpServletResponse response){ + public void getRiskTypeDictionary(HttpServletResponse response) { SafePolicyController dictionary = new SafePolicyController(); - dictionary.getRiskTypeDictionaryEntityData(response); + dictionary.getRiskTypeDictionaryEntityData(response); } public void getSafePolicyWarningDictionary(HttpServletResponse response) { SafePolicyController dictionary = new SafePolicyController(); - dictionary.getSafePolicyWarningeEntityData(response); + dictionary.getSafePolicyWarningeEntityData(response); } -} \ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java index 5e4b4ee7d..01fbff7ce 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. * 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.service; import java.io.BufferedWriter; @@ -29,10 +30,8 @@ import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.UUID; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -43,7 +42,7 @@ import org.onap.policy.pap.xacml.rest.components.CreateNewOptimizationModel; public class ImportService { private static final Logger logger = FlexLogger.getLogger(ImportService.class); private static String errorMessage = "Error in reading in file from API call"; - private static String errorMsg = "error"; + private static String errorMsg = "error"; private static String operation = "operation"; private static String importHeader = "import"; private static String service = "service"; @@ -59,7 +58,7 @@ public class ImportService { String version = request.getParameter("version"); String serviceName = request.getParameter("serviceName"); - if(serviceName == null || serviceName.isEmpty() || !serviceName.matches(REGEX)){ + if (serviceName == null || serviceName.isEmpty() || !serviceName.matches(REGEX)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.addHeader(errorMsg, MISSING); response.addHeader(operation, importHeader); @@ -69,12 +68,12 @@ public class ImportService { String description = request.getParameter("description"); Map successMap = new HashMap<>(); - if(("BRMSPARAM").equals(importServiceCreation)){ + if (("BRMSPARAM").equals(importServiceCreation)) { StringBuilder builder = new StringBuilder(); int ch; try { - while((ch = request.getInputStream().read()) != -1){ - builder.append((char)ch); + while ((ch = request.getInputStream().read()) != -1) { + builder.append((char) ch); } } catch (IOException e) { logger.error(e); @@ -85,19 +84,19 @@ public class ImportService { response.addHeader(service, serviceName); } CreateBRMSRuleTemplate brmsRuleTemplate = new CreateBRMSRuleTemplate(); - successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); - } - else if(("MICROSERVICE").equals(importServiceCreation)){ + successMap = + brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); + } else if (("MICROSERVICE").equals(importServiceCreation)) { CreateNewMicroServiceModel newMS = null; String randomID = UUID.randomUUID().toString(); String type = ".xmi"; - if ( fileName != null) { + if (fileName != null) { File extracDir = new File(extractDir); - if (!extracDir.exists()){ + if (!extracDir.exists()) { extracDir.mkdirs(); } - if (fileName.contains(".xmi") || fileName.contains(".yml")){ - if(fileName.contains(".yml")){ + if (fileName.contains(".xmi") || fileName.contains(".yml")) { + if (fileName.contains(".yml")) { type = ".yml"; } // get the request content into a String @@ -106,7 +105,7 @@ public class ImportService { try { scanner = new java.util.Scanner(request.getInputStream()); scanner.useDelimiter("\\A"); - xmi = scanner.hasNext() ? scanner.next() : ""; + xmi = scanner.hasNext() ? scanner.next() : ""; scanner.close(); } catch (IOException e1) { logger.error(e1); @@ -115,37 +114,41 @@ public class ImportService { } PolicyLogger.info("Request from API to import new Service"); try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(extractDir + File.separator + randomID+type), "utf-8"))) { + new FileOutputStream(extractDir + File.separator + randomID + type), + "utf-8"))) { writer.write(xmi); } catch (IOException e) { logger.error(e); PolicyLogger.error(errorMessage); return; } - }else{ + } else { InputStream inputStream = null; - try(FileOutputStream outputStream = new FileOutputStream(extractDir + File.separator + randomID+".zip")) { + try (FileOutputStream outputStream = + new FileOutputStream(extractDir + File.separator + randomID + ".zip")) { inputStream = request.getInputStream(); byte[] buffer = new byte[4096]; - int bytesRead = -1 ; + int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead) ; + outputStream.write(buffer, 0, bytesRead); } } catch (IOException e) { - PolicyLogger.error("Error in reading in Zip File from API call"+e); + PolicyLogger.error("Error in reading in Zip File from API call" + e); return; - }finally{ + } finally { try { - if(inputStream != null){ + if (inputStream != null) { inputStream.close(); } } catch (IOException e) { - PolicyLogger.error("Exception Occured while closing the input/output stream"+e); + PolicyLogger.error( + "Exception Occured while closing the input/output stream" + e); } } } - newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID); + newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, + randomID); successMap = newMS.addValuesToNewModel(type); @@ -154,12 +157,12 @@ public class ImportService { successMap = newMS.saveImportService(); } } - } else if(("OPTIMIZATION").equals(importServiceCreation)){ + } else if (("OPTIMIZATION").equals(importServiceCreation)) { CreateNewOptimizationModel newOOF = null; String randomID = UUID.randomUUID().toString(); - if ( fileName != null) { + if (fileName != null) { File extracDir = new File(extractDir); - if (!extracDir.exists()){ + if (!extracDir.exists()) { extracDir.mkdirs(); } @@ -167,9 +170,9 @@ public class ImportService { // get the request content into a String String yml = null; - try (java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());){ + try (java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());) { scanner.useDelimiter("\\A"); - yml = scanner.hasNext() ? scanner.next() : ""; + yml = scanner.hasNext() ? scanner.next() : ""; } catch (IOException e1) { logger.error(e1); PolicyLogger.error(errorMessage); @@ -177,7 +180,8 @@ public class ImportService { } PolicyLogger.info("Request from API to import new Optimization Service Model"); try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(extractDir + File.separator + randomID+type), "utf-8"))) { + new FileOutputStream(extractDir + File.separator + randomID + type), + "utf-8"))) { writer.write(yml); } catch (IOException e) { logger.error(e); @@ -185,7 +189,8 @@ public class ImportService { return; } - newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", version, randomID); + newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", + version, randomID); successMap = newOOF.addValuesToNewModel(); if (successMap.containsKey(successMessage)) { successMap.clear(); @@ -201,22 +206,22 @@ public class ImportService { response.addHeader(operation, importHeader); response.addHeader(service, serviceName); } else if (successMap.containsKey("DBError")) { - if (successMap.get("DBError").contains("EXISTS")){ + if (successMap.get("DBError").contains("EXISTS")) { response.setStatus(HttpServletResponse.SC_CONFLICT); response.addHeader(service, serviceName); response.addHeader(errorMsg, "modelExistsDB"); - }else{ + } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.addHeader(errorMsg, "importDB"); } response.addHeader(operation, importHeader); response.addHeader(service, serviceName); - }else if (successMap.get(errorMsg).contains("MISSING")){ + } else if (successMap.get(errorMsg).contains("MISSING")) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.addHeader(errorMsg, MISSING); response.addHeader(operation, importHeader); response.addHeader(service, serviceName); - }else if (successMap.get(errorMsg).contains("VALIDATION")){ + } else if (successMap.get(errorMsg).contains("VALIDATION")) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.addHeader(errorMsg, "validation"); response.addHeader(operation, importHeader); @@ -224,4 +229,4 @@ public class ImportService { } } -} \ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java index f85255785..e88efa931 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. * 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. @@ -17,18 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.util; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONObject; @@ -41,14 +43,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Service public class DictionaryUtils { - private static final Log LOGGER = LogFactory.getLog(DictionaryUtils.class); + private static final Log LOGGER = LogFactory.getLog(DictionaryUtils.class); private static String apiflag = "apiflag"; private static String operation = "operation"; @@ -69,78 +67,80 @@ public class DictionaryUtils { } @Autowired - public DictionaryUtils(CommonClassDao commonClassDao){ + public DictionaryUtils(CommonClassDao commonClassDao) { DictionaryUtils.commonClassDao = commonClassDao; } - public DictionaryUtils(){ + public DictionaryUtils() { super(); } - public UserInfo getUserInfo(String loginId){ + public UserInfo getUserInfo(String loginId) { return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); } - public boolean isRequestFromAPI(HttpServletRequest request){ - return request.getParameter(apiflag)!=null && "api".equalsIgnoreCase(request.getParameter(apiflag)); + public boolean isRequestFromAPI(HttpServletRequest request) { + return request.getParameter(apiflag) != null + && "api".equalsIgnoreCase(request.getParameter(apiflag)); } - public String appendKey(List objects, String key1, String appendValue){ + public String appendKey(List objects, String key1, String appendValue) { StringBuilder userValue = new StringBuilder(); int counter = 0; - for(Object attribute : objects){ - if(attribute instanceof LinkedHashMap){ + for (Object attribute : objects) { + if (attribute instanceof LinkedHashMap) { String key = ((LinkedHashMap) attribute).get(key1).toString(); - if(counter>0){ + if (counter > 0) { userValue.append(appendValue); } userValue.append(key); - counter ++; + counter++; } } return userValue.toString(); } - public String appendKeyValue(List objects, String append1, String append2){ + public String appendKeyValue(List objects, String append1, String append2) { StringBuilder header = new StringBuilder(); int counter = 0; - for(Object attribute : objects){ - if(attribute instanceof LinkedHashMap){ + for (Object attribute : objects) { + if (attribute instanceof LinkedHashMap) { String key = ((LinkedHashMap) attribute).get("option").toString(); String value = ((LinkedHashMap) attribute).get("number").toString(); - if(counter>0){ + if (counter > 0) { header.append(append1); } header.append(key).append(append2).append(value); - counter ++; + counter++; } } return header.toString(); } - public Datatype getDataType(String datatype){ + public Datatype getDataType(String datatype) { Datatype a = new Datatype(); - if("string".equalsIgnoreCase(datatype)){ + if ("string".equalsIgnoreCase(datatype)) { a.setId(26); - }else if("integer".equalsIgnoreCase(datatype)){ + } else if ("integer".equalsIgnoreCase(datatype)) { a.setId(12); - }else if("boolean".equalsIgnoreCase(datatype)){ + } else if ("boolean".equalsIgnoreCase(datatype)) { a.setId(18); - }else if("double".equalsIgnoreCase(datatype)){ + } else if ("double".equalsIgnoreCase(datatype)) { a.setId(25); - }else if("user".equalsIgnoreCase(datatype)){ + } else if ("user".equalsIgnoreCase(datatype)) { a.setId(29); } return a; } - public Category getCategory(){ - return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource").get(0); + public Category getCategory() { + return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource") + .get(0); } - public ModelAndView getResultForApi(String inResponseString){ + public ModelAndView getResultForApi(String inResponseString) { String responseString = inResponseString; - if(responseString!=null && !duplicateResponseString.equals(responseString)){ + if (responseString != null && !duplicateResponseString.equals(responseString)) { responseString = "Success"; } ModelAndView result = new ModelAndView(); @@ -148,16 +148,17 @@ public class DictionaryUtils { return result; } - public void setResponseData(HttpServletResponse response, String key, String responseString) throws IOException{ + public void setResponseData(HttpServletResponse response, String key, String responseString) + throws IOException { response.setCharacterEncoding(utf8); response.setContentType(applicationJsonContentType); PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{"+key+":" + responseString + "}"); + JSONObject j = new JSONObject("{" + key + ":" + responseString + "}"); out.write(j.toString()); } - public void setErrorResponseData(HttpServletResponse response, Exception e) throws IOException{ + public void setErrorResponseData(HttpServletResponse response, Exception e) throws IOException { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); response.setCharacterEncoding(utf8); PrintWriter out = response.getWriter(); @@ -165,47 +166,51 @@ public class DictionaryUtils { } @SuppressWarnings("rawtypes") - public void getDataByEntity(HttpServletResponse response, String key, String value, Class className){ - try{ + public void getDataByEntity(HttpServletResponse response, String key, String value, + Class className) { + try { Map model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); - model.put(key, mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value))); + model.put(key, + mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value))); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); JSONObject j = new JSONObject(msg); response.getWriter().write(j.toString()); - }catch(Exception e){ + } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); } } @SuppressWarnings("rawtypes") - public void getData(HttpServletResponse response, String key, Class className){ - try{ + public void getData(HttpServletResponse response, String key, Class className) { + try { Map model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); model.put(key, mapper.writeValueAsString(commonClassDao.getData(className))); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); + response.addHeader("successMapKey", "success"); response.addHeader(operation, "getDictionary"); response.getWriter().write(j.toString()); - }catch(Exception e){ + } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.addHeader("error", "dictionaryDBQuery"); } } @SuppressWarnings("unchecked") - public void removeData(HttpServletRequest request, HttpServletResponse response, String key, @SuppressWarnings("rawtypes") Class className) throws IOException{ - try{ + public void removeData(HttpServletRequest request, HttpServletResponse response, String key, + @SuppressWarnings("rawtypes") Class className) throws IOException { + try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - commonClassDao.delete((Object)mapper.readValue(root.get("data").toString(), className)); + commonClassDao + .delete(mapper.readValue(root.get("data").toString(), className)); String responseString = mapper.writeValueAsString(commonClassDao.getData(className)); setResponseData(response, key, responseString); - }catch(Exception e){ + } catch (Exception e) { setErrorResponseData(response, e); } } diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java index fcf319c8e..c227d9d2a 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PDP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -276,6 +276,13 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor" + e); throw new ServletException(e); } + + try { + System.setProperty("msToscaModel.home", properties.getProperty("msToscaModel.home")); + } catch (Exception e) { + logger.error("ERROR: Unable to set msToscaModel.home- Please check the configuration"); + } + startThreads(baseLoggingContext, new Thread(this)); } diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java index f7c1cc578..f8cba5123 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PDP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -20,6 +20,7 @@ package org.onap.policy.pdp.rest.api.services; import java.io.BufferedInputStream; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.UUID; @@ -77,6 +78,25 @@ public class PolicyEngineImportService { importResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e; status = HttpStatus.BAD_REQUEST; } + + // Save the imported file + if (!file.isEmpty() && status.equals(HttpStatus.OK) ) { + String filePath = null; + try { + String uploadsDir = System.getProperty("msToscaModel.home"); + if(uploadsDir != null) { + if(! new File(uploadsDir).exists()){ + new File(uploadsDir).mkdir(); + } + String orgName = file.getOriginalFilename(); + filePath = uploadsDir + orgName; + File dest = new File(filePath); + file.transferTo(dest); + } + }catch(Exception e){ + LOGGER.error("Operation: policyEngineImport : " + e.getMessage() + ". " + filePath + " is not a valid file path."); + } + } } private void specialCheck() { diff --git a/ONAP-PDP-REST/xacml.pdp.properties b/ONAP-PDP-REST/xacml.pdp.properties index b6050ff58..90e0f5c3c 100644 --- a/ONAP-PDP-REST/xacml.pdp.properties +++ b/ONAP-PDP-REST/xacml.pdp.properties @@ -2,7 +2,7 @@ # ============LICENSE_START======================================================= # ONAP-PDP-REST # ================================================================================ -# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. +# Copyright (C) 2017-2019 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. @@ -192,6 +192,9 @@ aaf_oauth2_token_url=https://aaf-onap-test.osaaf.org:8095/AAF_NS.token:2.1/token fs_url=https://aaf-onap-test.osaaf.org:8095/AAF_NS.fs.2.1 gui_url=https://aaf-onap-test.osaaf.org:8095/AAF_NS.gui.2.1 +#TOSCA MS model yaml file directory which can be changed based on systems. +#msToscaModel.home=C://home//msyamlFiles// +msToscaModel.home=/home/users/PolicyEngine/webapps/ConfigPAP/ # Decision Response settings. # can be either PERMIT or DENY. diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java index fa9e759b7..baf27b06f 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -82,16 +82,17 @@ import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; - -@WebServlet(value ="/fm/*", loadOnStartup = 1, initParams = { @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") }) +@WebServlet(value = "/fm/*", loadOnStartup = 1, initParams = { + @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") }) public class PolicyManagerServlet extends HttpServlet { - private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class); + private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class); private static final long serialVersionUID = -8453502699403909016L; private static final String VERSION = "version"; private static final String NAME = "name"; private static final String DATE = "date"; private static final String SIZE = "size"; private static final String TYPE = "type"; + private static final String ROLETYPE = "roleType"; private static final String CREATED_BY = "createdBy"; private static final String MODIFIED_BY = "modifiedBy"; private static final String CONTENTTYPE = "application/json"; @@ -125,16 +126,19 @@ public class PolicyManagerServlet extends HttpServlet { private static final String SCOPE_NAME = "scopeName"; private static final String SUCCESS = "success"; private static final String SUB_SCOPENAME = "subScopename"; + private static final String ALLSCOPES = "@All@"; private static final String PERCENT_AND_ID_GT_0 = "%' and id >0"; private static List serviceTypeNamesList = new ArrayList<>(); private static JsonArray policyNames; private static String testUserId = null; private enum Mode { - LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST + LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, + EXPORT, SEARCHLIST } private static PolicyController policyController; + private synchronized PolicyController getPolicyController() { return policyController; } @@ -163,21 +167,20 @@ public class PolicyManagerServlet extends HttpServlet { // XACMLRest.xacmlInit(servletConfig); // - //Initialize ClosedLoop JSON + // Initialize ClosedLoop JSON // PolicyManagerServlet.initializeJSONLoad(); } private static void initializeJSONLoad() { - Path closedLoopJsonLocation = Paths.get(XACMLProperties - .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP)); + Path closedLoopJsonLocation = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP)); String location = closedLoopJsonLocation.toString(); - if (! location.endsWith("json")) { + if (!location.endsWith("json")) { LOGGER.warn("JSONConfig file does not end with extension .json"); return; } try (FileInputStream inputStream = new FileInputStream(location); - JsonReader jsonReader = Json.createReader(inputStream)) { + JsonReader jsonReader = Json.createReader(inputStream)) { policyNames = jsonReader.readArray(); serviceTypeNamesList = new ArrayList<>(); for (int i = 0; i < policyNames.size(); i++) { @@ -186,7 +189,7 @@ public class PolicyManagerServlet extends HttpServlet { serviceTypeNamesList.add(name); } } catch (IOException e) { - LOGGER.error("Exception Occured while initializing the JSONConfig file"+e); + LOGGER.error("Exception Occured while initializing the JSONConfig file" + e); } } @@ -205,13 +208,13 @@ public class PolicyManagerServlet extends HttpServlet { } catch (Exception e) { try { setError(e, response); - }catch(Exception e1){ - LOGGER.error(EXCEPTION_OCCURED +e1); + } catch (Exception e1) { + LOGGER.error(EXCEPTION_OCCURED + e1); } } } - //Set Error Message for Exception + // Set Error Message for Exception private void setError(Exception t, HttpServletResponse response) throws IOException { try { JSONObject responseJsonObject = error(t.getMessage()); @@ -220,12 +223,12 @@ public class PolicyManagerServlet extends HttpServlet { out.print(responseJsonObject); out.flush(); } catch (Exception x) { - LOGGER.error(EXCEPTION_OCCURED +x); + LOGGER.error(EXCEPTION_OCCURED + x); response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage()); } } - //Policy Import Functionality + // Policy Import Functionality private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { Map files = new HashMap<>(); @@ -253,27 +256,24 @@ public class PolicyManagerServlet extends HttpServlet { private void processFormFile(HttpServletRequest request, FileItem item) { String newFile; - if(item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()){ + if (item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()) { File file = new File(item.getName()); - try (OutputStream outputStream = new FileOutputStream(file)) - { + try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(item.getInputStream(), outputStream); newFile = file.toString(); PolicyExportAndImportController importController = new PolicyExportAndImportController(); importController.importRepositoryFile(newFile, request); - }catch(Exception e){ + } catch (Exception e) { LOGGER.error("Upload error : " + e); } - } - else if (!item.getName().endsWith(".xls")) { + } else if (!item.getName().endsWith(".xls")) { LOGGER.error("Non .xls filetype uploaded: " + item.getName()); - } - else { //uploaded file size is greater than allowed + } else { // uploaded file size is greater than allowed LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize()); } } - //File Operation Functionality + // File Operation Functionality private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException { JSONObject responseJsonObject; StringBuilder sb = new StringBuilder(); @@ -294,9 +294,12 @@ public class PolicyManagerServlet extends HttpServlet { Mode mode = Mode.valueOf(params.getString("mode")); String userId = UserUtils.getUserSession(request).getOrgUserId(); - LOGGER.info("****************************************Logging UserID while doing actions on Editor tab*******************************************"); - LOGGER.info("UserId: " + userId + "Action Mode: "+ mode.toString() + "Action Params: "+params.toString()); - LOGGER.info("***********************************************************************************************************************************"); + LOGGER.info( + "****************************************Logging UserID while doing actions on Editor tab*******************************************"); + LOGGER.info( + "UserId: " + userId + "Action Mode: " + mode.toString() + "Action Params: " + params.toString()); + LOGGER.info( + "***********************************************************************************************************************************"); responseJsonObject = operateBasedOnMode(mode, params, request); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Processing Json" + e); @@ -315,8 +318,8 @@ public class PolicyManagerServlet extends HttpServlet { } } - - private JSONObject operateBasedOnMode(Mode mode, JSONObject params, HttpServletRequest request) throws ServletException{ + private JSONObject operateBasedOnMode(Mode mode, JSONObject params, HttpServletRequest request) + throws ServletException { JSONObject responseJsonObject; switch (mode) { case ADDFOLDER: @@ -357,11 +360,10 @@ public class PolicyManagerServlet extends HttpServlet { return responseJsonObject; } - private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) { List policyData = new ArrayList<>(); JSONArray policyList = null; - if(params.has("policyList")){ + if (params.has("policyList")) { policyList = (JSONArray) params.get("policyList"); } PolicyController controller = getPolicyControllerInstance(); @@ -370,66 +372,69 @@ public class PolicyManagerServlet extends HttpServlet { if (!lookupPolicyData(request, policyData, policyList, controller, resultList)) return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); - }catch(Exception e){ - LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e); + } catch (Exception e) { + LOGGER.error( + "Exception occured while reading policy Data from Policy Version table for Policy Search Data" + e); } return new JSONObject().put(RESULT, resultList); } - private boolean lookupPolicyData(HttpServletRequest request, List policyData, JSONArray policyList, PolicyController controller, List resultList){ + private boolean lookupPolicyData(HttpServletRequest request, List policyData, JSONArray policyList, + PolicyController controller, List resultList) { List roles; - Set scopes;//Get the Login Id of the User from Request - String userId = UserUtils.getUserSession(request).getOrgUserId(); + Set scopes;// Get the Login Id of the User from Request + String userId = UserUtils.getUserSession(request).getOrgUserId(); List userRoles = controller.getRoles(userId); Pair, List> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); roles = pair.u; scopes = pair.t; - if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { - if(scopes.isEmpty()){ + if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) { + if (scopes.isEmpty()) { return false; } Set tempScopes = scopes; - for(String scope : tempScopes){ + for (String scope : tempScopes) { addScope(scopes, scope); } } - if(policyList!= null){ - for(int i = 0; i < policyList.length(); i++){ + if (policyList != null) { + for (int i = 0; i < policyList.length(); i++) { String policyName = policyList.get(i).toString().replace(".xml", ""); - String version = policyName.substring(policyName.lastIndexOf('.')+1); + String version = policyName.substring(policyName.lastIndexOf('.') + 1); policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator); parsePolicyList(resultList, controller, policyName, version); } - }else { + } else { getPolicyDataForSUPERRoles(policyData, controller, resultList, roles, scopes); } return true; } - private void getPolicyDataForSUPERRoles(List policyData, PolicyController controller, List resultList, List roles, Set scopes) { - if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){ + private void getPolicyDataForSUPERRoles(List policyData, PolicyController controller, + List resultList, List roles, Set scopes) { + if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) { policyData = controller.getData(PolicyVersion.class); - }else{ + } else { List filterdatas = controller.getData(PolicyVersion.class); - for(Object filter : filterdatas) { + for (Object filter : filterdatas) { addFilterData(policyData, scopes, (PolicyVersion) filter); } } - if(!policyData.isEmpty()){ + if (!policyData.isEmpty()) { updateResultList(policyData, resultList); } } private void addFilterData(List policyData, Set scopes, PolicyVersion filter) { - try{ + try { String scopeName = filter.getPolicyName().substring(0, filter.getPolicyName().lastIndexOf(File.separator)); - if(scopes.contains(scopeName)){ + if (scopes.contains(scopeName)) { policyData.add(filter); } - }catch(Exception e){ - LOGGER.error("Exception occured while filtering policyversion data"+e); + } catch (Exception e) { + LOGGER.error("Exception occured while filtering policyversion data" + e); } } @@ -448,8 +453,9 @@ public class PolicyManagerServlet extends HttpServlet { } } - private void parsePolicyList(List resultList, PolicyController controller, String policyName, String version) { - if(policyName.contains(BACKSLASH)){ + private void parsePolicyList(List resultList, PolicyController controller, String policyName, + String version) { + if (policyName.contains(BACKSLASH)) { policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH); } String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0"; @@ -457,7 +463,7 @@ public class PolicyManagerServlet extends HttpServlet { pvParams.put("policyName", policyName); pvParams.put(VERSION, version); List activeData = controller.getDataByQuery(policyVersionQuery, pvParams); - if(!activeData.isEmpty()){ + if (!activeData.isEmpty()) { PolicyVersion policy = (PolicyVersion) activeData.get(0); JSONObject el = new JSONObject(); el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH)); @@ -473,7 +479,7 @@ public class PolicyManagerServlet extends HttpServlet { private void addScope(Set scopes, String scope) { List scopesList = queryPolicyEditorScopes(scope); - if(!scopesList.isEmpty()){ + if (!scopesList.isEmpty()) { for (Object aScopesList : scopesList) { PolicyEditorScopes tempScope = (PolicyEditorScopes) aScopesList; scopes.add(tempScope.getScopeName()); @@ -481,63 +487,64 @@ public class PolicyManagerServlet extends HttpServlet { } } - //Switch Version Functionality - private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{ + // Switch Version Functionality + private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException { String path = params.getString("path"); String userId = null; try { userId = UserUtils.getUserSession(request).getOrgUserId(); } catch (Exception e) { - LOGGER.error("Exception Occured while reading userid from cookie" +e); + LOGGER.error("Exception Occured while reading userid from cookie" + e); } String policyName; String removeExtension = path.replace(".xml", ""); - if(path.startsWith(FORWARD_SLASH)){ + if (path.startsWith(FORWARD_SLASH)) { policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.')); - }else{ + } else { policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.')); } String activePolicy; PolicyController controller = getPolicyControllerInstance(); - if(! params.toString().contains("activeVersion")){ + if (!params.toString().contains("activeVersion")) { return controller.switchVersionPolicyContent(policyName); } String activeVersion = params.getString("activeVersion"); String highestVersion = params.get("highestVersion").toString(); - if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){ + if (Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)) { return error("The Version shouldn't be greater than Highest Value"); } activePolicy = policyName + "." + activeVersion + ".xml"; String[] splitDBCheckName = modifyPolicyName(activePolicy); - String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0"; + String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0"; SimpleBindings policyParams = new SimpleBindings(); policyParams.put("splitDBCheckName_1", splitDBCheckName[1]); policyParams.put("splitDBCheckName_0", splitDBCheckName[0]); List policyEntity = controller.getDataByQuery(peQuery, policyParams); PolicyEntity pentity = (PolicyEntity) policyEntity.get(0); - if(pentity.isDeleted()){ + if (pentity.isDeleted()) { return error("The Policy is Not Existing in Workspace"); } - if(policyName.contains(FORWARD_SLASH)){ + if (policyName.contains(FORWARD_SLASH)) { policyName = policyName.replace(FORWARD_SLASH, File.separator); } - policyName = policyName.substring(policyName.indexOf(File.separator)+1); - if(policyName.contains(BACKSLASH)){ + policyName = policyName.substring(policyName.indexOf(File.separator) + 1); + if (policyName.contains(BACKSLASH)) { policyName = policyName.replace(File.separator, BACKSLASH); } - policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName; + policyName = splitDBCheckName[0].replace(".", File.separator) + File.separator + policyName; String watchPolicyName = policyName; - if(policyName.contains(FORWARD_SLASH)){ + if (policyName.contains(FORWARD_SLASH)) { policyName = policyName.replace(FORWARD_SLASH, File.separator); } - if(policyName.contains(BACKSLASH)){ + if (policyName.contains(BACKSLASH)) { policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH); } - String query = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION +activeVersion+"' where policy_name ='"+policyName+"' and id >0"; - //query the database + String query = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + activeVersion + "' where policy_name ='" + policyName + + "' and id >0"; + // query the database controller.executeQuery(query); - //Policy Notification + // Policy Notification PolicyVersion entity = new PolicyVersion(); entity.setPolicyName(watchPolicyName); entity.setActiveVersion(Integer.parseInt(activeVersion)); @@ -546,24 +553,24 @@ public class PolicyManagerServlet extends HttpServlet { return success(); } - //Describe Policy - private JSONObject describePolicy(JSONObject params) throws ServletException{ + // Describe Policy + private JSONObject describePolicy(JSONObject params) throws ServletException { JSONObject object; String path = params.getString("path"); String policyName; - if(path.startsWith(FORWARD_SLASH)){ + if (path.startsWith(FORWARD_SLASH)) { path = path.substring(1); - policyName = path.substring(path.lastIndexOf('/') +1); + policyName = path.substring(path.lastIndexOf('/') + 1); path = path.replace(FORWARD_SLASH, "."); - }else{ + } else { path = path.replace(FORWARD_SLASH, "."); policyName = path; } - if(path.contains(CONFIG2)){ + if (path.contains(CONFIG2)) { path = path.replace(CONFIG, CONFIG1); - }else if(path.contains(ACTION2)){ + } else if (path.contains(ACTION2)) { path = path.replace(ACTION, ACTION1); - }else if(path.contains(DECISION2)){ + } else if (path.contains(DECISION2)) { path = path.replace(DECISION, DECISION1); } PolicyController controller = getPolicyControllerInstance(); @@ -573,12 +580,12 @@ public class PolicyManagerServlet extends HttpServlet { peParams.put(SPLIT_1, split[1]); peParams.put(SPLIT_0, split[0]); List queryData; - if(PolicyController.isjUnit()){ + if (PolicyController.isjUnit()) { queryData = controller.getDataByQuery(query, null); - }else{ + } else { queryData = controller.getDataByQuery(query, peParams); } - if(queryData.isEmpty()){ + if (queryData.isEmpty()) { return error("Error Occured while Describing the Policy - query is empty"); } PolicyEntity entity = (PolicyEntity) queryData.get(0); @@ -593,7 +600,7 @@ public class PolicyManagerServlet extends HttpServlet { try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) { bw.write(entity.getPolicyData()); } catch (IOException e) { - LOGGER.error("Exception Occured while Describing the Policy"+e); + LOGGER.error("Exception Occured while Describing the Policy" + e); } object = HumanPolicyComponent.DescribePolicy(temp); try { @@ -604,7 +611,7 @@ public class PolicyManagerServlet extends HttpServlet { return object; } - //Get the List of Policies and Scopes for Showing in Editor tab + // Get the List of Policies and Scopes for Showing in Editor tab private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException { try { return processPolicyList(params, request); @@ -616,26 +623,27 @@ public class PolicyManagerServlet extends HttpServlet { private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException { PolicyController controller = getPolicyControllerInstance(); - //Get the Login Id of the User from Request + // Get the Login Id of the User from Request String testUserID = getTestUserId(); - String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId(); + String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId(); List userRoles = controller.getRoles(userId); Pair, List> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); List roles = pair.u; Set scopes = pair.t; + Map roleByScope = org.onap.policy.utils.UserUtils.getRoleByScope(userRoles); List resultList = new ArrayList<>(); - boolean onlyFolders = params.getBoolean("onlyFolders"); String path = params.getString("path"); - if(path.contains("..xml")){ + if (path.contains("..xml")) { path = path.replaceAll("..xml", "").trim(); } - if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { - if(scopes.isEmpty()){ + if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) { + if (scopes.isEmpty() + && !(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST))) { return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); - }else{ - if(!FORWARD_SLASH.equals(path)){ + } else { + if (!FORWARD_SLASH.equals(path)) { String tempScope = path.substring(1, path.length()); tempScope = tempScope.replace(FORWARD_SLASH, File.separator); scopes.add(tempScope); @@ -644,26 +652,27 @@ public class PolicyManagerServlet extends HttpServlet { } if (!FORWARD_SLASH.equals(path)) { - try{ - String scopeName = path.substring(path.indexOf('/') +1); - activePolicyList(scopeName, resultList, roles, scopes, onlyFolders); + try { + String scopeName = path.substring(path.indexOf('/') + 1); + activePolicyList(scopeName, resultList, roles, scopes, roleByScope); } catch (Exception ex) { - LOGGER.error("Error Occured While reading Policy Files List"+ex ); + LOGGER.error("Error Occured While reading Policy Files List" + ex); } return new JSONObject().put(RESULT, resultList); } - processRoles(scopes, roles, resultList); + processRoles(scopes, roles, resultList, roleByScope); return new JSONObject().put(RESULT, resultList); } - private void processRoles(Set scopes, List roles, List resultList) { - if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ + private void processRoles(Set scopes, List roles, List resultList, + Map roleByScope) { + if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) { List scopesList = queryPolicyEditorScopes(null); - for(Object list : scopesList){ + for (Object list : scopesList) { PolicyEditorScopes scope = (PolicyEditorScopes) list; - if(!(scope.getScopeName().contains(File.separator))){ + if (!(scope.getScopeName().contains(File.separator))) { JSONObject el = new JSONObject(); el.put(NAME, scope.getScopeName()); el.put(DATE, scope.getModifiedDate()); @@ -671,14 +680,18 @@ public class PolicyManagerServlet extends HttpServlet { el.put(TYPE, "dir"); el.put(CREATED_BY, scope.getUserCreatedBy().getUserName()); el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName()); - resultList.add(el); + el.put(ROLETYPE, roleByScope.get(ALLSCOPES)); + if (!scopes.contains(scope.getScopeName())) { + resultList.add(el); + } } } - }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){ - for(Object scope : scopes){ + } + if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) { + for (Object scope : scopes) { JSONObject el = new JSONObject(); List scopesList = queryPolicyEditorScopes(scope.toString()); - if(!scopesList.isEmpty()){ + if (!scopesList.isEmpty()) { PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0); el.put(NAME, scopeById.getScopeName()); el.put(DATE, scopeById.getModifiedDate()); @@ -686,39 +699,43 @@ public class PolicyManagerServlet extends HttpServlet { el.put(TYPE, "dir"); el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName()); el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName()); - resultList.add(el); + if (!(resultList).stream().anyMatch(item -> item.get("name").equals(scopeById.getScopeName()))) { + el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName())); + resultList.add(el); + } } } } } - private List queryPolicyEditorScopes(String scopeName){ + private List queryPolicyEditorScopes(String scopeName) { String scopeNamequery; SimpleBindings params = new SimpleBindings(); - if(scopeName == null){ + if (scopeName == null) { scopeNamequery = "from PolicyEditorScopes"; - }else{ + } else { scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME; params.put(SCOPE_NAME, scopeName + "%"); } PolicyController controller = getPolicyControllerInstance(); List scopesList; - if(PolicyController.isjUnit()){ + if (PolicyController.isjUnit()) { scopesList = controller.getDataByQuery(scopeNamequery, null); - }else{ + } else { scopesList = controller.getDataByQuery(scopeNamequery, params); } - return scopesList; + return scopesList; } - //Get Active Policy List based on Scope Selection form Policy Version table - private void activePolicyList(String inScopeName, List resultList, List roles, Set scopes, boolean onlyFolders){ + // Get Active Policy List based on Scope Selection form Policy Version table + private void activePolicyList(String inScopeName, List resultList, List roles, + Set scopes, Map roleByScope) { PolicyController controller = getPolicyControllerInstance(); String scopeName = inScopeName; - if(scopeName.contains(FORWARD_SLASH)){ + if (scopeName.contains(FORWARD_SLASH)) { scopeName = scopeName.replace(FORWARD_SLASH, File.separator); } - if(scopeName.contains(BACKSLASH)){ + if (scopeName.contains(BACKSLASH)) { scopeName = scopeName.replace(BACKSLASH, ESCAPE_BACKSLASH); } String query = "from PolicyVersion where POLICY_NAME like :scopeName"; @@ -729,40 +746,47 @@ public class PolicyManagerServlet extends HttpServlet { List activePolicies; List scopesList; - if(PolicyController.isjUnit()){ + if (PolicyController.isjUnit()) { activePolicies = controller.getDataByQuery(query, null); scopesList = controller.getDataByQuery(scopeNamequery, null); - }else{ + } else { activePolicies = controller.getDataByQuery(query, params); scopesList = controller.getDataByQuery(scopeNamequery, params); } - for(Object list : scopesList) { - scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list); + for (Object list : scopesList) { + scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope); } String scopeNameCheck; for (Object list : activePolicies) { PolicyVersion policy = (PolicyVersion) list; - String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator)); - if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ - if(scopeName.contains(ESCAPE_BACKSLASH)){ + String scopeNameValue = policy.getPolicyName().substring(0, + policy.getPolicyName().lastIndexOf(File.separator)); + if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) { + if (scopeName.contains(ESCAPE_BACKSLASH)) { scopeNameCheck = scopeName.replace(ESCAPE_BACKSLASH, File.separator); - }else{ + } else { scopeNameCheck = scopeName; } - if(scopeNameValue.equals(scopeNameCheck)){ + if (scopeNameValue.equals(scopeNameCheck)) { JSONObject el = new JSONObject(); - el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1)); + el.put(NAME, + policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1)); el.put(DATE, policy.getModifiedDate()); el.put(VERSION, policy.getActiveVersion()); el.put(SIZE, ""); el.put(TYPE, "file"); el.put(CREATED_BY, getUserName(policy.getCreatedBy())); el.put(MODIFIED_BY, getUserName(policy.getModifiedBy())); + String roleType = roleByScope.get(scopeNameValue); + if (roleType == null) { + roleType = roleByScope.get(ALLSCOPES); + } + el.put(ROLETYPE, roleType); resultList.add(el); } - }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){ + } else if (!scopes.isEmpty() && scopes.contains(scopeNameValue)) { JSONObject el = new JSONObject(); - el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1)); + el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1)); el.put(DATE, policy.getModifiedDate()); el.put(VERSION, policy.getActiveVersion()); el.put(SIZE, ""); @@ -774,20 +798,21 @@ public class PolicyManagerServlet extends HttpServlet { } } - private String checkScope(List resultList, String scopeName, PolicyEditorScopes scopeById) { + private String checkScope(List resultList, String scopeName, PolicyEditorScopes scopeById, + Map roleByScope) { String scope = scopeById.getScopeName(); - if(scope.contains(File.separator)){ + if (scope.contains(File.separator)) { String targetScope = scope.substring(0, scope.lastIndexOf(File.separator)); - if(scopeName.contains(ESCAPE_BACKSLASH)){ + if (scopeName.contains(ESCAPE_BACKSLASH)) { scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator); } - if(scope.contains(File.separator)){ - scope = scope.substring(targetScope.length()+1); - if(scope.contains(File.separator)){ + if (scope.contains(File.separator)) { + scope = scope.substring(targetScope.length() + 1); + if (scope.contains(File.separator)) { scope = scope.substring(0, scope.indexOf(File.separator)); } } - if(scopeName.equalsIgnoreCase(targetScope)){ + if (scopeName.equalsIgnoreCase(targetScope)) { JSONObject el = new JSONObject(); el.put(NAME, scope); el.put(DATE, scopeById.getModifiedDate()); @@ -795,27 +820,35 @@ public class PolicyManagerServlet extends HttpServlet { el.put(TYPE, "dir"); el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName()); el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName()); + String roleType = roleByScope.get(scopeName); + if (roleType == null) { + roleType = roleByScope.get(scopeName + File.separator + scope); + if (roleType == null) { + roleType = roleByScope.get(ALLSCOPES); + } + } + el.put(ROLETYPE, roleType); resultList.add(el); } } return scopeName; } - private String getUserName(String loginId){ + private String getUserName(String loginId) { PolicyController controller = getPolicyControllerInstance(); UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId); - if(userInfo == null){ + if (userInfo == null) { return SUPERADMIN; } return userInfo.getUserName(); } - //Rename Policy + // Rename Policy private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException { try { return handlePolicyRename(params, request); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e); return error(e.getMessage()); } } @@ -827,33 +860,34 @@ public class PolicyManagerServlet extends HttpServlet { String userId = UserUtils.getUserSession(request).getOrgUserId(); String oldPath = params.getString("path"); String newPath = params.getString("newPath"); - oldPath = oldPath.substring(oldPath.indexOf('/')+1); - newPath = newPath.substring(newPath.indexOf('/')+1); + oldPath = oldPath.substring(oldPath.indexOf('/') + 1); + newPath = newPath.substring(newPath.indexOf('/') + 1); String checkValidation; - if(oldPath.endsWith(".xml")){ + if (oldPath.endsWith(".xml")) { checkValidation = newPath.replace(".xml", ""); - checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf(".")); - checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH)+1); - if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)){ + checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, + checkValidation.lastIndexOf(".")); + checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH) + 1); + if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) { return error("Policy Rename Failed. The Name contains special characters."); } JSONObject result = policyRename(oldPath, newPath, userId); - if(!(Boolean)(result.getJSONObject(RESULT).get(SUCCESS))){ + if (!(Boolean) (result.getJSONObject(RESULT).get(SUCCESS))) { return result; } - }else{ + } else { String scopeName = oldPath; String newScopeName = newPath; - if(scopeName.contains(FORWARD_SLASH)){ + if (scopeName.contains(FORWARD_SLASH)) { scopeName = scopeName.replace(FORWARD_SLASH, File.separator); newScopeName = newScopeName.replace(FORWARD_SLASH, File.separator); } - checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator)+1); - if(scopeName.contains(BACKSLASH)){ + checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator) + 1); + if (scopeName.contains(BACKSLASH)) { scopeName = scopeName.replace(BACKSLASH, BACKSLASH_8TIMES); newScopeName = newScopeName.replace(BACKSLASH, BACKSLASH_8TIMES); } - if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)){ + if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) { return error("Scope Rename Failed. The Name contains special characters."); } PolicyController controller = getPolicyControllerInstance(); @@ -863,12 +897,13 @@ public class PolicyManagerServlet extends HttpServlet { pvParams.put(SCOPE_NAME, scopeName + "%"); List activePolicies = controller.getDataByQuery(query, pvParams); List scopesList = controller.getDataByQuery(scopeNamequery, pvParams); - for(Object object : activePolicies){ + for (Object object : activePolicies) { PolicyVersion activeVersion = (PolicyVersion) object; - String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "." + activeVersion.getActiveVersion() + ".xml"; + String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "." + + activeVersion.getActiveVersion() + ".xml"; String policyNewPath = policyOldPath.replace(oldPath, newPath); JSONObject result = policyRename(policyOldPath, policyNewPath, userId); - if(!(Boolean)(result.getJSONObject("result").get(SUCCESS))){ + if (!(Boolean) (result.getJSONObject("result").get(SUCCESS))) { isActive = true; policyActiveInPDP.add(policyOldPath); String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/')); @@ -876,17 +911,17 @@ public class PolicyManagerServlet extends HttpServlet { } } boolean rename = false; - if(activePolicies.size() != policyActiveInPDP.size()){ + if (activePolicies.size() != policyActiveInPDP.size()) { rename = true; } UserInfo userInfo = new UserInfo(); userInfo.setUserLoginId(userId); - if(policyActiveInPDP.isEmpty()){ + if (policyActiveInPDP.isEmpty()) { renameScope(scopesList, scopeName, newScopeName, controller); - }else if(rename){ + } else if (rename) { renameScope(scopesList, scopeName, newScopeName, controller); - for(String scope : scopeOfPolicyActiveInPDP){ + for (String scope : scopeOfPolicyActiveInPDP) { PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes(); editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES)); editorScopeEntity.setUserCreatedBy(userInfo); @@ -894,18 +929,20 @@ public class PolicyManagerServlet extends HttpServlet { controller.saveData(editorScopeEntity); } } - if(isActive){ - return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP); + if (isActive) { + return error("The Following policies rename failed. Since they are active in PDP Groups" + + policyActiveInPDP); } } return success(); } - private void renameScope(List scopesList, String inScopeName, String newScopeName, PolicyController controller){ - for(Object object : scopesList){ + private void renameScope(List scopesList, String inScopeName, String newScopeName, + PolicyController controller) { + for (Object object : scopesList) { PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object; String scopeName = inScopeName; - if(scopeName.contains(BACKSLASH_8TIMES)){ + if (scopeName.contains(BACKSLASH_8TIMES)) { scopeName = scopeName.replace(BACKSLASH_8TIMES, File.separator); newScopeName = newScopeName.replace(BACKSLASH_8TIMES, File.separator); } @@ -921,52 +958,55 @@ public class PolicyManagerServlet extends HttpServlet { PolicyController controller = getPolicyControllerInstance(); String policyVersionName = newPath.replace(".xml", ""); - String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator); + String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')) + .replace(FORWARD_SLASH, File.separator); String oldpolicyVersionName = oldPath.replace(".xml", ""); - String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator); + String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')) + .replace(FORWARD_SLASH, File.separator); String newpolicyName = newPath.replace("/", "."); String[] newPolicySplit = modifyPolicyName(newPath); String[] oldPolicySplit = modifyPolicyName(oldPath); - //Check PolicyEntity table with newPolicy Name + // Check PolicyEntity table with newPolicy Name String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0"; SimpleBindings policyParams = new SimpleBindings(); policyParams.put("newPolicySplit_1", newPolicySplit[1]); policyParams.put("newPolicySplit_0", newPolicySplit[0]); List queryData = controller.getDataByQuery(policyEntityquery, policyParams); - if(!queryData.isEmpty()){ + if (!queryData.isEmpty()) { return error("Policy rename failed. Since, the policy with same name already exists."); } - //Query the Policy Entity with oldPolicy Name + // Query the Policy Entity with oldPolicy Name String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.')); String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0"; SimpleBindings params = new SimpleBindings(); params.put("policyEntityCheck", policyEntityCheck + "%"); params.put("oldPolicySplit_0", oldPolicySplit[0]); List oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params); - if(oldEntityData.isEmpty()){ - return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin."); + if (oldEntityData.isEmpty()) { + return error( + "Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin."); } StringBuilder groupQuery = new StringBuilder(); groupQuery.append("FROM PolicyGroupEntity where ("); SimpleBindings geParams = new SimpleBindings(); - for(int i=0; i groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams); - if(! groupEntityData.isEmpty()){ + if (!groupEntityData.isEmpty()) { return error("Policy rename failed. Since the policy or its version is active in PDP Groups."); } for (Object anOldEntityData : oldEntityData) { @@ -975,13 +1015,14 @@ public class PolicyManagerServlet extends HttpServlet { checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.')); String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator) + 1); if (checkEntityName.equals(originalPolicyName)) { - checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId); + checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0], + oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId); } } return success(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e); return error(e.getMessage()); } } @@ -992,18 +1033,19 @@ public class PolicyManagerServlet extends HttpServlet { private String[] modifyPolicyName(String separator, String pathName) { String policyName = pathName.replace(separator, "."); - if(policyName.contains(CONFIG2)){ + if (policyName.contains(CONFIG2)) { policyName = policyName.replace(CONFIG, CONFIG1); - }else if(policyName.contains(ACTION2)){ + } else if (policyName.contains(ACTION2)) { policyName = policyName.replace(ACTION, ACTION1); - }else if(policyName.contains(DECISION2)){ + } else if (policyName.contains(DECISION2)) { policyName = policyName.replace(DECISION, DECISION1); } return policyName.split(":"); } - private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension, - String policyName, String newpolicyName, String oldpolicyName, String userId) { + private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, + String oldScope, String removeoldPolicyExtension, String policyName, String newpolicyName, + String oldpolicyName, String userId) { try { ConfigurationDataEntity configEntity = entity.getConfigurationData(); ActionBodyEntity actionEntity = entity.getActionBodyEntity(); @@ -1011,35 +1053,45 @@ public class PolicyManagerServlet extends HttpServlet { String oldPolicyNameWithoutExtension = removeoldPolicyExtension; String newPolicyNameWithoutExtension = removenewPolicyExtension; - if(removeoldPolicyExtension.endsWith(".xml")){ - oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.')); - newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.')); + if (removeoldPolicyExtension.endsWith(".xml")) { + oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, + oldPolicyNameWithoutExtension.indexOf('.')); + newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, + newPolicyNameWithoutExtension.indexOf('.')); } - entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension)); - entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension)); + entity.setPolicyName( + entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension)); + entity.setPolicyData(entity.getPolicyData().replace(oldScope + "." + oldPolicyNameWithoutExtension, + newScope + "." + newPolicyNameWithoutExtension)); entity.setScope(newScope); entity.setModifiedBy(userId); String oldConfigurationName = null; String newConfigurationName = null; - if(newpolicyName.contains(CONFIG2)){ + if (newpolicyName.contains(CONFIG2)) { oldConfigurationName = configEntity.getConfigurationName(); - configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension)); + configEntity.setConfigurationName( + configEntity.getConfigurationName().replace(oldScope + "." + oldPolicyNameWithoutExtension, + newScope + "." + newPolicyNameWithoutExtension)); controller.updateData(configEntity); newConfigurationName = configEntity.getConfigurationName(); File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName); - if(file.exists()){ - File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName); + if (file.exists()) { + File renamefile = new File( + PolicyController.getConfigHome() + File.separator + newConfigurationName); file.renameTo(renamefile); } - }else if(newpolicyName.contains(ACTION2)){ + } else if (newpolicyName.contains(ACTION2)) { oldConfigurationName = actionEntity.getActionBodyName(); - actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension)); + actionEntity.setActionBody( + actionEntity.getActionBody().replace(oldScope + "." + oldPolicyNameWithoutExtension, + newScope + "." + newPolicyNameWithoutExtension)); controller.updateData(actionEntity); newConfigurationName = actionEntity.getActionBodyName(); File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName); - if(file.exists()){ - File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName); + if (file.exists()) { + File renamefile = new File( + PolicyController.getActionHome() + File.separator + newConfigurationName); file.renameTo(renamefile); } } @@ -1047,25 +1099,26 @@ public class PolicyManagerServlet extends HttpServlet { PolicyRestController restController = new PolicyRestController(); restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName); - PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName); + PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", + oldpolicyName); versionEntity.setPolicyName(policyName); versionEntity.setModifiedBy(userId); controller.updateData(versionEntity); - String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1); - String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1); - if(movePolicyCheck.equals(moveOldPolicyCheck)){ + String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator) + 1); + String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator) + 1); + if (movePolicyCheck.equals(moveOldPolicyCheck)) { controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move"); - }else{ + } else { controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename"); } } catch (Exception e) { - LOGGER.error(EXCEPTION_OCCURED +e); + LOGGER.error(EXCEPTION_OCCURED + e); throw e; } } private void cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope, - String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws IOException{ + String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws IOException { String queryEntityName; PolicyController controller = getPolicyControllerInstance(); PolicyEntity cloneEntity = new PolicyEntity(); @@ -1074,14 +1127,16 @@ public class PolicyManagerServlet extends HttpServlet { String removenewPolicyExtension = inRemovenewPolicyExtension; removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", ""); removenewPolicyExtension = removenewPolicyExtension.replace(".xml", ""); - cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension)); + cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope + "." + removeoldPolicyExtension, + newScope + "." + removenewPolicyExtension)); cloneEntity.setScope(entity.getScope()); String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", ""); String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", ""); String newConfigurationName = null; - if(newpolicyName.contains(CONFIG2)){ + if (newpolicyName.contains(CONFIG2)) { ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity(); - configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension)); + configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName() + .replace(oldScope + "." + oldConfigRemoveExtension, newScope + "." + newConfigRemoveExtension)); queryEntityName = configurationDataEntity.getConfigurationName(); configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody()); configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType()); @@ -1089,33 +1144,38 @@ public class PolicyManagerServlet extends HttpServlet { configurationDataEntity.setCreatedBy(userId); configurationDataEntity.setModifiedBy(userId); controller.saveData(configurationDataEntity); - ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName); + ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller + .getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName); cloneEntity.setConfigurationData(configEntiy); newConfigurationName = configEntiy.getConfigurationName(); - try (FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName); - BufferedWriter bw = new BufferedWriter(fw)){ + try (FileWriter fw = new FileWriter( + PolicyController.getConfigHome() + File.separator + newConfigurationName); + BufferedWriter bw = new BufferedWriter(fw)) { bw.write(configEntiy.getConfigBody()); } catch (IOException e) { - LOGGER.error("Exception Occured While cloning the configuration file"+e); + LOGGER.error("Exception Occured While cloning the configuration file" + e); throw e; } - }else if(newpolicyName.contains(ACTION2)){ + } else if (newpolicyName.contains(ACTION2)) { ActionBodyEntity actionBodyEntity = new ActionBodyEntity(); - actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension)); + actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName() + .replace(oldScope + "." + oldConfigRemoveExtension, newScope + "." + newConfigRemoveExtension)); queryEntityName = actionBodyEntity.getActionBodyName(); actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody()); actionBodyEntity.setDeleted(false); actionBodyEntity.setCreatedBy(userId); actionBodyEntity.setModifiedBy(userId); controller.saveData(actionBodyEntity); - ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName); + ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, + "actionBodyName", queryEntityName); cloneEntity.setActionBodyEntity(actionEntiy); newConfigurationName = actionEntiy.getActionBodyName(); - try (FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName); - BufferedWriter bw = new BufferedWriter(fw)){ + try (FileWriter fw = new FileWriter( + PolicyController.getActionHome() + File.separator + newConfigurationName); + BufferedWriter bw = new BufferedWriter(fw)) { bw.write(actionEntiy.getActionBody()); } catch (IOException e) { - LOGGER.error("Exception Occured While cloning the configuration file"+e); + LOGGER.error("Exception Occured While cloning the configuration file" + e); throw e; } } @@ -1125,44 +1185,46 @@ public class PolicyManagerServlet extends HttpServlet { cloneEntity.setModifiedBy(userId); controller.saveData(cloneEntity); - //Notify others paps regarding clone policy. + // Notify others paps regarding clone policy. PolicyRestController restController = new PolicyRestController(); restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null); } - //Clone the Policy + // Clone the Policy private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException { try { String userId = UserUtils.getUserSession(request).getOrgUserId(); String oldPath = params.getString("path"); String newPath = params.getString("newPath"); - oldPath = oldPath.substring(oldPath.indexOf('/')+1); - newPath = newPath.substring(newPath.indexOf('/')+1); + oldPath = oldPath.substring(oldPath.indexOf('/') + 1); + newPath = newPath.substring(newPath.indexOf('/') + 1); String policyVersionName = newPath.replace(".xml", ""); - String version = policyVersionName.substring(policyVersionName.indexOf('.')+1); - String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator); + String version = policyVersionName.substring(policyVersionName.indexOf('.') + 1); + String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')) + .replace(FORWARD_SLASH, File.separator); String newpolicyName = newPath.replace(FORWARD_SLASH, "."); String orignalPolicyName = oldPath.replace(FORWARD_SLASH, "."); String newPolicyCheck = newpolicyName; - if(newPolicyCheck.contains(CONFIG2)){ + if (newPolicyCheck.contains(CONFIG2)) { newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1); - }else if(newPolicyCheck.contains(ACTION2)){ + } else if (newPolicyCheck.contains(ACTION2)) { newPolicyCheck = newPolicyCheck.replace(ACTION, ACTION1); - }else if(newPolicyCheck.contains(DECISION2)){ + } else if (newPolicyCheck.contains(DECISION2)) { newPolicyCheck = newPolicyCheck.replace(DECISION, DECISION1); } - if(!newPolicyCheck.contains(":")){ + if (!newPolicyCheck.contains(":")) { return error("Policy Clone Failed. The Name contains special characters."); } String[] newPolicySplit = newPolicyCheck.split(":"); String checkValidation = newPolicySplit[1].replace(".xml", ""); - checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf(".")); - if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)){ + checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, + checkValidation.lastIndexOf(".")); + if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) { return error("Policy Clone Failed. The Name contains special characters."); } @@ -1173,35 +1235,36 @@ public class PolicyManagerServlet extends HttpServlet { PolicyEntity entity = null; boolean success = false; - //Check PolicyEntity table with newPolicy Name + // Check PolicyEntity table with newPolicy Name String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0"; SimpleBindings policyParams = new SimpleBindings(); policyParams.put("newPolicySplit_1", newPolicySplit[1]); policyParams.put("newPolicySplit_0", newPolicySplit[0]); List queryData = controller.getDataByQuery(policyEntityquery, policyParams); - if(!queryData.isEmpty()){ + if (!queryData.isEmpty()) { return error("Policy already exists with same name"); } - //Query the Policy Entity with oldPolicy Name + // Query the Policy Entity with oldPolicy Name policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0"; SimpleBindings peParams = new SimpleBindings(); peParams.put("oldPolicySplit_1", oldPolicySplit[1]); peParams.put("oldPolicySplit_0", oldPolicySplit[0]); - if(PolicyController.isjUnit()){ + if (PolicyController.isjUnit()) { queryData = controller.getDataByQuery(policyEntityquery, null); - }else{ + } else { queryData = controller.getDataByQuery(policyEntityquery, peParams); } - if(!queryData.isEmpty()){ + if (!queryData.isEmpty()) { entity = (PolicyEntity) queryData.get(0); } - if(entity != null){ - cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId); + if (entity != null) { + cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], + newPolicySplit[1], entity, userId); success = true; } - if(success){ + if (success) { PolicyVersion entityItem = new PolicyVersion(); entityItem.setActiveVersion(Integer.parseInt(version)); entityItem.setHigherVersion(Integer.parseInt(version)); @@ -1212,7 +1275,7 @@ public class PolicyManagerServlet extends HttpServlet { controller.saveData(entityItem); } - LOGGER.debug("copy from: {} to: {}" + oldPath +newPath); + LOGGER.debug("copy from: {} to: {}" + oldPath + newPath); return success(); } catch (Exception e) { @@ -1221,7 +1284,7 @@ public class PolicyManagerServlet extends HttpServlet { } } - //Delete Policy or Scope Functionality + // Delete Policy or Scope Functionality private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException { PolicyController controller = getPolicyControllerInstance(); PolicyRestController restController = new PolicyRestController(); @@ -1231,81 +1294,96 @@ public class PolicyManagerServlet extends HttpServlet { String userId = UserUtils.getUserSession(request).getOrgUserId(); String deleteVersion = ""; String path = params.getString("path"); - LOGGER.debug("delete {}" +path); - if(params.has("deleteVersion")){ - deleteVersion = params.getString("deleteVersion"); + LOGGER.debug("delete {}" + path); + if (params.has("deleteVersion")) { + deleteVersion = params.getString("deleteVersion"); } - path = path.substring(path.indexOf('/')+1); + path = path.substring(path.indexOf('/') + 1); String policyNamewithExtension = path.replace(FORWARD_SLASH, File.separator); String policyVersionName = policyNamewithExtension.replace(".xml", ""); String query; SimpleBindings policyParams = new SimpleBindings(); - if(path.endsWith(".xml")){ + if (path.endsWith(".xml")) { policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')); String[] split = modifyPolicyName(File.separator, policyNamewithoutExtension); query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0"; policyParams.put(SPLIT_1, split[1] + "%"); policyParams.put(SPLIT_0, split[0]); - }else{ + } else { policyNamewithoutExtension = path.replace(File.separator, "."); - query = "FROM PolicyEntity where scope like :policyNamewithoutExtension"; - policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%"); + query = "FROM PolicyEntity where scope like :policyNamewithoutExtension or scope = :exactScope"; + policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + ".%"); + policyParams.put("exactScope", policyNamewithoutExtension); } List policyEntityobjects = controller.getDataByQuery(query, policyParams); String activePolicyName = null; boolean pdpCheck = false; - if(path.endsWith(".xml")){ + if (path.endsWith(".xml")) { policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator); - int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.')+1)); - if("ALL".equals(deleteVersion)){ - if(!policyEntityobjects.isEmpty()){ - for(Object object : policyEntityobjects){ + int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.') + 1)); + if ("ALL".equals(deleteVersion)) { + if (!policyEntityobjects.isEmpty()) { + for (Object object : policyEntityobjects) { policyEntity = (PolicyEntity) object; - String groupEntityquery = "from PolicyGroupEntity where policyid ='"+policyEntity.getPolicyId()+"'"; + String groupEntityquery = "from PolicyGroupEntity where policyid ='" + + policyEntity.getPolicyId() + "'"; SimpleBindings pgeParams = new SimpleBindings(); List groupobject = controller.getDataByQuery(groupEntityquery, pgeParams); - if(!groupobject.isEmpty()){ + if (!groupobject.isEmpty()) { pdpCheck = true; - activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName(); - }else{ - //Delete the entity from Elastic Search Database + activePolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + } else { + // Delete the entity from Elastic Search Database String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); restController.deleteElasticData(searchFileName); - //Delete the entity from Policy Entity table + // Delete the entity from Policy Entity table controller.deleteData(policyEntity); - if(policyNamewithoutExtension.contains(CONFIG2)){ - Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName())); + if (policyNamewithoutExtension.contains(CONFIG2)) { + Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + + policyEntity.getConfigurationData().getConfigurationName())); controller.deleteData(policyEntity.getConfigurationData()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getConfigurationData().getConfigurationName()); - }else if(policyNamewithoutExtension.contains(ACTION2)){ - Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName())); + restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, + policyEntity.getConfigurationData().getConfigurationName()); + } else if (policyNamewithoutExtension.contains(ACTION2)) { + Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + + policyEntity.getActionBodyEntity().getActionBodyName())); controller.deleteData(policyEntity.getActionBodyEntity()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getActionBodyEntity().getActionBodyName()); + restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, + policyEntity.getActionBodyEntity().getActionBodyName()); } } } } - //Policy Notification + // Policy Notification PolicyVersion versionEntity = new PolicyVersion(); versionEntity.setPolicyName(policyNamewithoutExtension); versionEntity.setModifiedBy(userId); controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll"); - if(pdpCheck){ - //Delete from policyVersion table + if (pdpCheck) { + // Delete from policyVersion table String getActivePDPPolicyVersion = activePolicyName.replace(".xml", ""); - getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.')+1); - String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION +getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH)+"' and id >0"; + getActivePDPPolicyVersion = getActivePDPPolicyVersion + .substring(getActivePDPPolicyVersion.lastIndexOf('.') + 1); + String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + getActivePDPPolicyVersion + + "' , highest_version='" + getActivePDPPolicyVersion + "' where policy_name ='" + + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0"; controller.executeQuery(policyVersionQuery); - return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName); - }else{ - //No Active Policy in PDP. So, deleting all entries from policyVersion table - String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME +policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH)+"' and id >0"; + return error( + "Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: " + + activePolicyName); + } else { + // No Active Policy in PDP. So, deleting all entries from policyVersion table + String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME + + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0"; controller.executeQuery(policyVersionQuery); } - }else if("CURRENT".equals(deleteVersion)){ - String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1); - String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, "."); + } else if ("CURRENT".equals(deleteVersion)) { + String currentVersionPolicyName = policyNamewithExtension + .substring(policyNamewithExtension.lastIndexOf(File.separator) + 1); + String currentVersionScope = policyNamewithExtension + .substring(0, policyNamewithExtension.lastIndexOf(File.separator)) + .replace(File.separator, "."); query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope"; SimpleBindings peParams = new SimpleBindings(); @@ -1313,10 +1391,10 @@ public class PolicyManagerServlet extends HttpServlet { peParams.put("currentVersionScope", currentVersionScope); List policyEntitys = controller.getDataByQuery(query, peParams); - if(!policyEntitys.isEmpty()){ + if (!policyEntitys.isEmpty()) { policyEntity = (PolicyEntity) policyEntitys.get(0); } - if(policyEntity == null){ + if (policyEntity == null) { return success(); } @@ -1324,39 +1402,45 @@ public class PolicyManagerServlet extends HttpServlet { SimpleBindings geParams = new SimpleBindings(); geParams.put("policyEntityId", policyEntity.getPolicyId()); List groupobject = controller.getDataByQuery(groupEntityquery, geParams); - if(!groupobject.isEmpty()){ - return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'"); + if (!groupobject.isEmpty()) { + return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '" + + policyEntity.getScope() + "." + policyEntity.getPolicyName() + "'"); } - //Delete the entity from Elastic Search Database + // Delete the entity from Elastic Search Database String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); restController.deleteElasticData(searchFileName); - //Delete the entity from Policy Entity table + // Delete the entity from Policy Entity table controller.deleteData(policyEntity); - if(policyNamewithoutExtension.contains(CONFIG2)){ - Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName())); + if (policyNamewithoutExtension.contains(CONFIG2)) { + Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + + policyEntity.getConfigurationData().getConfigurationName())); controller.deleteData(policyEntity.getConfigurationData()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getConfigurationData().getConfigurationName()); - }else if(policyNamewithoutExtension.contains(ACTION2)){ - Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName())); + restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, + policyEntity.getConfigurationData().getConfigurationName()); + } else if (policyNamewithoutExtension.contains(ACTION2)) { + Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + + policyEntity.getActionBodyEntity().getActionBodyName())); controller.deleteData(policyEntity.getActionBodyEntity()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getActionBodyEntity().getActionBodyName()); + restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, + policyEntity.getActionBodyEntity().getActionBodyName()); } - if(version > 1){ + if (version > 1) { int highestVersion = 0; - if(!policyEntityobjects.isEmpty()){ - for(Object object : policyEntityobjects){ + if (!policyEntityobjects.isEmpty()) { + for (Object object : policyEntityobjects) { policyEntity = (PolicyEntity) object; String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); - int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1)); - if(policyEntityVersion > highestVersion && policyEntityVersion != version){ + int policyEntityVersion = Integer + .parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.') + 1)); + if (policyEntityVersion > highestVersion && policyEntityVersion != version) { highestVersion = policyEntityVersion; } } } - //Policy Notification + // Policy Notification PolicyVersion entity = new PolicyVersion(); entity.setPolicyName(policyNamewithoutExtension); entity.setActiveVersion(highestVersion); @@ -1364,66 +1448,78 @@ public class PolicyManagerServlet extends HttpServlet { controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne"); String updatequery; - if(highestVersion != 0){ - updatequery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION +highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'"; - }else{ - updatequery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + if (highestVersion != 0) { + updatequery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + highestVersion + + "' , highest_version='" + highestVersion + "' where policy_name ='" + + policyNamewithoutExtension.replace("\\", "\\\\") + "'"; + } else { + updatequery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME + + policyNamewithoutExtension.replace("\\", "\\\\") + "' and id >0"; } controller.executeQuery(updatequery); - }else{ - String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + } else { + String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME + + policyNamewithoutExtension.replace("\\", "\\\\") + "' and id >0"; controller.executeQuery(policyVersionQuery); } } - }else{ + } else { List activePoliciesInPDP = new ArrayList<>(); - if(policyEntityobjects.isEmpty()){ - String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace(BACKSLASH, ESCAPE_BACKSLASH)+PERCENT_AND_ID_GT_0; + if (policyEntityobjects.isEmpty()) { + String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '" + + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0; controller.executeQuery(policyScopeQuery); return success(); } - for(Object object : policyEntityobjects){ + for (Object object : policyEntityobjects) { policyEntity = (PolicyEntity) object; String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId"; SimpleBindings geParams = new SimpleBindings(); geParams.put("policyEntityId", policyEntity.getPolicyId()); List groupobject = controller.getDataByQuery(groupEntityquery, geParams); - if(!groupobject.isEmpty()){ + if (!groupobject.isEmpty()) { pdpCheck = true; - activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName()); - }else{ - //Delete the entity from Elastic Search Database + activePoliciesInPDP.add(policyEntity.getScope() + "." + policyEntity.getPolicyName()); + } else { + // Delete the entity from Elastic Search Database String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); restController.deleteElasticData(searchFileName); - //Delete the entity from Policy Entity table + // Delete the entity from Policy Entity table controller.deleteData(policyEntity); policyNamewithoutExtension = policyEntity.getPolicyName(); - if(policyNamewithoutExtension.contains(CONFIG2)){ - Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName())); + if (policyNamewithoutExtension.contains(CONFIG2)) { + Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + + policyEntity.getConfigurationData().getConfigurationName())); controller.deleteData(policyEntity.getConfigurationData()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getConfigurationData().getConfigurationName()); - }else if(policyNamewithoutExtension.contains(ACTION2)){ - Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName())); + restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, + policyEntity.getConfigurationData().getConfigurationName()); + } else if (policyNamewithoutExtension.contains(ACTION2)) { + Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + + policyEntity.getActionBodyEntity().getActionBodyName())); controller.deleteData(policyEntity.getActionBodyEntity()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getActionBodyEntity().getActionBodyName()); + restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, + policyEntity.getActionBodyEntity().getActionBodyName()); } } } - //Delete from policyVersion and policyEditor Scope table - String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace(BACKSLASH, ESCAPE_BACKSLASH)+PERCENT_AND_ID_GT_0; + // Delete from policyVersion and policyEditor Scope table + String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '" + + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + File.separator + PERCENT_AND_ID_GT_0; controller.executeQuery(policyVersionQuery); - //Policy Notification + // Policy Notification PolicyVersion entity = new PolicyVersion(); entity.setPolicyName(path); entity.setModifiedBy(userId); controller.watchPolicyFunction(entity, path, "DeleteScope"); - if(pdpCheck){ - //Add Active Policies List to PolicyVersionTable + if (pdpCheck) { + // Add Active Policies List to PolicyVersionTable for (String anActivePoliciesInPDP : activePoliciesInPDP) { String activePDPPolicyName = anActivePoliciesInPDP.replace(".xml", ""); - int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.') + 1)); - activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')).replace(".", File.separator); + int activePDPPolicyVersion = Integer + .parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.') + 1)); + activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')) + .replace(".", File.separator); PolicyVersion insertactivePDPVersion = new PolicyVersion(); insertactivePDPVersion.setPolicyName(activePDPPolicyName); insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion); @@ -1433,9 +1529,11 @@ public class PolicyManagerServlet extends HttpServlet { controller.saveData(insertactivePDPVersion); } - return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP); - }else{ - String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace(BACKSLASH, ESCAPE_BACKSLASH)+PERCENT_AND_ID_GT_0; + return error("All the Policies has been deleted in Scope. Except the following list of Policies:" + + activePoliciesInPDP); + } else { + String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '" + + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0; controller.executeQuery(policyScopeQuery); } @@ -1447,14 +1545,14 @@ public class PolicyManagerServlet extends HttpServlet { } } - //Edit the Policy + // Edit the Policy private JSONObject editFile(JSONObject params) throws ServletException { // get content try { PolicyController controller = getPolicyControllerInstance(); String mode = params.getString("mode"); String path = params.getString("path"); - LOGGER.debug("editFile path: {}"+ path); + LOGGER.debug("editFile path: {}" + path); String domain = path.substring(1, path.lastIndexOf('/')); domain = domain.replace(FORWARD_SLASH, "."); @@ -1469,23 +1567,22 @@ public class PolicyManagerServlet extends HttpServlet { peParams.put(SPLIT_1, split[1]); peParams.put(SPLIT_0, split[0]); List queryData; - if(PolicyController.isjUnit()){ + if (PolicyController.isjUnit()) { queryData = controller.getDataByQuery(query, null); - }else{ + } else { queryData = controller.getDataByQuery(query, peParams); } PolicyEntity entity = (PolicyEntity) queryData.get(0); InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8)); - Object policy = XACMLPolicyScanner.readPolicy(stream); - PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); + PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); policyAdapter.setData(policy); - if("viewPolicy".equalsIgnoreCase(mode)){ + if ("viewPolicy".equalsIgnoreCase(mode)) { policyAdapter.setReadOnly(true); policyAdapter.setEditPolicy(false); - }else{ + } else { policyAdapter.setReadOnly(false); policyAdapter.setEditPolicy(true); } @@ -1494,10 +1591,10 @@ public class PolicyManagerServlet extends HttpServlet { policyAdapter.setPolicyData(policy); String policyName = path.replace(".xml", ""); policyName = policyName.substring(0, policyName.lastIndexOf('.')); - policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.')+1)); + policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.') + 1)); PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance(); - Objects.requireNonNull(setpolicyAdapter).configure(policyAdapter,entity); + Objects.requireNonNull(setpolicyAdapter).configure(policyAdapter, entity); policyAdapter.setParentPath(null); ObjectMapper mapper = new ObjectMapper(); @@ -1511,44 +1608,46 @@ public class PolicyManagerServlet extends HttpServlet { } } - //Add Scopes + // Add Scopes private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException { PolicyController controller = getPolicyControllerInstance(); String name = ""; try { String userId = UserUtils.getUserSession(request).getOrgUserId(); String path = params.getString("path"); - try{ - if(params.has(SUB_SCOPENAME)){ - if(! "".equals(params.getString(SUB_SCOPENAME))) { - name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator +params.getString(SUB_SCOPENAME); + try { + if (params.has(SUB_SCOPENAME)) { + if (!"".equals(params.getString(SUB_SCOPENAME))) { + name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator + + params.getString(SUB_SCOPENAME); } - }else{ + } else { name = params.getString(NAME); } - }catch(Exception e){ + } catch (Exception e) { name = params.getString(NAME); - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope" + e); } String validateName; - if(name.contains(File.separator)){ - validateName = name.substring(name.lastIndexOf(File.separator)+1); - }else{ + if (name.contains(File.separator)) { + validateName = name.substring(name.lastIndexOf(File.separator) + 1); + } else { validateName = name; } - if(!name.isEmpty()){ + if (!name.isEmpty()) { String validate = PolicyUtils.policySpecialCharValidator(validateName); - if(!validate.contains(SUCCESS)){ + if (!validate.contains(SUCCESS)) { return error(validate); } } - LOGGER.debug("addFolder path: {} name: {}" + path +name); - if(! "".equals(name)){ - if(name.startsWith(File.separator)){ + LOGGER.debug("addFolder path: {} name: {}" + path + name); + if (!"".equals(name)) { + if (name.startsWith(File.separator)) { name = name.substring(1); } - PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, SCOPE_NAME, name); - if(entity == null){ + PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, + SCOPE_NAME, name); + if (entity == null) { UserInfo userInfo = new UserInfo(); userInfo.setUserLoginId(userId); PolicyEditorScopes newScope = new PolicyEditorScopes(); @@ -1556,7 +1655,7 @@ public class PolicyManagerServlet extends HttpServlet { newScope.setUserCreatedBy(userInfo); newScope.setUserModifiedBy(userInfo); controller.saveData(newScope); - }else{ + } else { return error("Scope Already Exists"); } } @@ -1567,7 +1666,7 @@ public class PolicyManagerServlet extends HttpServlet { } } - //Return Error Object + // Return Error Object private JSONObject error(String msg) throws ServletException { try { JSONObject result = new JSONObject(); @@ -1579,7 +1678,7 @@ public class PolicyManagerServlet extends HttpServlet { } } - //Return Success Object + // Return Success Object private JSONObject success() throws ServletException { try { JSONObject result = new JSONObject(); @@ -1591,7 +1690,7 @@ public class PolicyManagerServlet extends HttpServlet { } } - private PolicyController getPolicyControllerInstance(){ + private PolicyController getPolicyControllerInstance() { return policyController != null ? getPolicyController() : new PolicyController(); } 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 e5e868fd9..018668fc7 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -20,7 +20,6 @@ package org.onap.policy.controller; - import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -72,336 +71,345 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; - @Controller -@RequestMapping({"/"}) -public class AutoPushController extends RestrictedBaseController{ +@RequestMapping({ "/" }) +public class AutoPushController extends RestrictedBaseController { - private static final Logger logger = FlexLogger.getLogger(AutoPushController.class); + private static final Logger logger = FlexLogger.getLogger(AutoPushController.class); private static final String UTF8 = "UTF-8"; - - @Autowired - CommonClassDao commonClassDao; - - private PDPGroupContainer container; - protected List groups = Collections.synchronizedList(new ArrayList()); - - private PDPPolicyContainer policyContainer; - - private PolicyController policyController; - public PolicyController getPolicyController() { - return policyController; - } - - public void setPolicyController(PolicyController policyController) { - this.policyController = policyController; - } - - private List data; - - public synchronized void refreshGroups() { - synchronized(this.groups) { - this.groups.clear(); - try { - PolicyController controller = getPolicyControllerInstance(); - this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); - } catch (PAPException e) { - String message = "Unable to retrieve Groups from server: " + e; - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - } - - } - } - - private PolicyController getPolicyControllerInstance(){ - return policyController != null ? getPolicyController() : new PolicyController(); - } - - @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){ - try{ - Set scopes; - List roles; - data = new ArrayList<>(); - String userId = UserUtils.getUserSession(request).getOrgUserId(); - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - PolicyController controller = policyController != null ? getPolicyController() : new PolicyController(); - List 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]); - } - }else{ - if(!"".equals(userRole.getScope())){ - scopes.add(userRole.getScope()); - } - } - } - } - if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) { - data = commonClassDao.getData(PolicyVersion.class); - }else{ - if(!scopes.isEmpty()){ - for(String scope : scopes){ - scope += "%"; - String query = "From PolicyVersion where policy_name like :scope and id > 0"; - SimpleBindings params = new SimpleBindings(); - params.put("scope", scope); - List filterdatas = commonClassDao.getDataByQuery(query, params); - if(filterdatas != null){ - for(int i =0; i < filterdatas.size(); i++){ - data.add(filterdatas.get(i)); - } - } - } - }else{ - PolicyVersion emptyPolicyName = new PolicyVersion(); - emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); - data.add(emptyPolicyName); - } - } - 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); - } - } - - @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { - try { - ArrayList selectedPDPS = new ArrayList<>(); - ArrayList selectedPoliciesInUI = new ArrayList<>(); - PolicyController controller = getPolicyControllerInstance(); - this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); - ObjectMapper mapper = new ObjectMapper(); - this.container = new PDPGroupContainer(controller.getPapEngine()); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - - String userId = UserUtils.getUserSession(request).getOrgUserId(); - logger.info("****************************************Logging UserID while Pushing Policy to PDP Group*****************************************"); - logger.info("UserId: " + userId + "Push Policy Data: "+ root.get("pushTabData").toString()); - logger.info("***********************************************************************************************************************************"); - - AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class); - for (Object pdpGroupId : adapter.getPdpDatas()) { - LinkedHashMap selectedPDP = (LinkedHashMap)pdpGroupId; - for(OnapPDPGroup pdpGroup : this.groups){ - if(pdpGroup.getId().equals(selectedPDP.get("id"))){ - selectedPDPS.add(pdpGroup); - } - } - } - - for (Object policyId : adapter.getPolicyDatas()) { - LinkedHashMap selected = (LinkedHashMap)policyId; - String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml"; - selectedPoliciesInUI.add(policyName); - } - - for (Object pdpDestinationGroupId : selectedPDPS) { - Set currentPoliciesInGroup = new HashSet<>(); - Set selectedPolicies = new HashSet<>(); - for (String policyId : selectedPoliciesInUI) { - logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId); - - // - // Get the current selection - String selectedItem = policyId; - // - assert selectedItem != null; - // create the id of the target file - // Our standard for file naming is: - // ...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 id = name; - if (id.endsWith(".xml")) { - id = id.replace(".xml", ""); - id = id.substring(0, id.lastIndexOf('.')); - } - - // Default policy to be Root policy; user can change to deferred - // later - - StdPDPPolicy selectedPolicy = null; - String dbCheckName = name; - if(dbCheckName.contains("Config_")){ - dbCheckName = dbCheckName.replace(".Config_", ":Config_"); - }else if(dbCheckName.contains("Action_")){ - dbCheckName = dbCheckName.replace(".Action_", ":Action_"); - }else if(dbCheckName.contains("Decision_")){ - dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); - } - String[] split = dbCheckName.split(":"); - String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0"; - SimpleBindings policyParams = new SimpleBindings(); - policyParams.put("split_1", split[1]); - policyParams.put("split_0", split[0]); - List queryData = controller.getDataByQuery(query, policyParams); - PolicyEntity policyEntity = (PolicyEntity) queryData.get(0); - File temp = new File(name); - BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); - bw.write(policyEntity.getPolicyData()); - bw.close(); - URI selectedURI = temp.toURI(); - try { - // - // Create the policy - selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI); - } catch (IOException e) { - logger.error("Unable to create policy '" + name + "': "+ e.getMessage(), e); - } - StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId; - if (selectedPolicy != null) { - // Add Current policies from container - for (OnapPDPGroup group : container.getGroups()) { - if (group.getId().equals(selectedGroup.getId())) { - currentPoliciesInGroup.addAll(group.getPolicies()); - } - } - // copy policy to PAP - try { - controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId); - } catch (PAPException e) { - logger.error("Exception Occured"+e); - return null; - } - selectedPolicies.add(selectedPolicy); - } - temp.delete(); - } - StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId; - StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory()); - updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps()); - updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs()); - updatedGroupObject.setStatus(pdpGroup.getStatus()); - updatedGroupObject.setOperation("push"); - - // replace the original set of Policies with the set from the - // container (possibly modified by the user) - // do not allow multiple copies of same policy - Iterator policyIterator = currentPoliciesInGroup.iterator(); - logger.debug("policyIterator....." + selectedPolicies); - while (policyIterator.hasNext()) { - PDPPolicy existingPolicy = policyIterator.next(); - for (PDPPolicy selPolicy : selectedPolicies) { - if (selPolicy.getName().equals(existingPolicy.getName())) { - if (selPolicy.getVersion().equals(existingPolicy.getVersion())) { - if (selPolicy.getId().equals(existingPolicy.getId())) { - policyIterator.remove(); - logger.debug("Removing policy: " + selPolicy); - break; - } - } else { - policyIterator.remove(); - logger.debug("Removing Old Policy version: "+ selPolicy); - break; - } - } - } - } - - currentPoliciesInGroup.addAll(selectedPolicies); - updatedGroupObject.setPolicies(currentPoliciesInGroup); - this.container.updateGroup(updatedGroupObject); - - response.setCharacterEncoding(UTF8); - response.setContentType("application / json"); - request.setCharacterEncoding(UTF8); - - PrintWriter out = response.getWriter(); - refreshGroups(); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); - // - // Why is this here? This defeats the purpose of the loop?? - // Sonar says to remove it or make it conditional - // - return null; - } - } - catch (Exception e){ - response.setCharacterEncoding(UTF8); - request.setCharacterEncoding(UTF8); - PrintWriter out = response.getWriter(); - logger.error(e); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; - } - - @SuppressWarnings("unchecked") - @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { - try { - PolicyController controller = getPolicyControllerInstance(); - this.container = new PDPGroupContainer(controller.getPapEngine()); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class); - JsonNode removePolicyData = root.get("data"); - - String userId = UserUtils.getUserSession(request).getOrgUserId(); - logger.info("****************************************Logging UserID while Removing Policy from PDP Group*****************************************"); - logger.info("UserId: " + userId + "PDP Group Data: "+ root.get("activePdpGroup").toString() + "Remove Policy Data: "+root.get("data")); - logger.info("***********************************************************************************************************************************"); - - 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 changedPolicies = new HashSet<>(); - changedPolicies.addAll((Collection) this.policyContainer.getItemIds()); - StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null); - updatedGroupObject.setPolicies(changedPolicies); - updatedGroupObject.setOnapPdps(group.getOnapPdps()); - updatedGroupObject.setPipConfigs(group.getPipConfigs()); - updatedGroupObject.setStatus(group.getStatus()); - updatedGroupObject.setOperation("delete"); - this.container.updateGroup(updatedGroupObject); - } - - response.setCharacterEncoding(UTF8); - response.setContentType("application / json"); - request.setCharacterEncoding(UTF8); - - PrintWriter out = response.getWriter(); - refreshGroups(); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - - out.write(j.toString()); - - return null; - } - catch (Exception e){ - response.setCharacterEncoding(UTF8); - request.setCharacterEncoding(UTF8); - PrintWriter out = response.getWriter(); - logger.error(e); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; - } + @Autowired + CommonClassDao commonClassDao; + + private PDPGroupContainer container; + protected List groups = Collections.synchronizedList(new ArrayList()); + + private PDPPolicyContainer policyContainer; + + private PolicyController policyController; + + public PolicyController getPolicyController() { + return policyController; + } + + public void setPolicyController(PolicyController policyController) { + this.policyController = policyController; + } + + private List data; + + public synchronized void refreshGroups() { + synchronized (this.groups) { + this.groups.clear(); + try { + PolicyController controller = getPolicyControllerInstance(); + this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + } + + } + } + + private PolicyController getPolicyControllerInstance() { + return policyController != null ? getPolicyController() : new PolicyController(); + } + + @RequestMapping(value = { "/get_AutoPushPoliciesContainerData" }, method = { + org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) { + try { + Set scopes; + List roles; + data = new ArrayList<>(); + String userId = UserUtils.getUserSession(request).getOrgUserId(); + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + PolicyController controller = policyController != null ? getPolicyController() : new PolicyController(); + List 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()); + } + } + } + } + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) { + data = commonClassDao.getData(PolicyVersion.class); + } else { + if (!scopes.isEmpty()) { + for (String scope : scopes) { + scope += "%"; + String query = "From PolicyVersion where policy_name like :scope and id > 0"; + SimpleBindings params = new SimpleBindings(); + params.put("scope", scope); + List filterdatas = commonClassDao.getDataByQuery(query, params); + if (filterdatas != null) { + for (int i = 0; i < filterdatas.size(); i++) { + data.add(filterdatas.get(i)); + } + } + } + } else { + PolicyVersion emptyPolicyName = new PolicyVersion(); + emptyPolicyName + .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); + data.add(emptyPolicyName); + } + } + 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); + } + } + + @RequestMapping(value = { "/auto_Push/PushPolicyToPDP.htm" }, method = { + org.springframework.web.bind.annotation.RequestMethod.POST }) + public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) + throws IOException { + try { + ArrayList selectedPDPS = new ArrayList<>(); + ArrayList selectedPoliciesInUI = new ArrayList<>(); + PolicyController controller = getPolicyControllerInstance(); + this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); + ObjectMapper mapper = new ObjectMapper(); + this.container = new PDPGroupContainer(controller.getPapEngine()); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + String userId = UserUtils.getUserSession(request).getOrgUserId(); + logger.info( + "****************************************Logging UserID while Pushing Policy to PDP Group*****************************************"); + logger.info("UserId: " + userId + "Push Policy Data: " + root.get("pushTabData").toString()); + logger.info( + "***********************************************************************************************************************************"); + + AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class); + for (Object pdpGroupId : adapter.getPdpDatas()) { + LinkedHashMap selectedPDP = (LinkedHashMap) pdpGroupId; + for (OnapPDPGroup pdpGroup : this.groups) { + if (pdpGroup.getId().equals(selectedPDP.get("id"))) { + selectedPDPS.add(pdpGroup); + } + } + } + + for (Object policyId : adapter.getPolicyDatas()) { + LinkedHashMap selected = (LinkedHashMap) policyId; + String policyName = selected.get("policyName").toString() + "." + + selected.get("activeVersion").toString() + ".xml"; + selectedPoliciesInUI.add(policyName); + } + + for (Object pdpDestinationGroupId : selectedPDPS) { + Set currentPoliciesInGroup = new HashSet<>(); + Set selectedPolicies = new HashSet<>(); + for (String policyId : selectedPoliciesInUI) { + logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId); + + // + // Get the current selection + String selectedItem = policyId; + // + assert selectedItem != null; + // create the id of the target file + // Our standard for file naming is: + // ...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 id = name; + if (id.endsWith(".xml")) { + id = id.replace(".xml", ""); + id = id.substring(0, id.lastIndexOf('.')); + } + + // Default policy to be Root policy; user can change to deferred + // later + + StdPDPPolicy selectedPolicy = null; + String dbCheckName = name; + if (dbCheckName.contains("Config_")) { + dbCheckName = dbCheckName.replace(".Config_", ":Config_"); + } else if (dbCheckName.contains("Action_")) { + dbCheckName = dbCheckName.replace(".Action_", ":Action_"); + } else if (dbCheckName.contains("Decision_")) { + dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); + } + String[] split = dbCheckName.split(":"); + String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0"; + SimpleBindings policyParams = new SimpleBindings(); + policyParams.put("split_1", split[1]); + policyParams.put("split_0", split[0]); + List queryData = controller.getDataByQuery(query, policyParams); + PolicyEntity policyEntity = (PolicyEntity) queryData.get(0); + File temp = new File(name); + BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); + bw.write(policyEntity.getPolicyData()); + bw.close(); + URI selectedURI = temp.toURI(); + try { + // + // Create the policy + selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI); + } catch (IOException e) { + logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e); + } + StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId; + if (selectedPolicy != null) { + // Add Current policies from container + for (OnapPDPGroup group : container.getGroups()) { + if (group.getId().equals(selectedGroup.getId())) { + currentPoliciesInGroup.addAll(group.getPolicies()); + } + } + // copy policy to PAP + try { + controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId); + } catch (PAPException e) { + logger.error("Exception Occured" + e); + return null; + } + selectedPolicies.add(selectedPolicy); + } + temp.delete(); + } + StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId; + StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), + pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory()); + updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps()); + updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs()); + updatedGroupObject.setStatus(pdpGroup.getStatus()); + updatedGroupObject.setOperation("push"); + + // replace the original set of Policies with the set from the + // container (possibly modified by the user) + // do not allow multiple copies of same policy + Iterator policyIterator = currentPoliciesInGroup.iterator(); + logger.debug("policyIterator....." + selectedPolicies); + while (policyIterator.hasNext()) { + PDPPolicy existingPolicy = policyIterator.next(); + for (PDPPolicy selPolicy : selectedPolicies) { + if (selPolicy.getName().equals(existingPolicy.getName())) { + if (selPolicy.getVersion().equals(existingPolicy.getVersion())) { + if (selPolicy.getId().equals(existingPolicy.getId())) { + policyIterator.remove(); + logger.debug("Removing policy: " + selPolicy); + break; + } + } else { + policyIterator.remove(); + logger.debug("Removing Old Policy version: " + selPolicy); + break; + } + } + } + } + + currentPoliciesInGroup.addAll(selectedPolicies); + updatedGroupObject.setPolicies(currentPoliciesInGroup); + this.container.updateGroup(updatedGroupObject); + + response.setCharacterEncoding(UTF8); + response.setContentType("application / json"); + request.setCharacterEncoding(UTF8); + + PrintWriter out = response.getWriter(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + // + // Why is this here? This defeats the purpose of the loop?? + // Sonar says to remove it or make it conditional + // + return null; + } + } catch (Exception e) { + response.setCharacterEncoding(UTF8); + request.setCharacterEncoding(UTF8); + PrintWriter out = response.getWriter(); + logger.error(e); + out.write(PolicyUtils.CATCH_EXCEPTION); + } + return null; + } + + @SuppressWarnings("unchecked") + @RequestMapping(value = { "/auto_Push/remove_GroupPolicies.htm" }, method = { + org.springframework.web.bind.annotation.RequestMethod.POST }) + public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { + try { + PolicyController controller = getPolicyControllerInstance(); + this.container = new PDPGroupContainer(controller.getPapEngine()); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class); + JsonNode removePolicyData = root.get("data"); + + String userId = UserUtils.getUserSession(request).getOrgUserId(); + logger.info( + "****************************************Logging UserID while Removing Policy from PDP Group*****************************************"); + logger.info("UserId: " + userId + "PDP Group Data: " + root.get("activePdpGroup").toString() + + "Remove Policy Data: " + root.get("data")); + logger.info( + "***********************************************************************************************************************************"); + + 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 changedPolicies = new HashSet<>(); + changedPolicies.addAll((Collection) this.policyContainer.getItemIds()); + StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), + group.getDescription(), null); + updatedGroupObject.setPolicies(changedPolicies); + updatedGroupObject.setOnapPdps(group.getOnapPdps()); + updatedGroupObject.setPipConfigs(group.getPipConfigs()); + updatedGroupObject.setStatus(group.getStatus()); + updatedGroupObject.setOperation("delete"); + this.container.updateGroup(updatedGroupObject); + } + + response.setCharacterEncoding(UTF8); + response.setContentType("application / json"); + request.setCharacterEncoding(UTF8); + + PrintWriter out = response.getWriter(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + + out.write(j.toString()); + + return null; + } catch (Exception e) { + response.setCharacterEncoding(UTF8); + request.setCharacterEncoding(UTF8); + PrintWriter out = response.getWriter(); + logger.error(e); + out.write(PolicyUtils.CATCH_EXCEPTION); + } + return null; + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java index 3b4d03de8..69444c478 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,6 +23,7 @@ package org.onap.policy.controller; import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -34,7 +35,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; -import java.util.TreeMap; +import java.nio.charset.StandardCharsets; import javax.annotation.PostConstruct; import javax.mail.MessagingException; import javax.script.SimpleBindings; @@ -43,6 +44,8 @@ import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; import org.onap.policy.admin.PolicyNotificationMail; import org.onap.policy.admin.RESTfulPAPEngine; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.model.PDPGroupContainer; @@ -57,6 +60,7 @@ import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.utils.UserUtils.Pair; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; +import org.onap.policy.xacml.util.XACMLPolicyScanner; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.portalsdk.core.domain.UserApp; import org.onap.portalsdk.core.web.support.JsonMessage; @@ -67,7 +71,8 @@ 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 oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; @Controller @RequestMapping("/") @@ -105,6 +110,9 @@ public class PolicyController extends RestrictedBaseController { private static final String characterEncoding = "UTF-8"; private static final String contentType = "application/json"; private static final String file = "file"; + private static final String SUPERADMIN = "super-admin"; + private static final String POLICYGUEST = "Policy Guest"; + private static final String LOGINID = "loginId"; // Smtp Java Mail Properties private static String smtpHost = null; @@ -147,7 +155,6 @@ public class PolicyController extends RestrictedBaseController { private static boolean jUnit = false; - public static boolean isjUnit() { return jUnit; } @@ -296,12 +303,11 @@ public class PolicyController extends RestrictedBaseController { /** * Get Functional Definition data. * - * @param request HttpServletRequest. + * @param request HttpServletRequest. * @param response HttpServletResponse. */ - @RequestMapping(value = {"/get_FunctionDefinitionDataByName"}, - method = {org.springframework.web.bind.annotation.RequestMethod.GET}, - produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = { "/get_FunctionDefinitionDataByName" }, method = { + org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response) { try { Map model = new HashMap<>(); @@ -320,7 +326,7 @@ public class PolicyController extends RestrictedBaseController { /** * Get PolicyEntity Data from db. * - * @param scope scopeName. + * @param scope scopeName. * @param policyName policyName. * @return policyEntity data. */ @@ -338,7 +344,7 @@ public class PolicyController extends RestrictedBaseController { */ public List getRolesOfUser(String userId) { List rolesList = new ArrayList<>(); - List roles = commonClassDao.getDataById(Roles.class, "loginId", userId); + List roles = commonClassDao.getDataById(Roles.class, LOGINID, userId); for (Object role : roles) { rolesList.add(((Roles) role).getRole()); } @@ -346,18 +352,17 @@ public class PolicyController extends RestrictedBaseController { } public List getRoles(String userId) { - return commonClassDao.getDataById(Roles.class, "loginId", userId); + return commonClassDao.getDataById(Roles.class, LOGINID, userId); } /** * Get List of User Roles. * - * @param request HttpServletRequest. + * @param request HttpServletRequest. * @param response HttpServletResponse. */ - @RequestMapping(value = {"/get_UserRolesData"}, - method = {org.springframework.web.bind.annotation.RequestMethod.GET}, - produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = { "/get_UserRolesData" }, method = { + org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response) { try { String userId = UserUtils.getUserSession(request).getOrgUserId(); @@ -378,7 +383,7 @@ public class PolicyController extends RestrictedBaseController { * @param request Request input. * @return view model. */ - @RequestMapping(value = {"/policy", "/policy/Editor"}, method = RequestMethod.GET) + @RequestMapping(value = { "/policy", "/policy/Editor" }, method = RequestMethod.GET) public ModelAndView view(HttpServletRequest request) { getUserRoleFromSession(request); String myRequestUrl = request.getRequestURL().toString(); @@ -386,8 +391,8 @@ public class PolicyController extends RestrictedBaseController { // // Set the URL for the RESTful PAP Engine // - setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestUrl)); - new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestUrl)); + setPapEngine(new RESTfulPAPEngine(myRequestUrl)); + new PDPGroupContainer(new RESTfulPAPEngine(myRequestUrl)); } catch (Exception e) { policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP" + e); } @@ -396,9 +401,9 @@ public class PolicyController extends RestrictedBaseController { } /** - * Read the role from session. + * Read the role from session for inserting into the database. * - * @param request Request input. + * @param request Request input for Role. */ public void getUserRoleFromSession(HttpServletRequest request) { // While user landing on Policy page, fetch the userId and Role from @@ -415,26 +420,50 @@ public class PolicyController extends RestrictedBaseController { newRoles.add(userApp.getRole().getName()); } List userRoles = getRoles(userId); - String filteredRole = filterRole(newRoles); - if (userRoles == null || userRoles.isEmpty()) { - savePolicyRoles(name, filteredRole, userId); - } else { - Pair, List> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - roles = pair.u; - if (!roles.contains(filteredRole)) { - String query = "delete from Roles where loginid='" + userId + "'"; - commonClassDao.updateQuery(query); + List filteredRoles = filterRole(newRoles); + if (!filteredRoles.isEmpty()) { + cleanUpRoles(filteredRoles, userId); + } + for (String filteredRole : filteredRoles) { + if (userRoles == null || userRoles.isEmpty()) { savePolicyRoles(name, filteredRole, userId); + } else { + userRoles = getRoles(userId); + Pair, List> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); + roles = pair.u; + if (!roles.contains(filteredRole)) { + savePolicyRoles(name, filteredRole, userId); + } + } + } + } + + /** + * Build a delete query for cleaning up roles and execute it. + * + * @param filteredRoles Filtered roles list. + * @param userId UserID. + */ + private void cleanUpRoles(List filteredRoles, String userId) { + StringBuilder query = new StringBuilder(); + query.append("delete from Roles where loginid = '" + userId + "'"); + if (filteredRoles.contains(SUPERADMIN)) { + query.append("and not role = '" + SUPERADMIN + "'"); + } else { + for (String filteredRole : filteredRoles) { + query.append("and not role = '" + filteredRole + "'"); } } + query.append("and id > 0"); + commonClassDao.updateQuery(query.toString()); } /** * Save the Role to DB. * - * @param name User Name. + * @param name User Name. * @param filteredRole Role Name. - * @param userId User LoginID. + * @param userId User LoginID. */ private void savePolicyRoles(String name, String filteredRole, String userId) { UserInfo userInfo = new UserInfo(); @@ -454,25 +483,35 @@ public class PolicyController extends RestrictedBaseController { * @param newRoles list of roles from request. * @return */ - private String filterRole(List newRoles) { - Map roleMap = new TreeMap<>(); - roleMap.put(6, "guest"); + private List filterRole(List newRoles) { + List roles = new ArrayList<>(); + boolean superCheck = false; for (String role : newRoles) { - if ("Policy Super Admin".equalsIgnoreCase(role.trim()) + if ("Policy Super Guest".equalsIgnoreCase(role.trim())) { + superCheck = true; + roles.add("super-guest"); + } else if ("Policy Super Editor".equalsIgnoreCase(role.trim())) { + superCheck = true; + roles.clear(); + roles.add("super-editor"); + } else if ("Policy Super Admin".equalsIgnoreCase(role.trim()) || "System Administrator".equalsIgnoreCase(role.trim()) || "Standard User".equalsIgnoreCase(role.trim())) { - roleMap.put(1, "super-admin"); - } else if ("Policy Super Editor".equalsIgnoreCase(role.trim())) { - roleMap.put(2, "super-editor"); - } else if ("Policy Super Guest".equalsIgnoreCase(role.trim())) { - roleMap.put(3, "super-guest"); - } else if ("Policy Admin".equalsIgnoreCase(role.trim())) { - roleMap.put(4, "admin"); - } else if ("Policy Editor".equalsIgnoreCase(role.trim())) { - roleMap.put(5, "editor"); + superCheck = true; + roles.clear(); + roles.add(SUPERADMIN); + } + if (!roles.contains(SUPERADMIN) || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) { + if ("Policy Admin".equalsIgnoreCase(role.trim())) { + roles.add("admin"); + } else if ("Policy Editor".equalsIgnoreCase(role.trim())) { + roles.add("editor"); + } else if (POLICYGUEST.equalsIgnoreCase(role.trim())) { + roles.add("guest"); + } } } - return roleMap.entrySet().iterator().next().getValue(); + return roles; } public PAPPolicyEngine getPapEngine() { @@ -491,12 +530,13 @@ public class PolicyController extends RestrictedBaseController { */ public String getUserName(String createdBy) { String loginId = createdBy; - List data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId); + List data = commonClassDao.getDataById(UserInfo.class, LOGINID, loginId); return data.get(0).toString(); } /** * Check if the Policy is Active or not. + * * @param query sql query. * @return boolean. */ @@ -532,19 +572,17 @@ public class PolicyController extends RestrictedBaseController { return commonClassDao.getDataByQuery(query, params); } - @SuppressWarnings("rawtypes") public Object getEntityItem(Class className, String columname, String key) { return commonClassDao.getEntityItem(className, columname, key); } - /** * Watch Policy Function. * - * @param entity PolicyVersion entity. + * @param entity PolicyVersion entity. * @param policyName updated policy name. - * @param mode type of action rename/delete/import. + * @param mode type of action rename/delete/import. */ public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode) { PolicyNotificationMail email = new PolicyNotificationMail(); @@ -569,6 +607,8 @@ public class PolicyController extends RestrictedBaseController { dbCheckName = dbCheckName.replace(".Config_", ":Config_"); } else if (dbCheckName.contains("Action_")) { dbCheckName = dbCheckName.replace(".Action_", ":Action_"); + } else if (dbCheckName.contains("Decision_MS_")) { + dbCheckName = dbCheckName.replace(".Decision_MS_", ":Decision_MS_"); } else if (dbCheckName.contains("Decision_")) { dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); } @@ -583,13 +623,14 @@ public class PolicyController extends RestrictedBaseController { PolicyEntity pEntity = (PolicyEntity) entity; String removeExtension = pEntity.getPolicyName().replace(".xml", ""); String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1); - av.add(version); + String userName = getUserId(pEntity, "@ModifiedBy:"); + av.add(version + " | " + pEntity.getModifiedDate() + " | " + userName); } if (policyName.contains("/")) { policyName = policyName.replace("/", File.separator); } - PolicyVersion entity = - (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName); + PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", + policyName); JSONObject el = new JSONObject(); el.put("activeVersion", entity.getActiveVersion()); el.put("availableVersions", av); @@ -597,6 +638,50 @@ public class PolicyController extends RestrictedBaseController { return el; } + public String getUserId(PolicyEntity data, String value) { + String userId = ""; + String uValue = value; + String description = getDescription(data); + if (description.contains(uValue)) { + userId = description.substring(description.indexOf(uValue) + uValue.length(), + description.lastIndexOf(uValue)); + } + UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId); + if (userInfo == null) { + return SUPERADMIN; + } + return userInfo.getUserName(); + } + + public String getDescription(PolicyEntity data) { + InputStream stream = new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8)); + Object policy = XACMLPolicyScanner.readPolicy(stream); + if (policy instanceof PolicySetType) { + return ((PolicySetType) policy).getDescription(); + } else if (policy instanceof PolicyType) { + return ((PolicyType) policy).getDescription(); + } else { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + + policy.getClass().getCanonicalName()); + return null; + } + } + + public String[] getUserInfo(PolicyEntity data, List activePolicies) { + String policyName = data.getScope().replace(".", File.separator) + File.separator + + data.getPolicyName().substring(0, data.getPolicyName().indexOf('.')); + PolicyVersion pVersion = activePolicies.stream().filter(a -> policyName.equals(a.getPolicyName())).findAny() + .orElse(null); + String[] result = new String[2]; + + UserInfo userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", pVersion.getCreatedBy()); + UserInfo userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", pVersion.getModifiedBy()); + result[0] = userCreate != null ? userCreate.getUserName() : "super-admin"; + result[1] = userModify != null ? userModify.getUserName() : "super-admin"; + + return result; + } + public static String getLogTableLimit() { return logTableLimit; } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java index daf3d6c97..b02da1996 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -20,7 +20,6 @@ package org.onap.policy.controller; - import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; @@ -54,123 +53,175 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Controller @RequestMapping("/") -public class PolicyRolesController extends RestrictedBaseController{ - - private static final Logger LOGGER = FlexLogger.getLogger(PolicyRolesController.class); - - @Autowired - CommonClassDao commonClassDao; - - public void setCommonClassDao(CommonClassDao commonClassDao) { - this.commonClassDao = commonClassDao; - } - - List scopelist; - - @RequestMapping(value={"/get_RolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPolicyRolesEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("rolesDatas", mapper.writeValueAsString(commonClassDao.getUserRoles())); - 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={"/save_NonSuperRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - StringBuilder scopeName = new StringBuilder(); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - String userId = UserUtils.getUserSession(request).getOrgUserId(); - JsonNode root = mapper.readTree(request.getReader()); - ReadScopes adapter = mapper.readValue(root.get("editRoleData").toString(), ReadScopes.class); - for(int i = 0; i < adapter.getScope().size(); i++){ - if(i == 0){ - scopeName.append(adapter.getScope().get(0)); - }else{ - scopeName.append("," + adapter.getScope().get(i)); - } - } - LOGGER.info("****************************************Logging UserID for Roles Function********************************************************"); - LOGGER.info("UserId: " + userId + "Updating the Scope for following user" + adapter.getLoginId() + "ScopeNames" + adapter.getScope()); - LOGGER.info("*********************************************************************************************************************************"); - PolicyRoles roles = new PolicyRoles(); - roles.setId(adapter.getId()); - roles.setLoginId(adapter.getLoginId()); - roles.setRole(adapter.getRole()); - roles.setScope(scopeName.toString()); - commonClassDao.update(roles); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getUserRoles()); - JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}"); - - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - } - return null; - } - - @RequestMapping(value={"/get_PolicyRolesScopeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPolicyScopesEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - scopelist = new ArrayList<>(); - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); - List scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName"); - model.put("scopeDatas", mapper.writeValueAsString(scopesData)); - 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); - } - } +public class PolicyRolesController extends RestrictedBaseController { + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyRolesController.class); + + @Autowired + CommonClassDao commonClassDao; + + public void setCommonClassDao(CommonClassDao commonClassDao) { + this.commonClassDao = commonClassDao; + } + + List scopelist; + + /** + * Gets the policy roles entity data. + * + * @param request the request + * @param response the response + */ + @RequestMapping(value = { "/get_RolesData" }, method = { + org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + public void getPolicyRolesEntityData(HttpServletRequest request, HttpServletResponse response) { + try { + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("rolesDatas", mapper.writeValueAsString(commonClassDao.getUserRoles())); + 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); + } + } + + /** + * Save roles and Mechid entity data. + * + * @param request the request + * @param response the response + * @return the model and view + */ + @RequestMapping(value = { "/save_NonSuperRolesData" }, method = { + org.springframework.web.bind.annotation.RequestMethod.POST }) + public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response) { + try { + StringBuilder scopeName = new StringBuilder(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String userId = UserUtils.getUserSession(request).getOrgUserId(); + JsonNode root = mapper.readTree(request.getReader()); + ReadScopes adapter = mapper.readValue(root.get("editRoleData").toString(), ReadScopes.class); + for (int i = 0; i < adapter.getScope().size(); i++) { + if (i == 0) { + scopeName.append(adapter.getScope().get(0)); + } else { + scopeName.append("," + adapter.getScope().get(i)); + } + } + LOGGER.info( + "****************************************Logging UserID for Roles Function********************************************************"); + LOGGER.info("UserId: " + userId + "Updating the Scope for following user" + adapter.getLoginId() + + "ScopeNames" + adapter.getScope()); + LOGGER.info( + "*********************************************************************************************************************************"); + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(adapter.getLoginId().getUserName()); + userInfo.setUserName(adapter.getLoginId().getUserName()); + + boolean checkNew = false; + if (adapter.getId() == 0 && "mechid".equals(adapter.getRole())) { + // Save new mechid scopes entity data. + LOGGER.info( + "****************************************Logging UserID for New Mechid Function***************************************************"); + LOGGER.info("UserId:" + userId + "Adding new mechid-scopes for following user" + adapter.getLoginId() + + "ScopeNames " + adapter.getScope()); + LOGGER.info( + "*********************************************************************************************************************************"); + // First add the mechid to userinfo + commonClassDao.save(userInfo); + checkNew = true; + } + + PolicyRoles roles = new PolicyRoles(); + roles.setId(adapter.getId()); + roles.setLoginId(adapter.getLoginId()); + roles.setRole(adapter.getRole()); + roles.setScope(scopeName.toString()); + if (checkNew) { + roles.setLoginId(userInfo); + commonClassDao.save(roles); + } else { + commonClassDao.update(roles); + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getUserRoles()); + JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}"); + + out.write(j.toString()); + } catch (Exception e) { + LOGGER.error("Exception Occured" + e); + } + return null; + } + + /** + * Gets the policy scopes entity data. + * + * @param request the request + * @param response the response + */ + @RequestMapping(value = { "/get_PolicyRolesScopeData" }, method = { + org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + public void getPolicyScopesEntityData(HttpServletRequest request, HttpServletResponse response) { + try { + scopelist = new ArrayList<>(); + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + List scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName"); + model.put("scopeDatas", mapper.writeValueAsString(scopesData)); + 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); + } + } } -class ReadScopes{ - private int id; - private UserInfo loginId; - private String role; - private List scope; - - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public UserInfo getLoginId() { - return loginId; - } - public void setLoginId(UserInfo loginId) { - this.loginId = loginId; - } - public String getRole() { - return role; - } - public void setRole(String role) { - this.role = role; - } - public List getScope() { - return scope; - } - public void setScope(List scope) { - this.scope = scope; - } +class ReadScopes { + private int id; + private UserInfo loginId; + private String role; + private List scope; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public UserInfo getLoginId() { + return loginId; + } + + public void setLoginId(UserInfo loginId) { + this.loginId = loginId; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public List getScope() { + return scope; + } + + public void setScope(List scope) { + this.scope = scope; + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java index 1f68ffc0e..40c839676 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -20,49 +20,107 @@ package org.onap.policy.utils; import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import org.onap.policy.model.Roles; public final class UserUtils { - - private UserUtils () { - // Empty Constructor - } - - public static class Pair { - public final T t; - public final U u; - - public Pair (T t, U u) { - this.t = t; - this.u = u; - } - } - - public static Pair, List> checkRoleAndScope(List userRoles) { - Set scopes; - List roles; - //Check if the Role and Scope Size are Null get the values from db. - 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]); - } - }else{ - scopes.add(userRole.getScope()); - } - } - } - return new Pair<>(scopes, roles); - } + + private UserUtils() { + // Empty Constructor + } + + public static class Pair { + public final T t; + public final U u; + + public Pair(T t, U u) { + this.t = t; + this.u = u; + } + } + + /** + * Check Role and its Scopes. + * + * @param userRoles list of UserRoles. + * @return return role and scope from UserRole Object. + */ + public static Pair, List> checkRoleAndScope(List userRoles) { + Set scopes; + List roles; + // Check if the Role and Scope Size are Null get the values from db. + 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(trimScope(multipleScopes[i])); + } + } else { + scopes.add(trimScope(userRole.getScope())); + } + } + } + return new Pair<>(scopes, roles); + } + + /** + * Get Role by Scope based on UserRole Object. + * + * @param userRoles list of UserRoles. + * @return return the map. + */ + public static Map getRoleByScope(List userRoles) { + Map rolesList = new HashMap<>(); + for (Object role : userRoles) { + Roles userRole = (Roles) role; + if (!userRole.getRole().startsWith("super-")) { + rolesList = addNonSuperUserScopes(userRole, rolesList); + } else { + rolesList.put("@All@", userRole.getRole()); + } + } + return rolesList; + } + + /** + * Read non super role scopes and add to map. + * + * @param userRole Role Object. + * @param rolesList roleList Object. + * @return return the map. + */ + private static Map addNonSuperUserScopes(Roles userRole, Map rolesList) { + if (userRole.getScope() != null && !(userRole.getScope().trim().isEmpty())) { + if (userRole.getScope().contains(",")) { + String[] multipleScopes = userRole.getScope().split(","); + for (int i = 0; i < multipleScopes.length; i++) { + rolesList.put(trimScope(multipleScopes[i]), userRole.getRole()); + } + } else { + rolesList.put(trimScope(userRole.getScope()), userRole.getRole()); + } + } + return rolesList; + } + + /** + * Trim Scope Value. + * + * @param scope string scope name. + * @return trim scope. + */ + private static String trimScope(String scope) { + return scope.replace("[", "").replace("]", "").replace("\"", "").trim(); + } } diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Edit_Roles_Window.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Edit_Roles_Window.html index 7974d4e3f..6b23e3280 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Edit_Roles_Window.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Edit_Roles_Window.html @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,38 +17,88 @@ * limitations under the License. * ============LICENSE_END========================================================= */--> + + + \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js index 42760a222..051a9130c 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -18,12 +18,28 @@ * ============LICENSE_END========================================================= */ app.controller('editRoleController' , function ($scope, PolicyAppService, $modalInstance, message){ - if(message.editRoleData!=null){ + if (message.editRoleData != null) { $scope.label='Edit Role' $scope.disableCd=true; + } else { + $scope.label='Add Role' + $scope.disableCd=false; + message.editRoleData = { + role : "mechid" + } } + $scope.editRole = message.editRoleData; + $scope.activeScopes = []; + if (message.editRoleData != null && message.editRoleData.scope != null) { + if (message.editRoleData.scope.constructor === Array) { + $scope.activeScopes = message.editRoleData.scope; + } else { + $scope.activeScopes = message.editRoleData.scope.split(','); + } + } + PolicyAppService.getData('get_PolicyRolesScopeData').then(function (data) { var j = data; $scope.data = JSON.parse(j.data); @@ -36,6 +52,7 @@ app.controller('editRoleController' , function ($scope, PolicyAppService, $moda $scope.saveRole = function(editRoleData) { var uuu = "save_NonSuperRolesData.htm"; + editRoleData.scope = $scope.activeScopes; var postData={editRoleData: editRoleData}; $.ajax({ type : 'POST', @@ -55,7 +72,39 @@ app.controller('editRoleController' , function ($scope, PolicyAppService, $moda }); }; - $scope.close = function() { - $modalInstance.close(); + + $scope.createMechidScope = function(editRoleData) { + var uuu = "save_NewMechidScopesData"; + editRoleData.scope = $scope.activeScopes; + var postData={editRoleData: editRoleData}; + $.ajax({ + type : 'POST', + url : uuu, + dataType: 'json', + contentType: 'application/json', + data: JSON.stringify(postData), + success : function(data){ + $scope.$apply(function(){ + $scope.rolesDatas=data.rolesDatas;}); + console.log($scope.rolesDatas); + $modalInstance.close({rolesDatas:$scope.rolesDatas}); + }, + error : function(data) { + alert("Error while Creating Mechid scopes."); + } + }); + }; + + + + $scope.addScope = function(scopes) { + for (var i = 0; i < scopes.length; i++) { + if ($.inArray(scopes[i], $scope.activeScopes) === -1) { + $scope.activeScopes.push(scopes[i]); + } + } + }; + $scope.deleteScope = function(index) { + $scope.activeScopes.splice(index, 1); }; }); \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyRolesController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyRolesController.js index ddd6b232c..ed1b8bd23 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyRolesController.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyRolesController.js @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -19,23 +19,23 @@ */ app.controller('policyRolesController', function ($scope, PolicyAppService, modalService, $modal, Notification){ $( "#dialog" ).hide(); - + $scope.isDisabled = true; + + PolicyAppService.getData('get_LockDownData').then(function(data) { + var j = data; + $scope.data = JSON.parse(j.data); + $scope.lockdowndata = JSON.parse($scope.data.lockdowndata); + if ($scope.lockdowndata[0].lockdown == true) { + $scope.isDisabled = true; + } else { + $scope.isDisabled = false; + } + console.log($scope.data); + }, function(error) { + console.log("failed"); + }); - PolicyAppService.getData('get_LockDownData').then(function(data){ - var j = data; - $scope.data = JSON.parse(j.data); - $scope.lockdowndata = JSON.parse($scope.data.lockdowndata); - if($scope.lockdowndata[0].lockdown == true){ - $scope.isDisabled = true; - }else{ - $scope.isDisabled = false; - } - console.log($scope.data); - },function(error){ - console.log("failed"); - }); - $scope.scopeDatas = []; PolicyAppService.getData('get_RolesData').then(function (data) { var j = data; @@ -51,7 +51,8 @@ app.controller('policyRolesController', function ($scope, PolicyAppService, moda data : 'rolesDatas', enableFiltering: true, columnDefs: [{ - field: 'id', enableFiltering: false, + field: 'id', enableFiltering: false, headerCellTemplate: '' + + '', cellTemplate: '' , width: '4%' }, @@ -63,30 +64,30 @@ app.controller('policyRolesController', function ($scope, PolicyAppService, moda $scope.editRoleName = null; - + $scope.editRolesWindow = function(editRoleData) { - if($scope.lockdowndata[0].lockdown == true){ - Notification.error("Policy Application has been Locked") - }else{ - $scope.editRoleName = editRoleData; - var modalInstance = $modal.open({ - backdrop: 'static', keyboard: false, - templateUrl : 'edit_Role_popup.html', - controller: 'editRoleController', - resolve: { - message: function () { - var message = { - editRoleData: $scope.editRoleName - }; - return message; - } - } - }); - modalInstance.result.then(function(response){ - console.log('response', response); - }); - } - + if ($scope.lockdowndata[0].lockdown == true) { + Notification.error("Policy Application has been Locked") + } else { + $scope.editRoleName = editRoleData; + var modalInstance = $modal.open({ + backdrop: 'static', keyboard: false, + templateUrl : 'edit_Role_popup.html', + controller: 'editRoleController', + resolve: { + message: function () { + var message = { + editRoleData: $scope.editRoleName + }; + return message; + } + } + }); + modalInstance.result.then(function(response) { + console.log('response', response); + $scope.rolesDatas = response.rolesDatas; + }); + } }; }); \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js index 7568030cf..0aec30c1d 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -20,7 +20,7 @@ app.controller('PolicyManagerController', [ '$scope', '$q', '$window', '$cookies', 'policyManagerConfig', 'item', 'policyNavigator', 'policyUploader', 'Notification','PolicyAppService', function($scope, $q, $Window, $cookies, policyManagerConfig, Item, PolicyNavigator, PolicyUploader, Notification, PolicyAppService ) { - + $scope.isDisabled = true; $scope.superAdminId = false; $scope.exportPolicyId = false; @@ -35,109 +35,75 @@ app.controller('PolicyManagerController', [ $scope.describePolicyId = false; $scope.viewPolicyId = false; $scope.deletePolicyId = false; - PolicyAppService.getData('get_LockDownData').then(function(data){ - var j = data; - $scope.data = JSON.parse(j.data); - $scope.lockdowndata = JSON.parse($scope.data.lockdowndata); - if($scope.lockdowndata[0].lockdown == true){ - $scope.isDisabled = true; - }else{ - $scope.isDisabled = false; - } - console.log($scope.data); - },function(error){ - console.log("failed"); + PolicyAppService.getData('get_LockDownData').then(function(data) { + var j = data; + $scope.data = JSON.parse(j.data); + $scope.lockdowndata = JSON.parse($scope.data.lockdowndata); + if ($scope.lockdowndata[0].lockdown == true) { + $scope.isDisabled = true; + } else { + $scope.isDisabled = false; + } + console.log($scope.data); + }, function(error) { + console.log("failed"); }); - - PolicyAppService.getData('getDictionary/get_DescriptiveScopeByName').then(function(data){ - var j = data; - $scope.data = JSON.parse(j.data); - console.log($scope.data); - $scope.descriptiveScopeDictionaryDatas = JSON.parse($scope.data.descriptiveScopeDictionaryDatas); + + PolicyAppService.getData('getDictionary/get_DescriptiveScopeByName').then(function(data) { + var j = data; + $scope.data = JSON.parse(j.data); + console.log($scope.data); + $scope.descriptiveScopeDictionaryDatas = JSON.parse($scope.data.descriptiveScopeDictionaryDatas); }, function (error) { - console.log("failed"); + console.log("failed"); }); - PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function(data){ - var j = data; - $scope.data = JSON.parse(j.data); - console.log($scope.data); - $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas); + PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function(data) { + var j = data; + $scope.data = JSON.parse(j.data); + console.log($scope.data); + $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas); }, function (error) { console.log("failed"); }); - PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function(data){ - var j = data; - $scope.data = JSON.parse(j.data); - console.log($scope.data); - $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas); + PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function(data) { + var j = data; + $scope.data = JSON.parse(j.data); + console.log($scope.data); + $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas); }, function (error) { - console.log("failed"); + console.log("failed"); }); - PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function(data){ - var j = data; - $scope.data = JSON.parse(j.data); - console.log($scope.data); - $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas); + PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function(data) { + var j = data; + $scope.data = JSON.parse(j.data); + console.log($scope.data); + $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas); }, function (error) { - console.log("failed"); + console.log("failed"); }); - + PolicyAppService.getData('get_UserRolesData').then(function (data) { - var j = data; - $scope.data = JSON.parse(j.data); - console.log($scope.data); - $scope.userRolesDatas = JSON.parse($scope.data.userRolesDatas); - console.log($scope.userRolesDatas); - if($scope.userRolesDatas[0] == 'super-admin'){ - $scope.superAdminId = true; - $scope.exportPolicyId = true; - $scope.importPolicyId = true; - $scope.createScopeId = true; - $scope.deleteScopeId = true; - $scope.renameId = true; - $scope.createPolicyId = true; - $scope.cloneId = true; - $scope.editPolicyId = true; - $scope.switchVersionId = true; - $scope.describePolicyId = true; - $scope.viewPolicyId = true; - $scope.deletePolicyId = true; - }else if($scope.userRolesDatas[0] == 'super-editor' || $scope.userRolesDatas[0] == 'editor'){ - $scope.exportPolicyId = true; - $scope.importPolicyId = true; - $scope.cloneId = true; - $scope.editPolicyId = true; - $scope.createPolicyId = true; - $scope.cloneId = true; - $scope.editPolicyId = true; - $scope.switchVersionId = true; - $scope.describePolicyId = true; - $scope.viewPolicyId = true; - $scope.deletePolicyId = true; - }else if($scope.userRolesDatas[0] == 'super-guest' || $scope.userRolesDatas[0] == 'guest'){ - $scope.describePolicyId = true; - $scope.viewPolicyId = true; - }else if($scope.userRolesDatas[0] == 'admin'){ - $scope.exportPolicyId = true; - $scope.importPolicyId = true; - $scope.createScopeId = true; - $scope.renameId = true; - $scope.createPolicyId = true; - $scope.cloneId = true; - $scope.editPolicyId = true; - $scope.switchVersionId = true; - $scope.describePolicyId = true; - $scope.viewPolicyId = true; - $scope.deletePolicyId = true; - } - }, function (error) { - console.log("failed"); - }); - + var j = data; + $scope.data = JSON.parse(j.data); + console.log($scope.data); + $scope.userRolesDatas = JSON.parse($scope.data.userRolesDatas); + console.log($scope.userRolesDatas); + if ($scope.userRolesDatas[0] == 'super-admin') { + $scope.superAdminId = true; + $scope.exportPolicyId = true; + $scope.importPolicyId = true; + } else if ($scope.userRolesDatas[0] == 'super-editor' || $scope.userRolesDatas[0] == 'editor' || $scope.userRolesDatas[0] == 'admin') { + $scope.exportPolicyId = true; + $scope.importPolicyId = true; + } + }, function (error) { + console.log("failed"); + }); + $scope.config = policyManagerConfig; $scope.reverse = false; $scope.predicate = ['model.type', 'model.name']; @@ -160,6 +126,49 @@ app.controller('PolicyManagerController', [ item = item instanceof Item ? item : new Item(); item.revert(); $scope.temp = item; + $scope.createScopeId = false; + $scope.deleteScopeId = false; + $scope.renameId = false; + $scope.createPolicyId = false; + $scope.cloneId = false; + $scope.editPolicyId = false; + $scope.switchVersionId = false; + $scope.describePolicyId = false; + $scope.viewPolicyId = false; + $scope.deletePolicyId = false; + if ($scope.temp.model.roleType == 'super-admin') { + $scope.createScopeId = true; + $scope.deleteScopeId = true; + $scope.renameId = true; + $scope.createPolicyId = true; + $scope.cloneId = true; + $scope.editPolicyId = true; + $scope.switchVersionId = true; + $scope.describePolicyId = true; + $scope.viewPolicyId = true; + $scope.deletePolicyId = true; + } else if ($scope.temp.model.roleType == 'super-editor' || $scope.temp.model.roleType == 'editor') { + $scope.cloneId = true; + $scope.editPolicyId = true; + $scope.createPolicyId = true; + $scope.switchVersionId = true; + $scope.describePolicyId = true; + $scope.viewPolicyId = true; + $scope.deletePolicyId = true; + } else if ($scope.temp.model.roleType == 'super-guest' || $scope.temp.model.roleType == 'guest') { + $scope.describePolicyId = true; + $scope.viewPolicyId = true; + } else if ($scope.temp.model.roleType == 'admin') { + $scope.createScopeId = true; + $scope.renameId = true; + $scope.createPolicyId = true; + $scope.cloneId = true; + $scope.editPolicyId = true; + $scope.switchVersionId = true; + $scope.describePolicyId = true; + $scope.viewPolicyId = true; + $scope.deletePolicyId = true; + } }; $scope.smartClick = function(item) { @@ -186,10 +195,10 @@ app.controller('PolicyManagerController', [ return currentPath.indexOf(path) !== -1; }; - $scope.watchPolicy = function(item){ + $scope.watchPolicy = function(item) { var uuu = "watchPolicy"; var data = {name : item.model.name, - path : item.model.path}; + path : item.model.path}; var postData={watchData: data}; $.ajax({ type : 'POST', @@ -197,32 +206,31 @@ app.controller('PolicyManagerController', [ dataType: 'json', contentType: 'application/json', data: JSON.stringify(postData), - success : function(data){ - $scope.$apply(function(){ + success : function(data) { + $scope.$apply(function() { $scope.watchData=data.watchData;}); Notification.success($scope.watchData); console.log($scope.watchData); }, - error : function(data){ + error : function(data) { alert("Error while saving."); } }); }; - - - $scope.refresh = function(){ - $scope.policyNavigator.refresh(); + + $scope.refresh = function() { + $scope.policyNavigator.refresh(); }; - - $scope.switchVersion = function(item){ - if ($scope.policyNavigator.fileNameExists(item.tempModel.content.activeVersion)) { + + $scope.switchVersion = function(item) { + if ($scope.policyNavigator.fileNameExists(item.tempModel.content.activeVersion)) { item.error = 'Invalid filename or already exists, specify another name'; return false; } - item.getSwitchVersionContent().then(function(){ - $scope.policyNavigator.refresh(); - $scope.modal('switchVersion', true); - }); + item.getSwitchVersionContent().then(function(){ + $scope.policyNavigator.refresh(); + $scope.modal('switchVersion', true); + }); }; $scope.copy = function(item) { @@ -250,7 +258,7 @@ app.controller('PolicyManagerController', [ $scope.modal('deletePolicy', true); }); }; - + $scope.rename = function(item) { var samePath = item.tempModel.path.join() === item.model.path.join(); if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) { @@ -262,7 +270,7 @@ app.controller('PolicyManagerController', [ $scope.modal('rename', true); }); }; - + $scope.move = function(item) { var samePath = item.tempModel.path.join() === item.model.path.join(); if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) { @@ -291,22 +299,22 @@ app.controller('PolicyManagerController', [ }; $scope.subScopeFolder = function(item) { - var name = item.tempModel.name +"\\" + item.tempModel.subScopename && item.tempModel.name.trim() + "\\"+item.tempModel.subScopename.trim() ; - item.tempModel.type = 'dir'; - item.tempModel.path = $scope.policyNavigator.currentPath; - if (name && !$scope.policyNavigator.fileNameExists(name)) { - item.getScopeContent().then(function() { - $scope.policyNavigator.refresh(); - $scope.modal('addSubScope', true); - }); - } else { - item.error = 'Invalid filename or already exists, specify another name'; - return false; - } + var name = item.tempModel.name +"\\" + item.tempModel.subScopename && item.tempModel.name.trim() + "\\"+item.tempModel.subScopename.trim() ; + item.tempModel.type = 'dir'; + item.tempModel.path = $scope.policyNavigator.currentPath; + if (name && !$scope.policyNavigator.fileNameExists(name)) { + item.getScopeContent().then(function() { + $scope.policyNavigator.refresh(); + $scope.modal('addSubScope', true); + }); + } else { + item.error = 'Invalid filename or already exists, specify another name'; + return false; + } }; - - $scope.closefunction = function(fianlPath){ - $scope.policyNavigator.policyrefresh(fianlPath); + + $scope.closefunction = function(fianlPath) { + $scope.policyNavigator.policyrefresh(fianlPath); }; $scope.uploadFiles = function() { diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js index 0e095a841..26cdf67c3 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -30,6 +30,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun version: model && model.version || '', createdBy: model && model.createdBy || '', modifiedBy: model && model.modifiedBy || '', + roleType: model && model.roleType || '', content: model && model.content || '', recursive: false, sizeKb: function() { @@ -84,7 +85,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun this.update(); return deferred.resolve(data); }; - + Item.prototype.createFolder = function() { var self = this; var deferred = $q.defer(); @@ -139,11 +140,11 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun self.inprocess = true; self.error = ''; $http.post(policyManagerConfig.renameUrl, data).success(function(data) { - if(data.result.error != undefined){ - var value = data.result.error; - value = value.replace("rename" , "move"); - data.result.error = value; - } + if(data.result.error != undefined){ + var value = data.result.error; + value = value.replace("rename" , "move"); + data.result.error = value; + } self.deferredHandler(data, deferred); }).error(function(data) { self.deferredHandler(data, deferred, 'Error Occured While Moving'); @@ -152,7 +153,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun }); return deferred.promise; }; - + Item.prototype.copy = function() { var self = this; var deferred = $q.defer(); @@ -249,7 +250,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun }); return deferred.promise; }; - + Item.prototype.getDescribePolicyContent = function() { var self = this; var deferred = $q.defer(); @@ -263,7 +264,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun $http.post(policyManagerConfig.describePolicyUrl, data).success(function(data) { self.tempModel.content = self.model.content = data.html; var describeTemplate = self.tempModel.content; - + self.deferredHandler(data, deferred); }).error(function(data) { self.deferredHandler(data, deferred, 'Error Occured While retrieving the Policy Data to Describe'); @@ -315,7 +316,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun }); return deferred.promise; }; - + Item.prototype.removePolicy = function() { var self = this; var deferred = $q.defer(); diff --git a/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties b/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties index 315fb4d67..8835fe45d 100644 --- a/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties +++ b/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties @@ -2,7 +2,7 @@ # ============LICENSE_START======================================================= # ONAP Policy Engine # ================================================================================ -# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. +# Copyright (C) 2017-2019 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. @@ -164,3 +164,5 @@ gui_url=https://${{AAF_HOST}}:8095/AAF_NS.gui.2.1 # Decision Response settings. # can be either PERMIT or DENY. decision.indeterminate.response=${{DECISION_INDETERMINATE_RESPONSE}} + +msToscaModel.home=${{REST_PDP_WEBAPPS}} \ No newline at end of file