From 9ffce7748d288fde9e55d92367a858020e5a32fc Mon Sep 17 00:00:00 2001 From: rb7147 Date: Tue, 27 Feb 2018 12:09:16 -0500 Subject: Added Junits for Policy PAP-REST Issue-ID: POLICY-600 Change-Id: I1d42a3a880c9d81115d48794a77fadb89562e136 Signed-off-by: rb7147 --- .../policy/pap/xacml/rest/DictionaryNames.java | 56 ++++ .../policy/pap/xacml/rest/DisctionaryNames.java | 56 ---- .../controller/DictionaryImportController.java | 369 +++++++++------------ .../rest/controller/SafePolicyController.java | 327 +++++------------- 4 files changed, 283 insertions(+), 525 deletions(-) create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java delete mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DisctionaryNames.java (limited to 'ONAP-PAP-REST/src/main') diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java new file mode 100644 index 000000000..3735316c4 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-Logging + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + + +package org.onap.policy.pap.xacml.rest; + +/** + * + * MessageCodes contains all the valid Dictionary names + * + */ +public enum DictionaryNames { + + Attribute, + ActionPolicyDictionary, + OnapName, + MSPolicyDictionary, + VNFType, + VSCLAction, + ClosedLoopService, + ClosedLoopSite, + PEPOptions, + VarbindDictionary, + BRMSParamDictionary, + BRMSControllerDictionary, + BRMSDependencyDictionary, + Settings, + PrefixList, + SecurityZone, + Zone, + ServiceList, + ServiceGroup, + AddressGroup, + ProtocolList, + ActionList, + TermList, + SearchCriteria +} + diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DisctionaryNames.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DisctionaryNames.java deleted file mode 100644 index f0dfa0ad2..000000000 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DisctionaryNames.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-Logging - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - - -package org.onap.policy.pap.xacml.rest; - -/** - * - * MessageCodes contains all the valid Dictionary names - * - */ -public enum DisctionaryNames { - - Attribute, - ActionPolicyDictionary, - OnapName, - MSPolicyDictionary, - VNFType, - VSCLAction, - ClosedLoopService, - ClosedLoopSite, - PEPOptions, - VarbindDictionary, - BRMSParamDictionary, - BRMSControllerDictionary, - BRMSDependencyDictionary, - Settings, - PrefixList, - SecurityZone, - Zone, - ServiceList, - ServiceGroup, - AddressGroup, - ProtocolList, - ActionList, - TermList, - SearchCriteria -} - 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 142f72b97..f3c78ffb9 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 @@ -19,10 +19,7 @@ */ package org.onap.policy.pap.xacml.rest.controller; - /* - * - * - * */ + import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; @@ -36,7 +33,7 @@ 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; -import org.onap.policy.pap.xacml.rest.DisctionaryNames; +import org.onap.policy.pap.xacml.rest.DictionaryNames; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ActionList; import org.onap.policy.rest.jpa.ActionPolicyDict; @@ -68,6 +65,7 @@ import org.onap.policy.rest.jpa.Zone; import org.springframework.beans.factory.annotation.Autowired; 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; @@ -79,8 +77,6 @@ import au.com.bytecode.opencsv.CSVReader; public class DictionaryImportController { private static final Logger LOGGER = FlexLogger.getLogger(DictionaryImportController.class); - private String newFile; - private static CommonClassDao commonClassDao; private static final String DESCRIPTION= "description"; @@ -89,11 +85,13 @@ public class DictionaryImportController { DictionaryImportController.commonClassDao = commonClassDao; } - public DictionaryImportController(){} + public DictionaryImportController(){ + super(); + } - @RequestMapping(value={"/dictionary/import_dictionary"}, method={org.springframework.web.bind.annotation.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"); @@ -109,22 +107,16 @@ public class DictionaryImportController { // fix Fortify Path Manipulation issue if(!isValidDictionaryName(dictionaryName)){ LOGGER.error("dictionaryName is invalid"); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.getWriter().write("Error"); + response.setStatus(HttpServletResponse.SC_OK); + response.getWriter().write("Dictionary Import failed. Hence the following dictionary doen't support import function : "+ dictionaryName); return; } - - boolean dictionaryImportExists = false; - try{ - File file = new File(dictionaryName); - OutputStream outputStream = new FileOutputStream(file); + File file = new File(dictionaryName); + try(OutputStream outputStream = new FileOutputStream(file); FileReader fileReader = new FileReader(file.toString())){ IOUtils.copy(request.getInputStream(), outputStream); - outputStream.close(); - this.newFile = file.toString(); - CSVReader csvReader = new CSVReader(new FileReader(this.newFile)); + CSVReader csvReader = new CSVReader(fileReader); List dictSheet = csvReader.readAll(); if(dictionaryName.startsWith("Attribute")){ - dictionaryImportExists = true; for(int i = 1; i< dictSheet.size(); i++){ Attribute attribute = new Attribute(""); UserInfo userinfo = new UserInfo(); @@ -133,26 +125,26 @@ public class DictionaryImportController { attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); for (int j=0 ; j model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("riskTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(RiskType.class, "name"))); - 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); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, riskTypeDatas, "name", RiskType.class); } @RequestMapping(value = { "/get_RiskTypeData" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) public void getRiskTypeDictionaryEntityData(HttpServletResponse response) { - try { - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("riskTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(RiskType.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader(operation, "getDictionary"); - response.getWriter().write(j.toString()); - } catch (Exception e) { - LOGGER.error(e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } + 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 { + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter(apiflag)!=null && ("api").equalsIgnoreCase(request.getParameter(apiflag))) { - fromAPI = true; - } + boolean fromAPI = utils.isRequestFromAPI(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); 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"; - - //check if update operation or create, get id for data to be updated and update attributeData - if ("update".equalsIgnoreCase(request.getParameter(operation))){ - List duplicateData = commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); - RiskType data = (RiskType) duplicateData.get(0); - int id = data.getId(); - - if(id==0){ - isFakeUpdate=true; - riskTypeData.setId(1); - } else { - riskTypeData.setId(id); - } - - riskTypeData.setUserCreatedBy(this.getUserInfo(userId)); - } } else { riskTypeData = mapper.readValue(root.get("riskTypeDictionaryData").toString(), RiskType.class); userId = root.get("userid").textValue(); } - - if (riskTypeData.getId() == 0) { - List duplicateData = commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); - if(!duplicateData.isEmpty()){ + UserInfo userInfo = utils.getUserInfo(userId); + List duplicateData = commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + RiskType data = (RiskType) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - riskTypeData.setUserCreatedBy(getUserInfo(userId)); - riskTypeData.setUserModifiedBy(getUserInfo(userId)); - commonClassDao.save(riskTypeData); } - } else { - if (!isFakeUpdate) { - riskTypeData.setUserModifiedBy(this.getUserInfo(userId)); + } + String responseString = null; + if(!duplicateflag){ + riskTypeData.setUserModifiedBy(userInfo); + if(riskTypeData.getId() == 0){ + riskTypeData.setUserCreatedBy(userInfo); + commonClassDao.save(riskTypeData); + }else{ riskTypeData.setModifiedDate(new Date()); - commonClassDao.update(riskTypeData); - } + commonClassDao.update(riskTypeData); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(RiskType.class)); + }else{ + responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, riskTypeDatas, responseString); } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(RiskType.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals(duplicateResponseString)) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{riskTypeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } }catch (Exception e) { - LOGGER.error(e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } @RequestMapping(value = { "/sp_dictionary/remove_riskType" }, method = {RequestMethod.POST }) - public ModelAndView removeRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - RiskType onapData = mapper.readValue(root.get("data").toString(), RiskType.class); - commonClassDao.delete(onapData); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(RiskType.class)); - JSONObject j = new JSONObject("{riskTypeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } catch (Exception e) { - LOGGER.error(e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; + 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) public void getSafePolicyWarningEntityDataByName(HttpServletResponse response) { - try { - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("safePolicyWarningDatas", - mapper.writeValueAsString(commonClassDao.getDataByColumn(SafePolicyWarning.class, "name"))); - 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); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, safePolicyWarningDatas, "name", SafePolicyWarning.class); } @RequestMapping(value = { "/get_SafePolicyWarningData" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) public void getSafePolicyWarningeEntityData(HttpServletResponse response) { - try { - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("safePolicyWarningDatas", - mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader(operation, "getDictionary"); - response.getWriter().write(j.toString()); - } catch (Exception e) { - LOGGER.error(e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } + 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 { + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter(apiflag)!=null && ("api").equalsIgnoreCase(request.getParameter(apiflag))) { - fromAPI = true; - } + boolean fromAPI = utils.isRequestFromAPI(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); SafePolicyWarning safePolicyWarning; if (fromAPI) { safePolicyWarning = mapper.readValue(root.get("dictionaryFields").toString(), SafePolicyWarning.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (("update").equals(request.getParameter(operation))) { - List duplicateData = commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class); - SafePolicyWarning data = (SafePolicyWarning) duplicateData.get(0); - int id = data.getId(); - - if(id==0){ - isFakeUpdate=true; - safePolicyWarning.setId(1); - } else { - safePolicyWarning.setId(id); - } - } } else { safePolicyWarning = mapper.readValue(root.get("safePolicyWarningData").toString(), SafePolicyWarning.class); } - if (safePolicyWarning.getId() == 0) { - List duplicateData = commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class); - if(!duplicateData.isEmpty()){ + List duplicateData = commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + SafePolicyWarning data = (SafePolicyWarning) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - commonClassDao.save(safePolicyWarning); - } - } else { - if(!isFakeUpdate) { - commonClassDao.update(safePolicyWarning); } } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals(duplicateResponseString)) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{safePolicyWarningDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - + String responseString = null; + if(!duplicateflag){ + if(safePolicyWarning.getId() == 0){ + commonClassDao.save(safePolicyWarning); + }else{ + commonClassDao.update(safePolicyWarning); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); + }else{ + responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, safePolicyWarningDatas, responseString); + } }catch (Exception e) { - LOGGER.error(e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } @RequestMapping(value = { "/sp_dictionary/remove_SafePolicyWarning" }, method = {RequestMethod.POST }) public void removeSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - SafePolicyWarning safePolicyWarningData = mapper.readValue(root.get("data").toString(), - SafePolicyWarning.class); - commonClassDao.delete(safePolicyWarningData); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); - JSONObject j = new JSONObject("{safePolicyWarningDatas: " + responseString + "}"); - out.write(j.toString()); - } catch (Exception e) { - LOGGER.error(e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, safePolicyWarningDatas, SafePolicyWarning.class); } } -- cgit 1.2.3-korg