diff options
author | rb7147 <rb7147@att.com> | 2018-02-26 18:04:46 -0500 |
---|---|---|
committer | rb7147 <rb7147@att.com> | 2018-02-27 09:56:31 -0500 |
commit | ccc932599675c927519040399b031ff1d10d9510 (patch) | |
tree | 83b43e211d982e2c80eee09e355844dd1b7c8145 /ONAP-PAP-REST/src/main/java | |
parent | 47c1630d48e40e1fbc051fa6eae251ffbe1d4945 (diff) |
Code Clean Up for Policy PAP-REST
Cleaned the duplicate code for all dictionary controllers and created
Utils class.
Issue-ID: POLICY-600
Change-Id: I65b8574d9f667758407515a5c55bc28f636be477
Signed-off-by: rb7147 <rb7147@att.com>
Diffstat (limited to 'ONAP-PAP-REST/src/main/java')
12 files changed, 2124 insertions, 5175 deletions
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java index fee4ed2cb..1b9afe547 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,6 +31,7 @@ import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.hibernate.SessionFactory; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.utils.CryptoUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -64,7 +65,7 @@ public class PAPRestConfig extends WebMvcConfigurerAdapter { setDbDriver(prop.getProperty("javax.persistence.jdbc.driver")); setDbUrl(prop.getProperty("javax.persistence.jdbc.url")); setDbUserName(prop.getProperty("javax.persistence.jdbc.user")); - setDbPassword(prop.getProperty("javax.persistence.jdbc.password")); + setDbPassword( CryptoUtils.decryptTxtNoExStr(prop.getProperty("javax.persistence.jdbc.password", ""))); }catch(Exception e){ LOGGER.error("Exception Occured while loading properties file"+e); }finally{ @@ -138,8 +139,8 @@ public class PAPRestConfig extends WebMvcConfigurerAdapter { return dbPassword; } - public static void setDbPassword(String dbPassword) { - PAPRestConfig.dbPassword = dbPassword; + public static void setDbPassword(String dbPassword) { + PAPRestConfig.dbPassword = CryptoUtils.decryptTxtNoExStr(dbPassword); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java index 7c0d2683c..45080cee9 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,4 +70,14 @@ public class CreateBRMSRuleTemplate { return responseMap; } + public static boolean validateRuleParams(String rule) { + CreateBrmsParamPolicy policy = new CreateBrmsParamPolicy(); + Map<String, String> paramValues = policy.findType(rule); + for(String key : paramValues.keySet()) { + if(!PolicyUtils.SUCCESS.equals(PolicyUtils.policySpecialCharValidator(key))){ + return false; + } + } + return true; + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java index 02b0707b6..3d275c3d9 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java @@ -21,28 +21,21 @@ package org.onap.policy.pap.xacml.rest.controller; import java.io.IOException; -import java.io.PrintWriter; import java.util.Date; -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.json.JSONObject; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ActionPolicyDict; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.utils.PolicyUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -51,12 +44,12 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Controller public class ActionPolicyDictionaryController { - - private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyDictionaryController.class); - + private static CommonClassDao commonClassDao; - private static String utf8 = "UTF-8"; + private static String operation = "operation"; private static String attributeName = "attributeName"; + private static String actionDatas = "actionPolicyDictionaryDatas"; + @Autowired public ActionPolicyDictionaryController(CommonClassDao commonClassDao){ ActionPolicyDictionaryController.commonClassDao = commonClassDao; @@ -65,190 +58,91 @@ public class ActionPolicyDictionaryController { public void setCommonClassDao(CommonClassDao commonClassDao){ ActionPolicyDictionaryController.commonClassDao = commonClassDao; } - /* - * This is an empty constructor - */ - public ActionPolicyDictionaryController(){ + public ActionPolicyDictionaryController(){ + super(); } - public UserInfo getUserInfo(String loginId){ - return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + private DictionaryUtils getDictionaryUtilsInstance(){ + return DictionaryUtils.dictionaryUtils != null ? DictionaryUtils.getDictionaryUtils() : new DictionaryUtils(); } - - @RequestMapping(value={"/get_ActionPolicyDictDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + + @RequestMapping(value={"/get_ActionPolicyDictDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getActionEntitybyName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("actionPolicyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ActionPolicyDict.class, attributeName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e.getMessage(),e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, actionDatas, attributeName, ActionPolicyDict.class); } - @RequestMapping(value={"/get_ActionPolicyDictData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ActionPolicyDictData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getActionPolicyDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("actionPolicyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ActionPolicyDict.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.getMessage(),e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, actionDatas, ActionPolicyDict.class); } - @RequestMapping(value={"/action_dictionary/save_ActionDict"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value={"/action_dictionary/save_ActionDict"}, method={RequestMethod.POST}) + public ModelAndView saveActionPolicyDictionary(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()); ActionPolicyDict actionPolicyDict = null; ActionAdapter adapter = null; String userId = null; - - if(fromAPI) { + if(fromAPI){ actionPolicyDict = mapper.readValue(root.get("dictionaryFields").toString(), ActionPolicyDict.class); adapter = mapper.readValue(root.get("dictionaryFields").toString(), ActionAdapter.class); userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (("update").equals(request.getParameter("operation"))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), attributeName, ActionPolicyDict.class); - ActionPolicyDict data = (ActionPolicyDict) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - actionPolicyDict.setId(1); - } else { - actionPolicyDict.setId(id); - } - actionPolicyDict.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { + }else{ actionPolicyDict = mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionPolicyDict.class); adapter = mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionAdapter.class); userId = root.get("userid").textValue(); } - StringBuilder header = new StringBuilder(); - int counter = 0; - if(!adapter.getHeaders().isEmpty()){ - for(Object attribute : adapter.getHeaders()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString(); - String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString(); - if(counter>0){ - header.append(":"); - } - header.append(key).append("=").append(value); - counter ++; - } + UserInfo userInfo = utils.getUserInfo(userId); + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), attributeName, ActionPolicyDict.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + ActionPolicyDict data = (ActionPolicyDict) duplicateData.get(0); + if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + actionPolicyDict.setId(data.getId()); + }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || + (request.getParameter(operation) == null && (data.getId() != actionPolicyDict.getId()))){ + duplicateflag = true; } } - actionPolicyDict.setHeader(header.toString()); - if(actionPolicyDict.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), attributeName, ActionPolicyDict.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - actionPolicyDict.setUserCreatedBy(this.getUserInfo(userId)); - actionPolicyDict.setUserModifiedBy(this.getUserInfo(userId)); + actionPolicyDict.setHeader(utils.appendKeyValue(adapter.getHeaders(), ":", "=")); + + String responseString = null; + if(!duplicateflag){ + actionPolicyDict.setUserModifiedBy(userInfo); + if(actionPolicyDict.getId() == 0){ + actionPolicyDict.setUserCreatedBy(userInfo); commonClassDao.save(actionPolicyDict); - } - }else{ - if(!isFakeUpdate) { - actionPolicyDict.setUserModifiedBy(this.getUserInfo(userId)); + }else{ actionPolicyDict.setModifiedDate(new Date()); commonClassDao.update(actionPolicyDict); - } - } - - String responseString = null; - if(duplicateflag) { - responseString = "Duplicate"; - } else { + } responseString = mapper.writeValueAsString(commonClassDao.getData(ActionPolicyDict.class)); + }else{ + responseString = "Duplicate"; } - - if (fromAPI) { - if (responseString!=null && !("Duplicate").equals(responseString)) { - if(isFakeUpdate) { - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding(utf8); - response.setContentType("application / json"); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{actionPolicyDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, actionDatas, responseString); } - } - catch (Exception e){ - LOGGER.error(e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + }catch(Exception e){ + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/action_dictionary/remove_actionPolicyDict"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/action_dictionary/remove_actionPolicyDict"}, method={RequestMethod.POST}) public void removeActionPolicyDictionary(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()); - ActionPolicyDict actionPolicyDict = mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); - commonClassDao.delete(actionPolicyDict); - response.setCharacterEncoding(utf8); - response.setContentType("application / json"); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(ActionPolicyDictionaryController.commonClassDao.getData(ActionPolicyDict.class)); - JSONObject j = new JSONObject("{actionPolicyDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, actionDatas, ActionPolicyDict.class); } } 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 3e695b7da..f07ca3478 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 @@ -21,27 +21,25 @@ package org.onap.policy.pap.xacml.rest.controller; import java.io.IOException; -import java.io.PrintWriter; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.Date; -import java.util.HashMap; import java.util.List; -import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; -import org.json.JSONObject; import org.onap.policy.api.PEDependency; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.pap.xacml.rest.components.CreateBRMSRuleTemplate; +import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.BRMSController; import org.onap.policy.rest.jpa.BRMSDependency; import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.OnapName; import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; @@ -49,6 +47,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -61,78 +60,53 @@ public class BRMSDictionaryController{ private static final Logger LOGGER = FlexLogger.getLogger(BRMSDictionaryController.class); - + private static final String VALIDATIONRESPONSE = "Validation"; + private static CommonClassDao commonClassDao; private static String rule; - private static String utf8 = "UTF-8"; - private static String applicationJsonContentType = "application / json"; private static String successMsg = "Success"; - private static String successMessage = "success"; private static String duplicateResponseString = "Duplicate"; private static String ruleName = "ruleName"; - private static String successMapKey = "successMapKey"; - private static String errorMsg = "error"; private static String errorMessage = "Error"; - private static String dictionaryDBQuery = "dictionaryDBQuery"; private static String operation = "operation"; - private static String getDictionary = "getDictionary"; - private static String apiflag = "apiflag"; private static String dictionaryFields ="dictionaryFields"; - private static String update = "update"; private static String userid = "userid"; private static String dependencyName = "dependencyName"; private static String controllerName = "controllerName"; + private static String brmsParamDatas = "brmsParamDictionaryDatas"; + private static String brmsDependencyDatas = "brmsDependencyDictionaryDatas"; + private static String brmsControllerDatas = "brmsControllerDictionaryDatas"; + @Autowired public BRMSDictionaryController(CommonClassDao commonClassDao){ BRMSDictionaryController.commonClassDao = commonClassDao; } + public static void setCommonClassDao(CommonClassDao commonClassDao2) { - BRMSDictionaryController.commonClassDao = commonClassDao2; + BRMSDictionaryController.commonClassDao = commonClassDao2; + } + + public BRMSDictionaryController() { + super(); } - /* - * This is an empty constructor - */ - public BRMSDictionaryController() {} - public UserInfo getUserInfo(String loginId){ - return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + private DictionaryUtils getDictionaryUtilsInstance(){ + return DictionaryUtils.dictionaryUtils != null ? DictionaryUtils.getDictionaryUtils() : new DictionaryUtils(); } - @RequestMapping(value={"/get_BRMSParamDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_BRMSParamDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getBRMSParamDictionaryByNameEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("brmsParamDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(BRMSParamTemplate.class, ruleName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, brmsParamDatas, ruleName, BRMSParamTemplate.class); } - @RequestMapping(value={"/get_BRMSParamData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_BRMSParamData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getBRMSParamDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("brmsParamDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, brmsParamDatas, BRMSParamTemplate.class); } - @RequestMapping(value={"/brms_dictionary/set_BRMSParamData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @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); @@ -140,431 +114,271 @@ public class BRMSDictionaryController{ rule = cleanStreamBoundary.substring(0, cleanStreamBoundary.lastIndexOf("end")+4); } - @RequestMapping(value={"/brms_dictionary/save_BRMSParam"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/brms_dictionary/save_BRMSParam"}, method={RequestMethod.POST}) public ModelAndView saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = 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()); BRMSParamTemplate bRMSParamTemplateData; String userId = null; - if(fromAPI) { - bRMSParamTemplateData = (BRMSParamTemplate)mapper.readValue(root.get(dictionaryFields).toString(), BRMSParamTemplate.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(bRMSParamTemplateData.getRuleName(), ruleName, BRMSParamTemplate.class); - BRMSParamTemplate data = (BRMSParamTemplate) duplicateData.get(0); - int id = data.getId(); - bRMSParamTemplateData.setId(id); - bRMSParamTemplateData.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - bRMSParamTemplateData = (BRMSParamTemplate)mapper.readValue(root.get("brmsParamDictionaryData").toString(), BRMSParamTemplate.class); - userId = root.get(userid).textValue(); - } - - bRMSParamTemplateData.setRule(rule); - if(bRMSParamTemplateData.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(bRMSParamTemplateData.getRuleName(), ruleName, BRMSParamTemplate.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - bRMSParamTemplateData.setUserCreatedBy(this.getUserInfo(userId)); - commonClassDao.save(bRMSParamTemplateData); - } - }else{ - commonClassDao.update(bRMSParamTemplateData); - } - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; + if(fromAPI){ + bRMSParamTemplateData = mapper.readValue(root.get(dictionaryFields).toString(), BRMSParamTemplate.class); + userId = "API"; }else{ - responseString = mapper.writeValueAsString(BRMSDictionaryController.commonClassDao.getData(BRMSParamTemplate.class)); + bRMSParamTemplateData = mapper.readValue(root.get("brmsParamDictionaryData").toString(), BRMSParamTemplate.class); + userId = root.get(userid).textValue(); } - if(fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { + UserInfo userInfo = utils.getUserInfo(userId); + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(bRMSParamTemplateData.getRuleName(), ruleName, BRMSParamTemplate.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + BRMSParamTemplate data = (BRMSParamTemplate) duplicateData.get(0); + 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()))){ + duplicateflag = true; + } + } + String responseString = null; + boolean validation = false; + if(rule != null && CreateBRMSRuleTemplate.validateRuleParams(rule)){ + bRMSParamTemplateData.setRule(rule); + validation = true; + if(!duplicateflag){ + if(bRMSParamTemplateData.getId() == 0){ + bRMSParamTemplateData.setUserCreatedBy(userInfo); + commonClassDao.save(bRMSParamTemplateData); + }else{ + commonClassDao.update(bRMSParamTemplateData); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class)); + }else{ + responseString = duplicateResponseString; + } + } + + if(!validation){ + responseString = VALIDATIONRESPONSE; + } + if(fromAPI){ + if (responseString!=null && !(duplicateResponseString).equals(responseString) && !VALIDATIONRESPONSE.equals(responseString)) { responseString = successMsg; } 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("{brmsParamDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); + }else{ + utils.setResponseData(response, brmsParamDatas, responseString); + } + }catch(Exception e){ + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/brms_dictionary/remove_brmsParam"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeBRMSParamDictionary(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()); - BRMSParamTemplate bRMSParamTemplateData = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); - commonClassDao.delete(bRMSParamTemplateData); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(BRMSDictionaryController.commonClassDao.getData(BRMSParamTemplate.class)); - JSONObject j = new JSONObject("{brmsParamDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; + @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={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_BRMSDependencyDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getBRMSDependencyDictionaryByNameEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("brmsDependencyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(BRMSDependency.class, dependencyName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, brmsDependencyDatas, dependencyName, BRMSDependency.class); } - @RequestMapping(value={"/get_BRMSDependencyData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_BRMSDependencyData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getBRMSDependencyDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("brmsDependencyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, brmsDependencyDatas, BRMSDependency.class); } - @RequestMapping(value={"/brms_dictionary/save_BRMSDependencyData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/brms_dictionary/save_BRMSDependencyData"}, method={RequestMethod.POST}) public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { - try { - boolean duplicateflag = false; - LOGGER.debug("DictionaryController: saveBRMSDependencyDictionary() is called"); - - boolean fromAPI = false; - if (request.getParameter(apiflag)!=null && ("api").equalsIgnoreCase(request.getParameter(apiflag))) { - fromAPI = true; - } - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - - BRMSDependency brmsDependency; - String userId = null; - if (fromAPI) { - brmsDependency = (BRMSDependency)mapper.readValue(root.get(dictionaryFields).toString(), BRMSDependency.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsDependency.getDependencyName(), dependencyName, BRMSDependency.class); - BRMSDependency data = (BRMSDependency) duplicateData.get(0); - int id = data.getId(); - brmsDependency.setId(id); - brmsDependency.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - brmsDependency = (BRMSDependency)mapper.readValue(root.get("brmsDependencyDictionaryData").toString(), BRMSDependency.class); - userId = root.get(userid).textValue(); - } - - LOGGER.audit("the userId from the onap portal is: " + userId); - String responseString = null; - - 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); - } - if(dependency==null){ - responseString = errorMessage; - }else{ - if(brmsDependency.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsDependency.getDependencyName(), dependencyName, BRMSDependency.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - brmsDependency.setUserCreatedBy(getUserInfo(userId)); - brmsDependency.setUserModifiedBy(getUserInfo(userId)); - LOGGER.audit("DictionaryController: got the user info now about to call Save() method on brmsDependencydao"); - commonClassDao.save(brmsDependency); - } - }else{ - brmsDependency.setUserModifiedBy(this.getUserInfo(userId)); - brmsDependency.setModifiedDate(new Date()); - commonClassDao.update(brmsDependency); - } - if(duplicateflag) { - responseString = duplicateResponseString; - } else { - responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class)); - } - } - } - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString) && !(errorMessage).equals(responseString)) { - responseString = successMsg; - } - 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("{brmsDependencyDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - } catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; + DictionaryUtils utils = getDictionaryUtilsInstance(); + try { + LOGGER.debug("DictionaryController: saveBRMSDependencyDictionary() is called"); + boolean fromAPI = utils.isRequestFromAPI(request); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + BRMSDependency brmsDependency; + String userId = null; + if(fromAPI){ + brmsDependency = mapper.readValue(root.get(dictionaryFields).toString(), BRMSDependency.class); + userId = "API"; + }else{ + brmsDependency = mapper.readValue(root.get("brmsDependencyDictionaryData").toString(), BRMSDependency.class); + userId = root.get(userid).textValue(); + } + UserInfo userInfo = utils.getUserInfo(userId); + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsDependency.getDependencyName(), dependencyName, BRMSDependency.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + BRMSDependency data = (BRMSDependency) duplicateData.get(0); + 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()))){ + duplicateflag = true; + } + } + LOGGER.audit("the userId from the onap portal is: " + userId); + String responseString = null; + 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); + } + if(dependency==null){ + responseString = errorMessage; + }else{ + if(!duplicateflag){ + brmsDependency.setUserModifiedBy(userInfo); + if(brmsDependency.getId() == 0){ + brmsDependency.setUserCreatedBy(userInfo); + commonClassDao.save(brmsDependency); + }else{ + brmsDependency.setModifiedDate(new Date()); + commonClassDao.update(brmsDependency); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class)); + }else{ + responseString = duplicateResponseString; + } + } + } + + if(fromAPI){ + if(responseString!=null && !duplicateResponseString.equals(responseString) && !errorMessage.equals(responseString)){ + responseString = successMsg; + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + }else{ + utils.setResponseData(response, brmsDependencyDatas, responseString); + } + } catch (Exception e){ + utils.setErrorResponseData(response, e); + } + return null; } - @RequestMapping(value={"/brms_dictionary/remove_brmsDependency"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeBRMSDependencyDictionary(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()); - BRMSDependency brmsDependency = (BRMSDependency)mapper.readValue(root.get("data").toString(), BRMSDependency.class); - commonClassDao.delete(brmsDependency); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class)); - JSONObject j = new JSONObject("{brmsDependencyDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; + @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={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_BRMSControllerDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getBRMSControllerDictionaryByNameEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("brmsControllerDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(BRMSController.class, controllerName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, brmsControllerDatas, controllerName, BRMSController.class); } - @RequestMapping(value={"/get_BRMSControllerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_BRMSControllerData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getBRMSControllerDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("brmsControllerDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(BRMSController.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, brmsControllerDatas, BRMSController.class); } - @RequestMapping(value={"/brms_dictionary/save_BRMSControllerData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/brms_dictionary/save_BRMSControllerData"}, method={RequestMethod.POST}) public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ - try { - boolean duplicateflag = false; - LOGGER.debug("DictionaryController: saveBRMSControllerDictionary() is called"); - boolean fromAPI = false; - if (request.getParameter(apiflag)!=null && ("api").equalsIgnoreCase(request.getParameter(apiflag))) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - BRMSController brmsController; - String userId = null; - if (fromAPI) { - brmsController = (BRMSController)mapper.readValue(root.get(dictionaryFields).toString(), BRMSController.class); - userId = "API"; - //check if update operation or create, get id for data to be updated - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsController.getControllerName(), controllerName, BRMSController.class); - BRMSController data = (BRMSController) duplicateData.get(0); - int id = data.getId(); - brmsController.setId(id); - brmsController.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - brmsController = (BRMSController)mapper.readValue(root.get("brmsControllerDictionaryData").toString(), BRMSController.class); - userId = root.get(userid).textValue(); - } - LOGGER.audit("the userId from the onap portal is: " + userId); - String responseString = null; - 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); - } - if(dependency==null){ - responseString = errorMessage; - }else{ - if(brmsController.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsController.getControllerName(), controllerName, BRMSController.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - brmsController.setUserCreatedBy(getUserInfo(userId)); - brmsController.setUserModifiedBy(getUserInfo(userId)); - LOGGER.audit("DictionaryController: got the user info now about to call Save() method on brmsControllerdao"); - commonClassDao.save(brmsController); - } - }else{ - brmsController.setUserModifiedBy(this.getUserInfo(userId)); - brmsController.setModifiedDate(new Date()); - commonClassDao.update(brmsController); - } - if(duplicateflag) { - responseString = duplicateResponseString; - } else { - responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSController.class)); - } - } - } - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString) && !(errorMessage).equals(responseString)) { - responseString = successMsg; - } - 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("{brmsControllerDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - } catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; + DictionaryUtils utils = getDictionaryUtilsInstance(); + try { + LOGGER.debug("DictionaryController: saveBRMSControllerDictionary() is called"); + boolean fromAPI = utils.isRequestFromAPI(request); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + BRMSController brmsController; + String userId = null; + if(fromAPI){ + brmsController = mapper.readValue(root.get(dictionaryFields).toString(), BRMSController.class); + userId = "API"; + }else{ + brmsController = mapper.readValue(root.get("brmsControllerDictionaryData").toString(), BRMSController.class); + userId = root.get(userid).textValue(); + } + UserInfo userInfo = utils.getUserInfo(userId); + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsController.getControllerName(), controllerName, BRMSController.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + BRMSController data = (BRMSController) duplicateData.get(0); + 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()))){ + duplicateflag = true; + } + } + String responseString = null; + 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); + } + if(dependency==null){ + responseString = errorMessage; + }else{ + if(!duplicateflag){ + brmsController.setUserModifiedBy(userInfo); + if(brmsController.getId() == 0){ + brmsController.setUserCreatedBy(userInfo); + commonClassDao.save(brmsController); + }else{ + brmsController.setModifiedDate(new Date()); + commonClassDao.update(brmsController); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); + }else{ + responseString = duplicateResponseString; + } + } + } + if(fromAPI){ + if (responseString!=null && !(duplicateResponseString).equals(responseString) && !(errorMessage).equals(responseString)) { + responseString = successMsg; + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + }else{ + utils.setResponseData(response, brmsControllerDatas, responseString); + } + } catch (Exception e){ + utils.setErrorResponseData(response, e); + } + return null; } - @RequestMapping(value={"/brms_dictionary/remove_brmsController"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeBRMSControllerDictionary(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()); - BRMSController brmsController = (BRMSController)mapper.readValue(root.get("data").toString(), BRMSController.class); - commonClassDao.delete(brmsController); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSController.class)); - JSONObject j = new JSONObject("{brmsControllerDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; + @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, dependencyName, dependencyName); + return (BRMSDependency) commonClassDao.getEntityItem(BRMSDependency.class, BRMSDictionaryController.dependencyName, dependencyName); } public BRMSController getControllerDataByID(String controllerName){ - return (BRMSController) commonClassDao.getEntityItem(BRMSController.class, controllerName, 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 a55ed4004..2b0556716 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 @@ -21,36 +21,29 @@ package org.onap.policy.pap.xacml.rest.controller; import java.io.IOException; -import java.io.PrintWriter; import java.util.Date; -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.json.JSONObject; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; 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.JsonMessage; +import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ClosedLoopD2Services; import org.onap.policy.rest.jpa.ClosedLoopSite; +import org.onap.policy.rest.jpa.OnapName; import org.onap.policy.rest.jpa.PEPOptions; import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.rest.jpa.VNFType; import org.onap.policy.rest.jpa.VSCLAction; import org.onap.policy.rest.jpa.VarbindDictionary; -import org.onap.policy.utils.PolicyUtils; -import org.onap.policy.xacml.api.XACMLErrorConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -60,29 +53,23 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Controller public class ClosedLoopDictionaryController{ - private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopDictionaryController.class); - private static CommonClassDao commonClassDao; private static String vsclaction = "vsclaction"; - private static String successMapKey = "successMapKey"; - private static String successMessage = "success"; private static String operation = "operation"; - private static String getDictionary = "getDictionary"; - private static String dictionaryDBQuery = "dictionaryDBQuery"; - private static String errorMsg = "error"; private static String vnftype = "vnftype"; private static String pepName = "pepName"; private static String varbindName = "varbindName"; private static String serviceName = "serviceName"; private static String siteName = "siteName"; - private static String apiflag = "apiflag"; private static String dictionaryFields = "dictionaryFields"; - private static String update = "update"; private static String duplicateResponseString = "Duplicate"; private static String userid = "userid"; - private static String utf8 = "UTF-8"; - private static String applicationJsonContentType = "application / json"; - private static String successMsg = "Success"; + private static String vsclActionDatas = "vsclActionDictionaryDatas"; + private static String vnfTypeDatas = "vnfTypeDictionaryDatas"; + private static String pepOptionDatas = "pepOptionsDictionaryDatas"; + private static String varbindDatas = "varbindDictionaryDatas"; + private static String closedLoopDatas = "closedLoopServiceDictionaryDatas"; + private static String closedLoopSiteDatas = "closedLoopSiteDictionaryDatas"; @Autowired public ClosedLoopDictionaryController(CommonClassDao commonClassDao){ @@ -92,966 +79,466 @@ public class ClosedLoopDictionaryController{ public void setCommonClassDao(CommonClassDao commonClassDao){ ClosedLoopDictionaryController.commonClassDao = commonClassDao; } - /* - * This is an empty constructor - */ - public ClosedLoopDictionaryController(){} - public UserInfo getUserInfo(String loginId){ - return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + public static void setCommonClassDao(CommonClassDaoImpl commonClassDaoImpl) { + commonClassDao = commonClassDaoImpl; + } + + public ClosedLoopDictionaryController(){ + super(); } - - @RequestMapping(value={"/get_VSCLActionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + private DictionaryUtils getDictionaryUtilsInstance(){ + return DictionaryUtils.dictionaryUtils != null ? DictionaryUtils.getDictionaryUtils() : new DictionaryUtils(); + } + + @RequestMapping(value={"/get_VSCLActionDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getVSCLActionDictionaryByNameEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("vsclActionDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(VSCLAction.class, vsclaction))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, vsclActionDatas, vsclaction, VSCLAction.class); } - @RequestMapping(value={"/get_VSCLActionData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_VSCLActionData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getVSCLActionDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("vsclActionDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, vsclActionDatas, VSCLAction.class); } - @RequestMapping(value={"/get_VNFTypeDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_VNFTypeDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getVNFTypeDictionaryByNameEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("vnfTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(VNFType.class, vnftype))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, vnfTypeDatas, vnftype, VNFType.class); } - @RequestMapping(value={"/get_VNFTypeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_VNFTypeData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getVNFTypeDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("vnfTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(VNFType.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, vnfTypeDatas, VNFType.class); } - @RequestMapping(value={"/get_PEPOptionsDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_PEPOptionsDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPEPOptionsDictionaryByNameEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("pepOptionsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PEPOptions.class, pepName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, pepOptionDatas, pepName, PEPOptions.class); } - @RequestMapping(value={"/get_PEPOptionsData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_PEPOptionsData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPEPOptionsDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("pepOptionsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, pepOptionDatas, PEPOptions.class); } - @RequestMapping(value={"/get_VarbindDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_VarbindDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getVarbindDictionaryByNameEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("varbindDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(VarbindDictionary.class, varbindName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, varbindDatas, varbindName, VarbindDictionary.class); } - @RequestMapping(value={"/get_VarbindDictionaryData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_VarbindDictionaryData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getVarbindDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("varbindDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, varbindDatas, VarbindDictionary.class); } - @RequestMapping(value={"/get_ClosedLoopServicesDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ClosedLoopServicesDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getClosedLoopServiceDictionaryByNameEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("closedLoopServiceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ClosedLoopD2Services.class, serviceName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, closedLoopDatas, serviceName, ClosedLoopD2Services.class); } - @RequestMapping(value={"/get_ClosedLoopServicesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ClosedLoopServicesData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getClosedLoopServiceDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("closedLoopServiceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, closedLoopDatas, ClosedLoopD2Services.class); } - @RequestMapping(value={"/get_ClosedLoopSiteDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ClosedLoopSiteDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getClosedLoopSiteDictionaryByNameEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("closedLoopSiteDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ClosedLoopSite.class, siteName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, closedLoopSiteDatas, siteName, ClosedLoopSite.class); } - @RequestMapping(value={"/get_ClosedLoopSiteData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ClosedLoopSiteData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getClosedLoopSiteDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("closedLoopSiteDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, closedLoopSiteDatas, ClosedLoopSite.class); } - @RequestMapping(value={"/cl_dictionary/save_vsclAction"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/cl_dictionary/save_vsclAction"}, method={RequestMethod.POST}) public ModelAndView saveVSCLAction(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()); VSCLAction vSCLAction; String userId = null; if (fromAPI) { - vSCLAction = (VSCLAction)mapper.readValue(root.get(dictionaryFields).toString(), VSCLAction.class); + vSCLAction = mapper.readValue(root.get(dictionaryFields).toString(), VSCLAction.class); userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(vSCLAction.getVsclaction(), vsclaction, VSCLAction.class); - VSCLAction data = (VSCLAction) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - vSCLAction.setId(1); - } else { - vSCLAction.setId(id); - } - - vSCLAction.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - vSCLAction = (VSCLAction)mapper.readValue(root.get("vsclActionDictionaryData").toString(), VSCLAction.class); + vSCLAction = mapper.readValue(root.get("vsclActionDictionaryData").toString(), VSCLAction.class); userId = root.get(userid).textValue(); } - if(vSCLAction.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(vSCLAction.getVsclaction(), vsclaction, VSCLAction.class); - if(!duplicateData.isEmpty()){ + UserInfo userInfo = utils.getUserInfo(userId); + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(vSCLAction.getVsclaction(), vsclaction, VSCLAction.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + VSCLAction data = (VSCLAction) duplicateData.get(0); + 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()))){ duplicateflag = true; + } + } + String responseString = null; + if(!duplicateflag){ + vSCLAction.setUserModifiedBy(userInfo); + if(vSCLAction.getId() == 0){ + vSCLAction.setUserCreatedBy(userInfo); + commonClassDao.save(vSCLAction); }else{ - vSCLAction.setUserCreatedBy(this.getUserInfo(userId)); - vSCLAction.setUserModifiedBy(this.getUserInfo(userId)); vSCLAction.setModifiedDate(new Date()); - commonClassDao.save(vSCLAction); - } - }else{ - if(!isFakeUpdate) { - vSCLAction.setUserModifiedBy(this.getUserInfo(userId)); commonClassDao.update(vSCLAction); - } + } + responseString = mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); + }else{ + responseString = duplicateResponseString; } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; + if(fromAPI){ + return utils.getResultForApi(responseString); }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); - } - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate) { - responseString = "Exists"; - } else { - responseString = successMsg; - } - - } - 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("{vsclActionDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + utils.setResponseData(response, vsclActionDatas, responseString); } - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + }catch(Exception e){ + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_VsclAction"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeVSCLAction(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()); - VSCLAction vSCLAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class); - commonClassDao.delete(vSCLAction); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); - JSONObject j = new JSONObject("{vsclActionDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; + @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={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/cl_dictionary/save_vnfType"}, method={RequestMethod.POST}) public ModelAndView saveVnfType(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()); VNFType vNFType; String userId = null; - if (fromAPI) { - vNFType = (VNFType)mapper.readValue(root.get(dictionaryFields).toString(), VNFType.class); + vNFType = mapper.readValue(root.get(dictionaryFields).toString(), VNFType.class); userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), vnftype, VNFType.class); - VNFType data = (VNFType) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - vNFType.setId(1); - } else { - vNFType.setId(id); - } - vNFType.setUserCreatedBy(this.getUserInfo(userId)); - } } else { - vNFType = (VNFType)mapper.readValue(root.get("vnfTypeDictionaryData").toString(), VNFType.class); + vNFType = mapper.readValue(root.get("vnfTypeDictionaryData").toString(), VNFType.class); userId = root.get(userid).textValue(); } - if(vNFType.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), vnftype, VNFType.class); - if(!duplicateData.isEmpty()){ + UserInfo userInfo = utils.getUserInfo(userId); + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), vnftype, VNFType.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + VNFType data = (VNFType) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - vNFType.setUserCreatedBy(this.getUserInfo(userId)); - vNFType.setUserModifiedBy(this.getUserInfo(userId)); + } + } + String responseString = null; + if(!duplicateflag){ + vNFType.setUserModifiedBy(userInfo); + if(vNFType.getId() == 0){ + vNFType.setUserCreatedBy(userInfo); commonClassDao.save(vNFType); - } - }else{ - if(!isFakeUpdate) { - vNFType.setUserModifiedBy(this.getUserInfo(userId)); + }else{ vNFType.setModifiedDate(new Date()); commonClassDao.update(vNFType); - } - } - String responseString = ""; - if(duplicateflag){ + } + responseString = mapper.writeValueAsString(commonClassDao.getData(VNFType.class)); + }else{ responseString = duplicateResponseString; + } + + if(fromAPI){ + return utils.getResultForApi(responseString); }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(VNFType.class)); - } - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate) { - responseString = "Exists"; - } else { - responseString = successMsg; - } - } - 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("{vnfTypeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + utils.setResponseData(response, vnfTypeDatas, responseString); } - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + }catch(Exception e){ + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_vnfType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeVnfType(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()); - VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class); - commonClassDao.delete(vNFType); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(VNFType.class)); - JSONObject j = new JSONObject("{vnfTypeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; + @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={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/cl_dictionary/save_pepOptions"}, method={RequestMethod.POST}) public ModelAndView savePEPOptions(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()); PEPOptions pEPOptions; GridData gridData; String userId = null; - if (fromAPI) { - pEPOptions = (PEPOptions)mapper.readValue(root.get(dictionaryFields).toString(), PEPOptions.class); - gridData = (GridData)mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); + if(fromAPI){ + pEPOptions = mapper.readValue(root.get(dictionaryFields).toString(), PEPOptions.class); + gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), pepName, PEPOptions.class); - PEPOptions data = (PEPOptions) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - pEPOptions.setId(1); - } else { - pEPOptions.setId(id); - } - pEPOptions.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - pEPOptions = (PEPOptions)mapper.readValue(root.get("pepOptionsDictionaryData").toString(), PEPOptions.class); - gridData = (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(); } - String actions = ""; - int counter = 0; + UserInfo userInfo = utils.getUserInfo(userId); + if(!gridData.getAttributes().isEmpty()){ - for(Object attribute : gridData.getAttributes()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString(); - String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString(); - if(counter>0){ - actions = actions + ":#@"; - } - actions = actions + key + "=#@"; - actions = actions + value; - counter ++; - } - } + pEPOptions.setActions(utils.appendKeyValue(gridData.getAttributes(), ":#@", "=#@")); } - pEPOptions.setActions(actions); - if(pEPOptions.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), pepName, PEPOptions.class); - if(!duplicateData.isEmpty()){ + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), pepName, PEPOptions.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + PEPOptions data = (PEPOptions) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - pEPOptions.setUserCreatedBy(this.getUserInfo(userId)); - pEPOptions.setUserModifiedBy(this.getUserInfo(userId)); + } + } + String responseString = null; + if(!duplicateflag){ + pEPOptions.setUserModifiedBy(userInfo); + if(pEPOptions.getId() == 0){ + pEPOptions.setUserCreatedBy(userInfo); commonClassDao.save(pEPOptions); - } - }else{ - if(!isFakeUpdate){ - pEPOptions.setUserModifiedBy(this.getUserInfo(userId)); + }else{ pEPOptions.setModifiedDate(new Date()); - commonClassDao.update(pEPOptions); - } + commonClassDao.update(pEPOptions); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); + }else{ + responseString = duplicateResponseString; } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); - } - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = successMsg; - } - } - - 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("{pepOptionsDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, pepOptionDatas, responseString); + } + }catch(Exception e){ + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_pepOptions"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePEPOptions(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()); - PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class); - commonClassDao.delete(pEPOptions); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); - JSONObject j = new JSONObject("{pepOptionsDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; + @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={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/cl_dictionary/save_service"}, method={RequestMethod.POST}) public ModelAndView saveServiceType(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()); ClosedLoopD2Services serviceData; String userId = null; - if (fromAPI) { - serviceData = (ClosedLoopD2Services)mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopD2Services.class); + if(fromAPI){ + serviceData = mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopD2Services.class); userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(serviceData.getServiceName(), serviceName, ClosedLoopD2Services.class); - ClosedLoopD2Services data = (ClosedLoopD2Services) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - serviceData.setId(1); - } else { - serviceData.setId(id); - } - serviceData.setUserCreatedBy(this.getUserInfo(userId)); - } } else { - serviceData = (ClosedLoopD2Services)mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(), ClosedLoopD2Services.class); + serviceData = mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(), ClosedLoopD2Services.class); userId = root.get(userid).textValue(); } - if(serviceData.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(serviceData.getServiceName(), serviceName, ClosedLoopD2Services.class); - if(!duplicateData.isEmpty()){ + UserInfo userInfo = utils.getUserInfo(userId); + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(serviceData.getServiceName(), serviceName, ClosedLoopD2Services.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + ClosedLoopD2Services data = (ClosedLoopD2Services) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - serviceData.setUserCreatedBy(this.getUserInfo(userId)); - serviceData.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(serviceData); } - }else{ - if(!isFakeUpdate){ - serviceData.setUserModifiedBy(this.getUserInfo(userId)); + } + String responseString = null; + if(!duplicateflag){ + serviceData.setUserModifiedBy(userInfo); + if(serviceData.getId() == 0){ + serviceData.setUserCreatedBy(userInfo); + commonClassDao.save(serviceData); + }else{ serviceData.setModifiedDate(new Date()); commonClassDao.update(serviceData); - } + } + responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); + }else{ + responseString = duplicateResponseString; } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); - } - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = successMsg; - } - } - 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("{closedLoopServiceDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, closedLoopDatas, responseString); + } + }catch(Exception e){ + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_Service"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeServiceType(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()); - ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); - commonClassDao.delete(closedLoopD2Services); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); - JSONObject j = new JSONObject("{closedLoopServiceDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; + @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={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/cl_dictionary/save_siteName"}, method={RequestMethod.POST}) public ModelAndView saveSiteType(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()); ClosedLoopSite siteData; String userId = null; - if (fromAPI) { - siteData = (ClosedLoopSite)mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopSite.class); + if(fromAPI){ + siteData = mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopSite.class); userId = "API"; - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), siteName, ClosedLoopSite.class); - ClosedLoopSite data = (ClosedLoopSite) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - siteData.setId(1); - } else { - siteData.setId(id); - } - siteData.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - siteData = (ClosedLoopSite)mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), ClosedLoopSite.class); + }else{ + siteData = mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), ClosedLoopSite.class); userId = root.get(userid).textValue(); } - if(siteData.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), siteName, ClosedLoopSite.class); - if(!duplicateData.isEmpty()){ + UserInfo userInfo = utils.getUserInfo(userId); + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), siteName, ClosedLoopSite.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + ClosedLoopSite data = (ClosedLoopSite) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - siteData.setUserCreatedBy(this.getUserInfo(userId)); - siteData.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(siteData); } - }else{ - if(!isFakeUpdate) { - siteData.setUserModifiedBy(this.getUserInfo(userId)); + } + String responseString = null; + if(!duplicateflag){ + siteData.setUserModifiedBy(userInfo); + if(siteData.getId() == 0){ + siteData.setUserCreatedBy(userInfo); + commonClassDao.save(siteData); + }else{ siteData.setModifiedDate(new Date()); - commonClassDao.update(siteData); - } + commonClassDao.update(siteData); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); + }else{ + responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, closedLoopSiteDatas, responseString); } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); - } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = successMsg; - } - } - 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("{closedLoopSiteDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_site"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeSiteType(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()); - ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); - commonClassDao.delete(closedLoopSite); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); - JSONObject j = new JSONObject("{closedLoopSiteDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; + @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={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/cl_dictionary/save_varbind"}, method={RequestMethod.POST}) public ModelAndView saveVarbind(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()); VarbindDictionary varbindDictionary; String userId = null; - if (fromAPI) { - varbindDictionary = (VarbindDictionary)mapper.readValue(root.get(dictionaryFields).toString(), VarbindDictionary.class); + if(fromAPI){ + varbindDictionary = mapper.readValue(root.get(dictionaryFields).toString(), VarbindDictionary.class); userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(varbindDictionary.getVarbindName(), varbindName, VarbindDictionary.class); - VarbindDictionary data = (VarbindDictionary) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - varbindDictionary.setId(1); - } else { - varbindDictionary.setId(id); - } - varbindDictionary.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("varbindDictionaryData").toString(), VarbindDictionary.class); + }else{ + varbindDictionary = mapper.readValue(root.get("varbindDictionaryData").toString(), VarbindDictionary.class); userId = root.get(userid).textValue(); } - if(varbindDictionary.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(varbindDictionary.getVarbindName(), varbindName, VarbindDictionary.class); - if(!duplicateData.isEmpty()){ + UserInfo userInfo = utils.getUserInfo(userId); + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(varbindDictionary.getVarbindName(), varbindName, VarbindDictionary.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + VarbindDictionary data = (VarbindDictionary) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - varbindDictionary.setUserCreatedBy(this.getUserInfo(userId)); - varbindDictionary.setUserModifiedBy(this.getUserInfo(userId)); + } + } + + String responseString = null; + if(!duplicateflag){ + varbindDictionary.setUserModifiedBy(userInfo); + if(varbindDictionary.getId() == 0){ + varbindDictionary.setUserCreatedBy(userInfo); commonClassDao.save(varbindDictionary); - } - }else{ - if(!isFakeUpdate){ - varbindDictionary.setUserModifiedBy(this.getUserInfo(userId)); + }else{ varbindDictionary.setModifiedDate(new Date()); - commonClassDao.update(varbindDictionary); - } + commonClassDao.update(varbindDictionary); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); + }else{ + responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, varbindDatas, responseString); } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); - } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = successMsg; - } - } - 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("{varbindDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_varbindDict"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeVarbind(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()); - VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class); - commonClassDao.delete(varbindDictionary); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); - JSONObject j = new JSONObject("{varbindDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; + @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); } - - public static void setCommonClassDao(CommonClassDaoImpl commonClassDaoImpl) { - commonClassDao = commonClassDaoImpl; - } - -} - +}
\ 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 5792cba81..9b79303fa 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,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,410 +20,213 @@ 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 org.json.JSONObject; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.util.JsonMessage; +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.Datatype; import org.onap.policy.rest.jpa.DecisionSettings; import org.onap.policy.rest.jpa.RainyDayTreatments; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.utils.PolicyUtils; -import org.onap.policy.xacml.api.XACMLErrorConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; @Controller public class DecisionPolicyDictionaryController { - - private static final Logger LOGGER = FlexLogger.getLogger(DecisionPolicyDictionaryController.class); private static CommonClassDao commonClassDao; + private static String xacmlId = "xacmlId"; + private static String bbID = "bbid"; + private static String operation = "operation"; + private static String duplicateResponseString = "Duplicate"; + private static String settingDatas = "settingsDictionaryDatas"; + private static String rainDayDatas = "rainyDayDictionaryDatas"; + private static String dictionaryFields ="dictionaryFields"; @Autowired public DecisionPolicyDictionaryController(CommonClassDao commonClassDao){ DecisionPolicyDictionaryController.commonClassDao = commonClassDao; } - public DecisionPolicyDictionaryController(){} + public DecisionPolicyDictionaryController(){ + super(); + } - public UserInfo getUserInfo(String loginId){ - UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - return name; + private DictionaryUtils getDictionaryUtilsInstance(){ + return DictionaryUtils.dictionaryUtils != null ? DictionaryUtils.getDictionaryUtils() : new DictionaryUtils(); } - @RequestMapping(value={"/get_SettingsDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_SettingsDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("settingsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DecisionSettings.class, "xacmlId"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, settingDatas, xacmlId, DecisionSettings.class); } - @RequestMapping(value={"/get_SettingsDictionaryData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_SettingsDictionaryData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getSettingsDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("settingsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.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(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, settingDatas, DecisionSettings.class); } - @RequestMapping(value={"/decision_dictionary/save_Settings"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException{ + @RequestMapping(value={"/decision_dictionary/save_Settings"}, method={RequestMethod.POST}) + public ModelAndView saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - 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()); DecisionSettings decisionSettings; - String userId = null; - - if (fromAPI) { - decisionSettings = (DecisionSettings)mapper.readValue(root.get("dictionaryFields").toString(), DecisionSettings.class); - userId = "API"; + String userId = null; - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), "xacmlId", DecisionSettings.class); - int id = 0; - DecisionSettings data = (DecisionSettings) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - decisionSettings.setId(1); - } else { - decisionSettings.setId(id); - } - decisionSettings.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - decisionSettings = (DecisionSettings)mapper.readValue(root.get("settingsDictionaryData").toString(), DecisionSettings.class); - userId = root.get("userid").textValue(); - } + if(fromAPI){ + decisionSettings = mapper.readValue(root.get(dictionaryFields).toString(), DecisionSettings.class); + userId = "API"; + }else{ + decisionSettings = mapper.readValue(root.get("settingsDictionaryData").toString(), DecisionSettings.class); + userId = root.get("userid").textValue(); + } + UserInfo userInfo = utils.getUserInfo(userId); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), xacmlId, DecisionSettings.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + DecisionSettings data = (DecisionSettings) duplicateData.get(0); + 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()))){ + duplicateflag = true; + } + } if(decisionSettings.getDatatypeBean().getShortName() != null){ String datatype = decisionSettings.getDatatypeBean().getShortName(); - Datatype a = new Datatype(); - if(datatype.equalsIgnoreCase("string")){ - a.setId(26); - }else if(datatype.equalsIgnoreCase("integer")){ - a.setId(12); - }else if(datatype.equalsIgnoreCase("boolean")){ - a.setId(18); - }else if(datatype.equalsIgnoreCase("double")){ - a.setId(25); - }else if(datatype.equalsIgnoreCase("user")){ - a.setId(29); - } - decisionSettings.setDatatypeBean(a); + decisionSettings.setDatatypeBean(utils.getDataType(datatype)); } - if(decisionSettings.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), "xacmlId", DecisionSettings.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - decisionSettings.setUserCreatedBy(this.getUserInfo(userId)); - decisionSettings.setUserModifiedBy(this.getUserInfo(userId)); + String responseString = null; + if(!duplicateflag){ + decisionSettings.setUserModifiedBy(userInfo); + if(decisionSettings.getId() == 0){ + decisionSettings.setUserCreatedBy(userInfo); commonClassDao.save(decisionSettings); - } - }else{ - if(!isFakeUpdate) { - decisionSettings.setUserModifiedBy(this.getUserInfo(userId)); + }else{ decisionSettings.setModifiedDate(new Date()); commonClassDao.update(decisionSettings); - } + } + responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); + }else{ + responseString = duplicateResponseString; } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); - } - - if (fromAPI) { - if (!"Duplicate".equals(responseString)) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{settingsDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, settingDatas, responseString); + } + }catch (Exception e){ + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/settings_dictionary/remove_settings"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException { - try{ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class); - commonClassDao.delete(decisionSettings); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); - JSONObject j = new JSONObject("{settingsDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; + @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={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_RainyDayDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("rainyDayDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(RainyDayTreatments.class, "bbid"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, rainDayDatas, bbID, RainyDayTreatments.class); } - - @RequestMapping(value={"/get_RainyDayDictionaryData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_RainyDayDictionaryData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getRainyDayDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("rainyDayDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.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(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, rainDayDatas, RainyDayTreatments.class); } - @RequestMapping(value={"/decision_dictionary/save_RainyDay"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException{ + @RequestMapping(value={"/decision_dictionary/save_RainyDay"}, method={RequestMethod.POST}) + public ModelAndView saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - 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()); RainyDayTreatments decisionRainyDay; TreatmentValues treatmentsData = null; - if (fromAPI) { - decisionRainyDay = (RainyDayTreatments)mapper.readValue(root.get("dictionaryFields").toString(), RainyDayTreatments.class); - treatmentsData = (TreatmentValues)mapper.readValue(root.get("dictionaryFields").toString(), TreatmentValues.class); - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(decisionRainyDay.getBbid()+":"+decisionRainyDay.getWorkstep(), "bbid:workstep", RainyDayTreatments.class); - int id = 0; - RainyDayTreatments data = (RainyDayTreatments) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - } else { - decisionRainyDay.setId(id); - } - } - } else { - decisionRainyDay = (RainyDayTreatments)mapper.readValue(root.get("rainyDayDictionaryData").toString(), RainyDayTreatments.class); - treatmentsData = (TreatmentValues)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); } - - String userValue = ""; - int counter = 0; - if(treatmentsData.getUserDataTypeValues().size() > 0){ - for(Object treatment : treatmentsData.getUserDataTypeValues()){ - if(treatment instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) treatment).get("treatment").toString(); - if(counter>0){ - userValue = userValue + ","; - } - userValue = userValue + key ; - counter ++; - } - } - decisionRainyDay.setTreatments(userValue); - } + decisionRainyDay.setTreatments(utils.appendKey(treatmentsData.getUserDataTypeValues(), "treatment", ",")); - if(decisionRainyDay.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(decisionRainyDay.getBbid()+":"+decisionRainyDay.getWorkstep(), "bbid:workstep", RainyDayTreatments.class); - if(!duplicateData.isEmpty()){ + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(decisionRainyDay.getBbid()+":"+decisionRainyDay.getWorkstep(), "bbid:workstep", RainyDayTreatments.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + RainyDayTreatments data = (RainyDayTreatments) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - commonClassDao.save(decisionRainyDay); } - }else{ - if(!isFakeUpdate) { + } + String responseString = null; + if(!duplicateflag){ + if(decisionRainyDay.getId() == 0){ + commonClassDao.save(decisionRainyDay); + }else{ commonClassDao.update(decisionRainyDay); - } + } + responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); + }else{ + responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, rainDayDatas, responseString); } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); - } - - if (fromAPI) { - if (!"Duplicate".equals(responseString)) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{rainyDayDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/decision_dictionary/remove_rainyDay"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException { - try{ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - RainyDayTreatments decisionRainyDay = (RainyDayTreatments)mapper.readValue(root.get("data").toString(), RainyDayTreatments.class); - commonClassDao.delete(decisionRainyDay); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); - JSONObject j = new JSONObject("{rainyDayDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; + @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 { - private ArrayList<Object> userDataTypeValues = new ArrayList<>(); + private List<Object> userDataTypeValues = new ArrayList<>(); - public ArrayList<Object> getUserDataTypeValues() { + public List<Object> getUserDataTypeValues() { return userDataTypeValues; } - public void setUserDataTypeValues(ArrayList<Object> userDataTypeValues) { + public void setUserDataTypeValues(List<Object> userDataTypeValues) { this.userDataTypeValues = userDataTypeValues; } } 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 b38351806..364a4f73a 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 @@ -21,31 +21,22 @@ package org.onap.policy.pap.xacml.rest.controller; import java.io.IOException; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; import java.util.Date; -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.json.JSONObject; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.adapters.GridData; -import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.DescriptiveScope; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.utils.PolicyUtils; -import org.onap.policy.xacml.api.XACMLErrorConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -54,10 +45,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Controller public class DescriptiveDictionaryController { - - private static final Logger LOGGER = FlexLogger.getLogger(DescriptiveDictionaryController.class); private static CommonClassDao commonClassDao; + private static String operation = "operation"; + private static String dScopeName = "descriptiveScopeName"; + private static String descriptiveDatas = "descriptiveScopeDictionaryDatas"; @Autowired public DescriptiveDictionaryController(CommonClassDao commonClassDao){ @@ -69,182 +61,86 @@ public class DescriptiveDictionaryController { } public DescriptiveDictionaryController(){ - //Empty Constructor - } - - public UserInfo getUserInfo(String loginId){ - return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + super(); } - @RequestMapping(value={"/get_DescriptiveScopeByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + private DictionaryUtils getDictionaryUtilsInstance(){ + return DictionaryUtils.dictionaryUtils != null ? DictionaryUtils.getDictionaryUtils() : new DictionaryUtils(); + } + + @RequestMapping(value={"/get_DescriptiveScopeByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getDescriptiveDictionaryByNameEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("descriptiveScopeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DescriptiveScope.class, "descriptiveScopeName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, descriptiveDatas, dScopeName, DescriptiveScope.class); } - @RequestMapping(value={"/get_DescriptiveScope"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_DescriptiveScope"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getDescriptiveDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("descriptiveScopeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.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(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, descriptiveDatas, DescriptiveScope.class); } - @RequestMapping(value={"/descriptive_dictionary/save_descriptive"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response)throws UnsupportedEncodingException, IOException{ + @RequestMapping(value={"/descriptive_dictionary/save_descriptive"}, method={RequestMethod.POST}) + public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response)throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - 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()); - DescriptiveScope descriptiveScope; - GridData data; - String userId = null; - if (fromAPI) { - descriptiveScope = mapper.readValue(root.get("dictionaryFields").toString(), DescriptiveScope.class); - data = mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), "descriptiveScopeName", DescriptiveScope.class); - int id = 0; - DescriptiveScope dbdata = (DescriptiveScope) duplicateData.get(0); - id = dbdata.getId(); - if(id==0){ - isFakeUpdate=true; - descriptiveScope.setId(1); - } else { - descriptiveScope.setId(id); - } - descriptiveScope.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - descriptiveScope = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), DescriptiveScope.class); - data = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), GridData.class); - userId = root.get("userid").textValue(); - } - StringBuilder header = new StringBuilder(); - int counter = 0; - if(!data.getAttributes().isEmpty()){ - for(Object attribute : data.getAttributes()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString(); - String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString(); - if(counter>0){ - header.append("AND"); - } - header.append(key).append(":").append(value); - counter ++; - } - } + DescriptiveScope descriptiveScope; + GridData data; + String userId = null; + 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); + userId = root.get("userid").textValue(); } - descriptiveScope.setSearch(header.toString()); - if(descriptiveScope.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), "descriptiveScopeName", DescriptiveScope.class); - if(!duplicateData.isEmpty()){ + descriptiveScope.setSearch(utils.appendKeyValue(data.getAttributes(), "AND", ":")); + UserInfo userInfo = utils.getUserInfo(userId); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), dScopeName, DescriptiveScope.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + DescriptiveScope data1 = (DescriptiveScope) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - descriptiveScope.setUserCreatedBy(this.getUserInfo(userId)); - descriptiveScope.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(descriptiveScope); } - }else{ - if(!isFakeUpdate){ - descriptiveScope.setUserModifiedBy(this.getUserInfo(userId)); + } + String responseString = null; + if(!duplicateflag){ + descriptiveScope.setUserModifiedBy(userInfo); + if(descriptiveScope.getId() == 0){ + descriptiveScope.setUserCreatedBy(userInfo); + commonClassDao.save(descriptiveScope); + }else{ descriptiveScope.setModifiedDate(new Date()); commonClassDao.update(descriptiveScope); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); + }else{ + responseString = "Duplicate"; + } + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, descriptiveDatas, responseString); + } + }catch (Exception e){ + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/descriptive_dictionary/remove_descriptiveScope"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/descriptive_dictionary/remove_descriptiveScope"}, method={RequestMethod.POST}) public void removeDescriptiveDictionary(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()); - DescriptiveScope descriptiveScope = mapper.readValue(root.get("data").toString(), DescriptiveScope.class); - commonClassDao.delete(descriptiveScope); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); - JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + 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 85e3944fd..7e30635f9 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,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,27 +21,19 @@ package org.onap.policy.pap.xacml.rest.controller; import java.io.IOException; -import java.io.PrintWriter; import java.util.Date; -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; -import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.Attribute; -import org.onap.policy.rest.jpa.Category; -import org.onap.policy.rest.jpa.Datatype; import org.onap.policy.rest.jpa.OnapName; import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.xacml.api.XACMLErrorConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; @@ -60,380 +52,186 @@ public class DictionaryController { private static CommonClassDao commonClassDao; private static String xacmlId = "xacmlId"; - private static String apiflag = "apiflag"; private static String operation = "operation"; private static String dictionaryFields ="dictionaryFields"; private static String duplicateResponseString = "Duplicate"; - private static String utf8 = "UTF-8"; - private static String applicationJsonContentType = "application / json"; private static String onapName = "onapName"; + private static String attributeDatas = "attributeDictionaryDatas"; + private static String onapNameDatas = "onapNameDictionaryDatas"; + @Autowired public DictionaryController(CommonClassDao commonClassDao){ DictionaryController.commonClassDao = commonClassDao; } - /* - * This is an empty constructor - */ - public DictionaryController(){} - - public UserInfo getUserInfo(String loginId){ - return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + + public DictionaryController(){ + super(); } - - public Category getCategory(){ - List<Object> list = commonClassDao.getData(Category.class); - for (int i = 0; i < list.size() ; i++) { - Category value = (Category) list.get(i); - if (("resource").equals(value.getShortName())) { - return value; - } - } - return null; + private DictionaryUtils getDictionaryUtilsInstance(){ + return DictionaryUtils.dictionaryUtils != null ? DictionaryUtils.getDictionaryUtils() : new DictionaryUtils(); } - - @RequestMapping(value={"/get_AttributeDatabyAttributeName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + + @RequestMapping(value={"/get_AttributeDatabyAttributeName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getAttributeDictionaryEntityDatabyAttributeName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("attributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(Attribute.class, xacmlId))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + 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){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("attributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(Attribute.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(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, attributeDatas, Attribute.class); } - @RequestMapping(value={"/attribute_dictionary/save_attribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/attribute_dictionary/save_attribute"}, method={RequestMethod.POST}) public ModelAndView saveAttributeDictionary(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()); - Attribute attributeData = null; - AttributeValues attributeValueData = null; - String userId = null; - if (fromAPI) { - attributeData = (Attribute)mapper.readValue(root.get(dictionaryFields).toString(), Attribute.class); - attributeValueData = (AttributeValues)mapper.readValue(root.get(dictionaryFields).toString(), AttributeValues.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (("update").equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class); - Attribute data = (Attribute) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - attributeData.setId(1); - } else { - attributeData.setId(id); - } - attributeData.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - attributeData = (Attribute)mapper.readValue(root.get("attributeDictionaryData").toString(), Attribute.class); - attributeValueData = (AttributeValues)mapper.readValue(root.get("attributeDictionaryData").toString(), AttributeValues.class); - userId = root.get("userid").textValue(); - } - String userValue = ""; - int counter = 0; - if(!attributeValueData.getUserDataTypeValues().isEmpty()){ - for(Object attribute : attributeValueData.getUserDataTypeValues()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get("attributeValues").toString(); - if(counter>0){ - userValue = userValue + ","; - } - userValue = userValue + key ; - counter ++; - } + 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); + userId = "API"; + }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<Object> duplicateData = commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + Attribute data = (Attribute) duplicateData.get(0); + 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()))){ + duplicateflag = true; } } - attributeData.setAttributeValue(userValue); + if(attributeValueData.getUserDataTypeValues() != null && !attributeValueData.getUserDataTypeValues().isEmpty()){ + attributeData.setAttributeValue(utils.appendKey(attributeValueData.getUserDataTypeValues(), "attributeValues", ",")); + } + if(attributeData.getDatatypeBean().getShortName() != null){ - String datatype = attributeData.getDatatypeBean().getShortName(); - Datatype a = new Datatype(); - if(("string").equalsIgnoreCase(datatype)){ - a.setId(26); - }else if(("integer").equalsIgnoreCase(datatype)){ - a.setId(12); - }else if(("boolean").equalsIgnoreCase(datatype)){ - a.setId(18); - }else if(("double").equalsIgnoreCase(datatype)){ - a.setId(25); - }else if(("user").equalsIgnoreCase(datatype)){ - a.setId(29); - } - attributeData.setDatatypeBean(a); + String datatype = attributeData.getDatatypeBean().getShortName(); + attributeData.setDatatypeBean(utils.getDataType(datatype)); } - if(attributeData.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - attributeData.setCategoryBean(this.getCategory()); - attributeData.setUserCreatedBy(this.getUserInfo(userId)); - attributeData.setUserModifiedBy(this.getUserInfo(userId)); + + String responseString = null; + if(!duplicateflag){ + attributeData.setUserModifiedBy(userInfo); + if(attributeData.getId() == 0){ + attributeData.setCategoryBean(utils.getCategory()); + attributeData.setUserCreatedBy(userInfo); commonClassDao.save(attributeData); - } - }else{ - if(!isFakeUpdate) { - attributeData.setUserModifiedBy(this.getUserInfo(userId)); + }else{ attributeData.setModifiedDate(new Date()); commonClassDao.update(attributeData); - } - } - String responseString = null; - if(duplicateflag) { - responseString = duplicateResponseString; - } else { - responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class)); - } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - 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("{attributeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class)); + }else{ + responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, attributeDatas, responseString); + } + }catch (Exception e){ + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/attribute_dictionary/remove_attribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeAttributeDictionary(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()); - Attribute attributeData = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class); - commonClassDao.delete(attributeData); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class)); - JSONObject j = new JSONObject("{attributeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; + @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={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_OnapNameDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getOnapNameDictionaryByNameEntityData(HttpServletResponse response){ LOGGER.info("get_OnapNameDataByName is called"); - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("onapNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(OnapName.class, onapName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, onapNameDatas, onapName, OnapName.class); } - @RequestMapping(value={"/get_OnapNameData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_OnapNameData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getOnapNameDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("onapNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(OnapName.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(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, onapNameDatas, OnapName.class); } - @RequestMapping(value={"/onap_dictionary/save_onapName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/onap_dictionary/save_onapName"}, method={RequestMethod.POST}) public ModelAndView saveOnapDictionary(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()); OnapName onapData; String userId = null; - if (fromAPI) { - onapData = (OnapName)mapper.readValue(root.get(dictionaryFields).toString(), OnapName.class); + if(fromAPI){ + onapData = mapper.readValue(root.get(dictionaryFields).toString(), OnapName.class); userId = "API"; - - //check if update operation or create, get id for data to be updated - if (("update").equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getOnapName(), onapName, OnapName.class); - OnapName data = (OnapName) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - onapData.setId(1); - } else { - onapData.setId(id); - } - onapData.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - onapData = (OnapName)mapper.readValue(root.get("onapNameDictionaryData").toString(), OnapName.class); + }else{ + onapData = mapper.readValue(root.get("onapNameDictionaryData").toString(), OnapName.class); userId = root.get("userid").textValue(); } - if(onapData.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getOnapName(), onapName, OnapName.class); - if(!duplicateData.isEmpty()){ + UserInfo userInfo = utils.getUserInfo(userId); + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getOnapName(), onapName, OnapName.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + OnapName data = (OnapName) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - onapData.setUserCreatedBy(getUserInfo(userId)); - onapData.setUserModifiedBy(getUserInfo(userId)); - commonClassDao.save(onapData); } - }else{ - if(!isFakeUpdate){ - onapData.setUserModifiedBy(this.getUserInfo(userId)); - onapData.setModifiedDate(new Date()); - commonClassDao.update(onapData); - } - } + } String responseString = null; - if(duplicateflag) { - responseString = duplicateResponseString; - } else { + if(!duplicateflag){ + onapData.setUserModifiedBy(userInfo); + if(onapData.getId() == 0){ + onapData.setUserCreatedBy(userInfo); + commonClassDao.save(onapData); + }else{ + onapData.setModifiedDate(new Date()); + commonClassDao.update(onapData); + } responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); + }else{ + responseString = duplicateResponseString; } - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - 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("{onapNameDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, onapNameDatas, responseString); } }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/onap_dictionary/remove_onap"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeOnapDictionary(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()); - OnapName onapData = (OnapName)mapper.readValue(root.get("data").toString(), OnapName.class); - commonClassDao.delete(onapData); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); - JSONObject j = new JSONObject("{onapNameDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; + @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{ @@ -446,5 +244,4 @@ class AttributeValues{ public void setUserDataTypeValues(List<Object> 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/FirewallDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java index 0466debb8..d02cbca73 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java @@ -24,10 +24,7 @@ import java.io.IOException; import java.io.PrintWriter; import java.net.UnknownHostException; import java.util.Date; -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; @@ -37,7 +34,7 @@ import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.adapters.GridData; -import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ActionList; import org.onap.policy.rest.jpa.AddressGroup; @@ -53,12 +50,11 @@ import org.onap.policy.rest.jpa.ServiceList; import org.onap.policy.rest.jpa.TermList; import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.rest.jpa.Zone; -import org.onap.policy.utils.PolicyUtils; -import org.onap.policy.xacml.api.XACMLErrorConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -73,20 +69,13 @@ public class FirewallDictionaryController { private static CommonClassDao commonClassDao; private static String prefixListName = "prefixListName"; - private static String successMapKey = "successMapKey"; private static String successMessage = "success"; private static String operation = "operation"; - private static String getDictionary = "getDictionary"; private static String errorMsg = "error"; - private static String dictionaryDBQuery = "dictionaryDBQuery"; - private static String apiflag = "apiflag"; private static String dictionaryFields ="dictionaryFields"; - private static String update = "update"; private static String duplicateResponseString = "Duplicate"; - private static String successMsg = "Success"; private static String utf8 = "UTF-8"; private static String applicationJsonContentType = "application / json"; - private static String existsResponseString = "Exists"; private static String protocolName = "protocolName"; private static String groupNameStart = "Group_"; private static String option = "option"; @@ -95,7 +84,19 @@ public class FirewallDictionaryController { private static String termName = "termName"; private static String userid = "userid"; private static String tagPickerName = "tagPickerName"; - private static String fwTagDictionaryDatas = "fwTagDictionaryDatas"; + private static String pfListDatas = "prefixListDictionaryDatas"; + private static String portListDatas = "portListDictionaryDatas"; + private static String protocolListDatas = "protocolListDictionaryDatas"; + private static String addressGroupDatas = "addressGroupDictionaryDatas"; + private static String actionListDatas = "actionListDictionaryDatas"; + private static String serviceGroupDatas = "serviceGroupDictionaryDatas"; + private static String securityZoneDatas = "securityZoneDictionaryDatas"; + private static String serviceListDatas = "serviceListDictionaryDatas"; + private static String zoneDatas = "zoneDictionaryDatas"; + private static String termListDictDatas = "termListDictionaryDatas"; + private static String fwDictListDatas = "fwDictListDictionaryDatas"; + private static String fwTagPickerDatas = "fwTagPickerDictionaryDatas"; + private static String fwTagDatas = "fwTagDictionaryDatas"; @Autowired @@ -108,159 +109,82 @@ public class FirewallDictionaryController { } public FirewallDictionaryController(){ - /* - * This is an empty constructor - */ + super(); } - public UserInfo getUserInfo(String loginId){ - return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + private DictionaryUtils getDictionaryUtilsInstance(){ + return DictionaryUtils.dictionaryUtils != null ? DictionaryUtils.getDictionaryUtils() : new DictionaryUtils(); } - - - @RequestMapping(value={"/get_PrefixListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + + @RequestMapping(value={"/get_PrefixListDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPrefixListDictionaryEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("prefixListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PrefixList.class, prefixListName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, pfListDatas, prefixListName, PrefixList.class); } - @RequestMapping(value={"/get_PrefixListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_PrefixListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPrefixListDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("prefixListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PrefixList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW, e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, pfListDatas, PrefixList.class); } - @RequestMapping(value={"/fw_dictionary/save_prefixList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_prefixList"}, method={RequestMethod.POST}) public ModelAndView savePrefixListDictionary(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()); PrefixList prefixList; if (fromAPI) { prefixList = mapper.readValue(root.get(dictionaryFields).toString(), PrefixList.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (update.equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(prefixList.getPrefixListName(), prefixListName, PrefixList.class); - PrefixList data = (PrefixList) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - prefixList.setId(1); - } else { - prefixList.setId(id); - } - } } else { prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); } - if(prefixList.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(prefixList.getPrefixListName(), prefixListName, PrefixList.class); - if(!duplicateData.isEmpty()){ + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(prefixList.getPrefixListName(), prefixListName, PrefixList.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + PrefixList data = (PrefixList) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ + } + } + String responseString = null; + if(!duplicateflag){ + if(prefixList.getId() == 0){ commonClassDao.save(prefixList); - } - }else{ - if(!isFakeUpdate) { + }else{ commonClassDao.update(prefixList); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ + } responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); + }else{ + responseString = duplicateResponseString; } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - } - 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("{prefixListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, pfListDatas, responseString); } }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW, e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_PrefixList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_PrefixList"}, method={RequestMethod.POST}) public void removePrefixListDictionary(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()); - PrefixList prefixList = mapper.readValue(root.get("data").toString(), PrefixList.class); - commonClassDao.delete(prefixList); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); - JSONObject j = new JSONObject("{prefixListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, pfListDatas, PrefixList.class); } - @RequestMapping(value={"/fw_dictionary/validate_prefixList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @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); @@ -282,626 +206,298 @@ public class FirewallDictionaryController { out.write(j.toString()); } catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } } - @RequestMapping(value={"/get_PortListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_PortListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPortListDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("portListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PortList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, portListDatas, PortList.class); } - @RequestMapping(value={"/fw_dictionary/save_portName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_portName"}, method={RequestMethod.POST}) public ModelAndView savePortListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = false; + boolean fromAPI = utils.isRequestFromAPI(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - PortList portList = mapper.readValue(root.get("portListDictionaryData").toString(), PortList.class); - if(portList.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(portList.getPortName(), "portName", PortList.class); - if(!duplicateData.isEmpty()){ + PortList portList; + if(fromAPI){ + portList = mapper.readValue(root.get(dictionaryFields).toString(), PortList.class); + }else{ + portList = mapper.readValue(root.get("portListDictionaryData").toString(), PortList.class); + } + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(portList.getPortName(), "portName", PortList.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + PortList data = (PortList) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - commonClassDao.save(portList); } + } + String responseString = null; + if(!duplicateflag){ + if(portList.getId() == 0){ + commonClassDao.save(portList); + }else{ + commonClassDao.update(portList); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(PortList.class)); }else{ - commonClassDao.update(portList); - } - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - String responseString = ""; - if(duplicateflag){ responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(PortList.class)); + utils.setResponseData(response, portListDatas, responseString); } - JSONObject j = new JSONObject("{portListDictionaryDatas: " + responseString + "}"); - - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + }catch (Exception e){ + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_PortList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_PortList"}, method={RequestMethod.POST}) public void removePortListDictionary(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()); - PortList portList = mapper.readValue(root.get("data").toString(), PortList.class); - commonClassDao.delete(portList); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(PortList.class)); - JSONObject j = new JSONObject("{portListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, portListDatas, PortList.class); } - @RequestMapping(value={"/get_ProtocolListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ProtocolListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getProtocolListDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("protocolListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, protocolListDatas, ProtocolList.class); } - @RequestMapping(value={"/get_ProtocolListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ProtocolListDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getProtocolListDictionaryEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("protocolListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ProtocolList.class, protocolName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, protocolListDatas, protocolName, ProtocolList.class); } - @RequestMapping(value={"/fw_dictionary/save_protocolList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_protocolList"}, method={RequestMethod.POST}) public ModelAndView saveProtocolListDictionary(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()); ProtocolList protocolList; - if (fromAPI) { + if(fromAPI){ protocolList = mapper.readValue(root.get(dictionaryFields).toString(), ProtocolList.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(protocolList.getProtocolName(), protocolName, ProtocolList.class); - ProtocolList data = (ProtocolList) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - protocolList.setId(1); - } else { - protocolList.setId(id); - } - } - } else { + }else{ protocolList = mapper.readValue(root.get("protocolListDictionaryData").toString(), ProtocolList.class); } - if(protocolList.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(protocolList.getProtocolName(), protocolName, ProtocolList.class); - if(!duplicateData.isEmpty()){ + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(protocolList.getProtocolName(), protocolName, ProtocolList.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + ProtocolList data = (ProtocolList) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - commonClassDao.save(protocolList); } + } + String responseString = null; + if(!duplicateflag){ + if(protocolList.getId() == 0){ + commonClassDao.save(protocolList); + }else{ + commonClassDao.update(protocolList); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); }else{ - if(!isFakeUpdate){ - commonClassDao.update(protocolList); - } - } - String responseString = ""; - if(duplicateflag){ responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - } - 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("{protocolListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, protocolListDatas, responseString); } }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_protocol"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_protocol"}, method={RequestMethod.POST}) public void removeProtocolListDictionary(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()); - ProtocolList protocolList = mapper.readValue(root.get("data").toString(), ProtocolList.class); - commonClassDao.delete(protocolList); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); - JSONObject j = new JSONObject("{protocolListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, protocolListDatas, ProtocolList.class); } - @RequestMapping(value={"/get_AddressGroupDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_AddressGroupDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getAddressGroupDictionaryEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("addressGroupDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(AddressGroup.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, addressGroupDatas, "name", AddressGroup.class); } - @RequestMapping(value={"/get_AddressGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_AddressGroupData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getAddressGroupDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("addressGroupDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, addressGroupDatas, AddressGroup.class); } - @RequestMapping(value={"/fw_dictionary/save_addressGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_addressGroup"}, method={RequestMethod.POST}) public ModelAndView saveAddressGroupDictionary(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()); AddressGroup addressGroup; GridData gridData; - if (fromAPI) { + if(fromAPI){ addressGroup = mapper.readValue(root.get(dictionaryFields).toString(), AddressGroup.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); - - if(!addressGroup.getGroupName().startsWith(groupNameStart)){ - String groupName = groupNameStart+addressGroup.getGroupName(); - addressGroup.setGroupName(groupName); - } - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); - AddressGroup data = (AddressGroup) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - addressGroup.setId(1); - } else { - addressGroup.setId(id); - } - } - } else { + }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(); - addressGroup.setGroupName(groupName); - } } - StringBuilder userValue = new StringBuilder(); - int counter = 0; - if(!gridData.getAttributes().isEmpty()){ - for(Object attribute : gridData.getAttributes()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get(option).toString(); - if(counter>0){ - userValue.append(","); - } - userValue.append(key) ; - counter ++; - } - } + if(!addressGroup.getGroupName().startsWith(groupNameStart)){ + String groupName = groupNameStart+addressGroup.getGroupName(); + addressGroup.setGroupName(groupName); } - addressGroup.setServiceList(userValue.toString()); - if(addressGroup.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); - if(!duplicateData.isEmpty()){ + addressGroup.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + AddressGroup data = (AddressGroup) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - commonClassDao.save(addressGroup); } - }else{ - if (!isFakeUpdate) { + } + String responseString = null; + if(!duplicateflag){ + if(addressGroup.getId() == 0){ + commonClassDao.save(addressGroup); + }else{ commonClassDao.update(addressGroup); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ + } responseString = mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); + }else{ + responseString = duplicateResponseString; } - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - } - 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("{addressGroupDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, addressGroupDatas, responseString); } }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_AddressGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_AddressGroup"}, method={RequestMethod.POST}) public void removeAddressGroupDictionary(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()); - AddressGroup addressGroup = mapper.readValue(root.get("data").toString(), AddressGroup.class); - commonClassDao.delete(addressGroup); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); - JSONObject j = new JSONObject("{addressGroupDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, addressGroupDatas, AddressGroup.class); } - @RequestMapping(value={"/get_ActionListDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ActionListDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getActionListDictionaryEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - List<String> list = commonClassDao.getDataByColumn(ActionList.class, "actionName"); - model.put("actionListDictionaryDatas", mapper.writeValueAsString(list)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, actionListDatas, "actionName", ActionList.class); } - @RequestMapping(value={"/get_ActionListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ActionListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getActionListDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("actionListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ActionList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, actionListDatas, ActionList.class); } - @RequestMapping(value={"/fw_dictionary/save_ActionList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_ActionList"}, method={RequestMethod.POST}) public ModelAndView saveActionListDictionary(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()); ActionList actionList; if (fromAPI) { actionList = mapper.readValue(root.get(dictionaryFields).toString(), ActionList.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionList.getActionName(), "actionName", ActionList.class); - ActionList data = (ActionList) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - actionList.setId(1); - } else { - actionList.setId(id); - } - } } else { actionList = mapper.readValue(root.get("actionListDictionaryData").toString(), ActionList.class); } - if(actionList.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionList.getActionName(), "actionName", ActionList.class); - if(!duplicateData.isEmpty()){ + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionList.getActionName(), "actionName", ActionList.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + ActionList data = (ActionList) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - commonClassDao.save(actionList); } + } + String responseString = null; + if(!duplicateflag){ + if(actionList.getId() == 0){ + commonClassDao.save(actionList); + }else{ + commonClassDao.update(actionList); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); }else{ - if(!isFakeUpdate) { - commonClassDao.update(actionList); - } - } - String responseString = ""; - if(duplicateflag){ responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - } - 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("{actionListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, actionListDatas, responseString); } }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_ActionList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_ActionList"}, method={RequestMethod.POST}) public void removeActionListDictionary(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()); - ActionList actionList = mapper.readValue(root.get("data").toString(), ActionList.class); - commonClassDao.delete(actionList); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); - JSONObject j = new JSONObject("{actionListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, actionListDatas, ActionList.class); } - @RequestMapping(value={"/get_ServiceGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ServiceGroupData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getServiceGroupDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("serviceGroupDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, serviceGroupDatas, GroupServiceList.class); } - @RequestMapping(value={"/get_ServiceGroupDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ServiceGroupDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getServiceGroupDictionaryEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("serviceGroupDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(GroupServiceList.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, serviceGroupDatas, "name", GroupServiceList.class); } - @RequestMapping(value={"/fw_dictionary/save_serviceGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_serviceGroup"}, method={RequestMethod.POST}) public ModelAndView saveServiceGroupDictionary(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()); GroupServiceList groupServiceList; GridData gridData; - if (fromAPI) { + if(fromAPI){ groupServiceList = mapper.readValue(root.get(dictionaryFields).toString(), GroupServiceList.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); - - if(!groupServiceList.getGroupName().startsWith(groupNameStart)){ - String groupName = groupNameStart+groupServiceList.getGroupName(); - groupServiceList.setGroupName(groupName); - } - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(groupServiceList.getGroupName(), "name", GroupServiceList.class); - GroupServiceList data = (GroupServiceList) duplicateData.get(0); - int id = data.getId(); - - if(id==0){ - isFakeUpdate=true; - groupServiceList.setId(1); - } else { - groupServiceList.setId(id); - } - } - } else { + }else{ groupServiceList = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class); gridData = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GridData.class); } @@ -909,1272 +505,563 @@ public class FirewallDictionaryController { String groupName = groupNameStart+groupServiceList.getGroupName(); groupServiceList.setGroupName(groupName); } - StringBuilder userValue = new StringBuilder(); - int counter = 0; - if(!gridData.getAttributes().isEmpty()){ - for(Object attribute : gridData.getAttributes()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get(option).toString(); - if(counter>0){ - userValue.append(","); - } - userValue.append(key); - counter ++; - } + groupServiceList.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(groupServiceList.getGroupName(), "name", GroupServiceList.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + GroupServiceList data = (GroupServiceList) duplicateData.get(0); + 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()))){ + duplicateflag = true; } } - groupServiceList.setServiceList(userValue.toString()); - if(groupServiceList.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(groupServiceList.getGroupName(), "name", GroupServiceList.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ + String responseString = null; + if(!duplicateflag){ + if(groupServiceList.getId() == 0){ commonClassDao.save(groupServiceList); - } - }else{ - if(!isFakeUpdate) { + }else{ commonClassDao.update(groupServiceList); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ + } responseString = mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); + }else{ + responseString = duplicateResponseString; } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - } - 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("{serviceGroupDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, serviceGroupDatas, responseString); } }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_serviceGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_serviceGroup"}, method={RequestMethod.POST}) public void removeServiceGroupDictionary(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()); - GroupServiceList groupServiceList = mapper.readValue(root.get("data").toString(), GroupServiceList.class); - commonClassDao.delete(groupServiceList); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); - JSONObject j = new JSONObject("{serviceGroupDictionaryDatas: " + 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, serviceGroupDatas, GroupServiceList.class); } - @RequestMapping(value={"/get_SecurityZoneDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_SecurityZoneDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getSecurityZoneDictionaryEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("securityZoneDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(SecurityZone.class, zoneName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, securityZoneDatas, zoneName, SecurityZone.class); } - @RequestMapping(value={"/get_SecurityZoneData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_SecurityZoneData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getSecurityZoneDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("securityZoneDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, securityZoneDatas, SecurityZone.class); } - @RequestMapping(value={"/fw_dictionary/save_securityZone"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_securityZone"}, method={RequestMethod.POST}) public ModelAndView saveSecurityZoneDictionary(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()); SecurityZone securityZone; - if (fromAPI) { + if(fromAPI){ securityZone = mapper.readValue(root.get(dictionaryFields).toString(), SecurityZone.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class); - SecurityZone data = (SecurityZone) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - securityZone.setId(1); - } else { - securityZone.setId(id); - } - } - } else { + }else{ securityZone = mapper.readValue(root.get("securityZoneDictionaryData").toString(), SecurityZone.class); } - if(securityZone.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class); - if(!duplicateData.isEmpty()){ + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + SecurityZone data = (SecurityZone) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ + } + } + String responseString = null; + if(!duplicateflag){ + if(securityZone.getId() == 0){ commonClassDao.save(securityZone); - } - }else{ - if(!isFakeUpdate) { + }else{ commonClassDao.update(securityZone); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ + } responseString = mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); + }else{ + responseString = duplicateResponseString; } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - } - 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("{securityZoneDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, securityZoneDatas, responseString); } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_securityZone"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_securityZone"}, method={RequestMethod.POST}) public void removeSecurityZoneDictionary(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()); - SecurityZone securityZone = mapper.readValue(root.get("data").toString(), SecurityZone.class); - commonClassDao.delete(securityZone); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); - JSONObject j = new JSONObject("{securityZoneDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, securityZoneDatas, SecurityZone.class); } - @RequestMapping(value={"/get_ServiceListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ServiceListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getServiceListDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("serviceListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ServiceList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, serviceListDatas, ServiceList.class); } - @RequestMapping(value={"/get_ServiceListDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ServiceListDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getServiceListDictionaryEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("serviceListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ServiceList.class, serviceName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, serviceListDatas, serviceName, ServiceList.class); } - @RequestMapping(value={"/fw_dictionary/save_serviceList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_serviceList"}, method={RequestMethod.POST}) public ModelAndView saveServiceListDictionary(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()); ServiceList serviceList; GridData serviceListGridData; - if (fromAPI) { + if(fromAPI){ serviceList = mapper.readValue(root.get(dictionaryFields).toString(), ServiceList.class); serviceListGridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(serviceList.getServiceName(), serviceName, ServiceList.class); - ServiceList data = (ServiceList) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - serviceList.setId(1); - } else { - serviceList.setId(id); - } - } }else{ serviceList = mapper.readValue(root.get("serviceListDictionaryData").toString(), ServiceList.class); serviceListGridData = mapper.readValue(root.get("serviceListDictionaryData").toString(), GridData.class); } - StringBuilder tcpValue = new StringBuilder(); - int counter = 0; - if(!serviceListGridData.getTransportProtocols().isEmpty()){ - for(Object attribute : serviceListGridData.getTransportProtocols()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get(option).toString(); - if(counter>0){ - tcpValue.append(","); - } - tcpValue.append(key); - counter ++; - } - } - } - serviceList.setServiceTransProtocol(tcpValue.toString()); - StringBuilder appValue = new StringBuilder(); - int counter1 = 0; - if(!serviceListGridData.getAppProtocols().isEmpty()){ - for(Object attribute : serviceListGridData.getAppProtocols()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get(option).toString(); - if(counter1>0){ - appValue.append(","); - } - appValue.append(key); - counter1 ++; - } - } - } - serviceList.setServiceAppProtocol(appValue.toString()); + serviceList.setServiceTransProtocol(utils.appendKey(serviceListGridData.getTransportProtocols(), option, ",")); + serviceList.setServiceAppProtocol(utils.appendKey(serviceListGridData.getAppProtocols(), option, ",")); serviceList.setServiceType("SERVICE"); - if(serviceList.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(serviceList.getServiceName(), serviceName, ServiceList.class); - if(!duplicateData.isEmpty()){ + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(serviceList.getServiceName(), serviceName, ServiceList.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + ServiceList data = (ServiceList) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - commonClassDao.save(serviceList); } - }else{ - if(!isFakeUpdate) { + } + String responseString = null; + if(!duplicateflag){ + if(serviceList.getId() == 0){ + commonClassDao.save(serviceList); + }else{ commonClassDao.update(serviceList); - } - } - - String responseString = ""; - if(duplicateflag){ + } + responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); + }else{ responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); - } - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - } - 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("{serviceListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + utils.setResponseData(response, serviceListDatas, responseString); } }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_serviceList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_serviceList"}, method={RequestMethod.POST}) public void removeServiceListDictionary(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()); - ServiceList serviceList = mapper.readValue(root.get("data").toString(), ServiceList.class); - commonClassDao.delete(serviceList); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); - JSONObject j = new JSONObject("{serviceListDictionaryDatas: " + 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, serviceListDatas, ServiceList.class); } - @RequestMapping(value={"/get_ZoneData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ZoneData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getZoneDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("zoneDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(Zone.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, zoneDatas, Zone.class); } - @RequestMapping(value={"/get_ZoneDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_ZoneDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getZoneDictionaryEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("zoneDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(Zone.class, zoneName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, zoneDatas, zoneName, PrefixList.class); } - @RequestMapping(value={"/fw_dictionary/save_zoneName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_zoneName"}, method={RequestMethod.POST}) public ModelAndView saveZoneDictionary(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()); Zone zone; if (fromAPI) { zone = mapper.readValue(root.get(dictionaryFields).toString(), Zone.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class); - Zone data = (Zone) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - zone.setId(1); - } else { - zone.setId(id); - } - } } else { zone = mapper.readValue(root.get("zoneDictionaryData").toString(), Zone.class); } - if(zone.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class); - if(!duplicateData.isEmpty()){ + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + Zone data = (Zone) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ + } + } + String responseString = null; + if(!duplicateflag){ + if(zone.getId() == 0){ commonClassDao.save(zone); - } - }else{ - if(!isFakeUpdate) { + }else{ commonClassDao.update(zone); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ + } responseString = mapper.writeValueAsString(commonClassDao.getData(Zone.class)); + }else{ + responseString = duplicateResponseString; } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - } - 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("{zoneDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, zoneDatas, responseString); } }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_zone"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_zone"}, method={RequestMethod.POST}) public void removeZoneDictionary(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()); - Zone zone = mapper.readValue(root.get("data").toString(), Zone.class); - commonClassDao.delete(zone); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(Zone.class)); - JSONObject j = new JSONObject("{zoneDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, zoneDatas, Zone.class); } - @RequestMapping(value={"/get_TermListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_TermListDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getTermListDictionaryEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("termListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(TermList.class, termName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, termListDictDatas, termName, TermList.class); } - @RequestMapping(value={"/get_TermListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_TermListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getTermListDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("termListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(TermList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, termListDictDatas, TermList.class); } - @RequestMapping(value={"/fw_dictionary/save_termList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_termList"}, method={RequestMethod.POST}) public ModelAndView saveTermListDictionary(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()); 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); userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), termName, TermList.class); - TermList data = (TermList) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - termList.setId(1); - } else { - termList.setId(id); - } - termList.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { + }else{ termList = mapper.readValue(root.get("termListDictionaryData").toString(), TermList.class); termListDatas = mapper.readValue(root.get("termListDictionaryData").toString(), TermListData.class); userId = root.get(userid).textValue(); } - StringBuilder fromZoneValue = new StringBuilder(); - int counter = 0; - if(!termListDatas.getFromZoneDatas().isEmpty()){ - for(Object fromZone : termListDatas.getFromZoneDatas()){ - if(fromZone instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) fromZone).get(option).toString(); - if(counter>0){ - fromZoneValue.append(","); - } - fromZoneValue.append(key); - counter ++; - } - } - } - termList.setFromZones(fromZoneValue.toString()); - - StringBuilder toZoneValue = new StringBuilder(); - int toZonecounter = 0; - if(!termListDatas.getToZoneDatas().isEmpty()){ - for(Object toZone : termListDatas.getToZoneDatas()){ - if(toZone instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) toZone).get(option).toString(); - if(toZonecounter>0){ - toZoneValue.append(","); - } - toZoneValue.append(key); - toZonecounter ++; - } - } - } - termList.setToZones(toZoneValue.toString()); - - StringBuilder srcListValues = new StringBuilder(); - int srcListcounter = 0; - if(!termListDatas.getSourceListDatas().isEmpty()){ - for(Object srcList : termListDatas.getSourceListDatas()){ - if(srcList instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) srcList).get(option).toString(); - if(srcListcounter>0){ - srcListValues.append(","); - } - srcListValues.append(key); - srcListcounter ++; - } - } - } - termList.setSrcIPList(srcListValues.toString()); - - StringBuilder desListValues = new StringBuilder(); - int destListcounter = 0; - if(!termListDatas.getDestinationListDatas().isEmpty()){ - for(Object desList : termListDatas.getDestinationListDatas()){ - if(desList instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) desList).get(option).toString(); - if(destListcounter>0){ - desListValues.append(","); - } - desListValues.append(key); - destListcounter ++; - } - } - } - termList.setDestIPList(desListValues.toString()); - - StringBuilder srcSerValue = new StringBuilder(); - int srcSercounter = 0; - if(!termListDatas.getSourceServiceDatas().isEmpty()){ - for(Object srcSrc : termListDatas.getSourceServiceDatas()){ - if(srcSrc instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) srcSrc).get(option).toString(); - if(srcSercounter>0){ - srcSerValue.append(","); - } - srcSerValue.append(key); - srcSercounter ++; - } - } - } - termList.setSrcPortList(srcSerValue.toString()); - - StringBuilder desSrcValue = new StringBuilder(); - int desSrccounter = 0; - if(!termListDatas.getDestinationServiceDatas().isEmpty()){ - for(Object desSrc : termListDatas.getDestinationServiceDatas()){ - if(desSrc instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) desSrc).get(option).toString(); - if(desSrccounter>0){ - desSrcValue.append(","); - } - desSrcValue.append(key); - desSrccounter ++; - } - } - } - termList.setDestPortList(desSrcValue.toString()); - - StringBuilder actionValue = new StringBuilder(); - int actioncounter = 0; - if(!termListDatas.getActionListDatas().isEmpty()){ - for(Object actionList : termListDatas.getActionListDatas()){ - if(actionList instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) actionList).get(option).toString(); - if(actioncounter>0){ - actionValue.append(","); - } - actionValue.append(key); - actioncounter ++; - } + + 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.setAction(utils.appendKey(termListDatas.getActionListDatas(), option, ",")); + + UserInfo userInfo = utils.getUserInfo(userId); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), termName, TermList.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + TermList data = (TermList) duplicateData.get(0); + 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()))){ + duplicateflag = true; } } - termList.setAction(actionValue.toString()); - - if(termList.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), termName, TermList.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - termList.setUserCreatedBy(this.getUserInfo(userId)); - termList.setUserModifiedBy(this.getUserInfo(userId)); - termList.setCreatedDate(new Date()); + String responseString = null; + if(!duplicateflag){ + termList.setUserModifiedBy(userInfo); + if(termList.getId() == 0){ + termList.setUserCreatedBy(userInfo); commonClassDao.save(termList); - } - }else{ - if(!isFakeUpdate) { - termList.setUserModifiedBy(this.getUserInfo(userId)); + }else{ termList.setModifiedDate(new Date()); commonClassDao.update(termList); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ + } responseString = mapper.writeValueAsString(commonClassDao.getData(TermList.class)); + }else{ + responseString = duplicateResponseString; } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - } - 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("{termListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, termListDictDatas, responseString); } }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_termList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_termList"}, method={RequestMethod.POST}) public void removeTermListDictionary(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()); - TermList termList = mapper.readValue(root.get("data").toString(), TermList.class); - commonClassDao.delete(termList); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(TermList.class)); - JSONObject j = new JSONObject("{termListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, termListDictDatas, TermList.class); } + //ParentList Dictionary Data - @RequestMapping(value={"/get_FWDictionaryListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_FWDictionaryListDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getFWDictListDictionaryEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("fwDictListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FirewallDictionaryList.class, "parentItemName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, fwDictListDatas, "parentItemName", FirewallDictionaryList.class); } - @RequestMapping(value={"/get_FWDictionaryListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_FWDictionaryListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getFWDictionaryListEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("fwDictListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, fwDictListDatas, FirewallDictionaryList.class); } - @RequestMapping(value={"/fw_dictionary/save_FWDictionaryList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_FWDictionaryList"}, method={RequestMethod.POST}) public ModelAndView saveFWDictionaryList(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = false; + boolean fromAPI = utils.isRequestFromAPI(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - FirewallDictionaryList fwDictList = mapper.readValue(root.get("fwDictListDictionaryData").toString(), FirewallDictionaryList.class); - GridData gridData = mapper.readValue(root.get("fwDictListDictionaryData").toString(), GridData.class); - StringBuilder userSLValue = new StringBuilder(); - int slcounter = 0; - if(!gridData.getAttributes().isEmpty()){ - for(Object attribute : gridData.getAttributes()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get(option).toString(); - if(slcounter>0){ - userSLValue.append(","); - } - userSLValue.append(key); - slcounter ++; - } - } + FirewallDictionaryList fwDictList; + GridData gridData; + if (fromAPI) { + 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.setServiceList(userSLValue.toString()); - StringBuilder userALValue = new StringBuilder(); - int alcounter = 0; - if(!gridData.getAlAttributes().isEmpty()){ - for(Object attribute : gridData.getAlAttributes()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get(option).toString(); - if(alcounter>0){ - userALValue.append(","); - } - userALValue.append(key); - alcounter ++; - } + + fwDictList.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); + fwDictList.setAddressList(utils.appendKey(gridData.getAlAttributes(), option, ",")); + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwDictList.getParentItemName(), "parentItemName", FirewallDictionaryList.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + FirewallDictionaryList data = (FirewallDictionaryList) duplicateData.get(0); + 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()))){ + duplicateflag = true; } } - fwDictList.setAddressList(userALValue.toString()); - if(fwDictList.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwDictList.getParentItemName(), "parentItemName", FirewallDictionaryList.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ + String responseString = null; + if(!duplicateflag){ + if(fwDictList.getId() == 0){ commonClassDao.save(fwDictList); - } + }else{ + commonClassDao.update(fwDictList); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); }else{ - commonClassDao.update(fwDictList); - } - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - String responseString = ""; - if(duplicateflag){ responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); + utils.setResponseData(response, fwDictListDatas, responseString); } - JSONObject j = new JSONObject("{fwDictListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; } catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_FWDictionaryList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_FWDictionaryList"}, method={RequestMethod.POST}) public void removeFWDictionaryList(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()); - FirewallDictionaryList fwDictList = mapper.readValue(root.get("data").toString(), FirewallDictionaryList.class); - commonClassDao.delete(fwDictList); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); - JSONObject j = new JSONObject("{fwDictListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, fwDictListDatas, FirewallDictionaryList.class); } - @RequestMapping(value={"/get_TagPickerNameByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_TagPickerNameByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getTagPickerNameEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("fwTagPickerDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FWTagPicker.class, tagPickerName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, fwTagPickerDatas, tagPickerName, FWTagPicker.class); } - @RequestMapping(value={"/get_TagPickerListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_TagPickerListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getTagPickerDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("fwTagPickerDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, fwTagPickerDatas, FWTagPicker.class); } - @RequestMapping(value={"/fw_dictionary/save_fwTagPicker"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_fwTagPicker"}, method={RequestMethod.POST}) public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = 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()); FWTagPicker fwTagPicker; - + TagGridValues data; String userId = ""; if (fromAPI) { fwTagPicker = mapper.readValue(root.get(dictionaryFields).toString(), FWTagPicker.class); + data = mapper.readValue(root.get(dictionaryFields).toString(), TagGridValues.class); userId = "API"; - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTagPicker.getTagPickerName(), tagPickerName, FWTagPicker.class); - int id = 0; - FWTagPicker dbdata = (FWTagPicker) duplicateData.get(0); - id = dbdata.getId(); - fwTagPicker.setId(id); - fwTagPicker.setUserCreatedBy(this.getUserInfo(userId)); - } } else { - TagGridValues data; fwTagPicker = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), FWTagPicker.class); data = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), TagGridValues.class); userId = root.get(userid).textValue(); - - StringBuilder header = new StringBuilder(); - int counter = 0; - if(!data.getTags().isEmpty()){ - for(Object attribute : data.getTags()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString(); - String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString(); - if(counter>0){ - header.append("#"); - } - header.append(key+":"+value); - counter ++; - } - } - } - fwTagPicker.setTagValues(header.toString()); } + fwTagPicker.setTagValues(utils.appendKeyValue(data.getTags(), "#", ":")); + + UserInfo userInfo = utils.getUserInfo(userId); - if(fwTagPicker.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTagPicker.getTagPickerName(), tagPickerName, FWTagPicker.class); - if(!duplicateData.isEmpty()){ + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTagPicker.getTagPickerName(), tagPickerName, FWTagPicker.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + FWTagPicker data1 = (FWTagPicker) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - fwTagPicker.setUserCreatedBy(this.getUserInfo(userId)); - fwTagPicker.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(fwTagPicker); } + } + String responseString = null; + if(!duplicateflag){ + fwTagPicker.setUserModifiedBy(userInfo); + if(fwTagPicker.getId() == 0){ + fwTagPicker.setUserCreatedBy(userInfo); + commonClassDao.save(fwTagPicker); + }else{ + fwTagPicker.setModifiedDate(new Date()); + commonClassDao.update(fwTagPicker); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); }else{ - fwTagPicker.setUserModifiedBy(this.getUserInfo(userId)); - fwTagPicker.setModifiedDate(new Date()); - commonClassDao.update(fwTagPicker); - } - String responseString = ""; - if(duplicateflag){ responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - responseString = successMsg; - } - 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("{fwTagPickerDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, fwTagPickerDatas, responseString); } } catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_tagPicker"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_tagPicker"}, method={RequestMethod.POST}) public void removeFirewallTagPickerDictionary(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()); - FWTagPicker fwTagPicker = mapper.readValue(root.get("data").toString(), FWTagPicker.class); - commonClassDao.delete(fwTagPicker); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); - JSONObject j = new JSONObject("{fwTagPickerDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, fwTagPickerDatas, FWTagPicker.class); } - @RequestMapping(value={"/get_TagListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_TagListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getTagDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put(fwTagDictionaryDatas, mapper.writeValueAsString(commonClassDao.getData(FWTag.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, fwTagDatas, FWTag.class); } - @RequestMapping(value={"/get_TagNameByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_TagNameByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getTagNameEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("fwTagDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FWTag.class, "fwTagName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, fwTagDatas, "fwTagName", FWTag.class); } - @RequestMapping(value={"/fw_dictionary/save_fwTag"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/save_fwTag"}, method={RequestMethod.POST}) public ModelAndView saveFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = 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()); FWTag fwTag; - + TagGridValues tagGridValues; String userId=""; - if (fromAPI) { + if(fromAPI){ fwTag = mapper.readValue(root.get(dictionaryFields).toString(), FWTag.class); + tagGridValues = mapper.readValue(root.get(dictionaryFields).toString(), TagGridValues.class); userId = "API"; - //check if update operation or create, get id for data to be updated and update attributeData - if (update.equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), "fwTagName", FWTag.class); - int id = 0; - FWTag data = (FWTag) duplicateData.get(0); - id = data.getId(); - fwTag.setId(id); - fwTag.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - TagGridValues tagGridValues; + }else{ fwTag = mapper.readValue(root.get("fwTagDictionaryData").toString(), FWTag.class); tagGridValues = mapper.readValue(root.get("fwTagDictionaryData").toString(), TagGridValues.class); userId = root.get(userid).textValue(); - - StringBuilder userValue = new StringBuilder(); - int counter = 0; - if(!tagGridValues.getTags().isEmpty()){ - for(Object attribute : tagGridValues.getTags()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get("tags").toString(); - if(counter>0){ - userValue.append(","); - } - userValue.append(key); - counter ++; - } - } - } - fwTag.setTagValues(userValue.toString()); } + fwTag.setTagValues(utils.appendKey(tagGridValues.getTags(), "tags", ",")); - if(fwTag.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), "fwTagName", FWTag.class); - if(!duplicateData.isEmpty()){ + UserInfo userInfo = utils.getUserInfo(userId); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), "fwTagName", FWTag.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + FWTag data = (FWTag) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - fwTag.setUserCreatedBy(this.getUserInfo(userId)); - fwTag.setUserModifiedBy(this.getUserInfo(userId)); + } + } + String responseString = null; + if(!duplicateflag){ + fwTag.setUserModifiedBy(userInfo); + if(fwTag.getId() == 0){ + fwTag.setUserCreatedBy(userInfo); commonClassDao.save(fwTag); - } - }else{ - fwTag.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.update(fwTag); - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ + }else{ + fwTag.setModifiedDate(new Date()); + commonClassDao.update(fwTag); + } responseString = mapper.writeValueAsString(commonClassDao.getData(FWTag.class)); + }else{ + responseString = duplicateResponseString; } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - responseString = successMsg; - } - 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("{fwTagDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, fwTagDatas, responseString); } } catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_tagList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/fw_dictionary/remove_tagList"}, method={RequestMethod.POST}) public void removeFirewallTagDictionary(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()); - FWTag fwTag = mapper.readValue(root.get("data").toString(), FWTag.class); - commonClassDao.delete(fwTag); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(FWTag.class)); - JSONObject j = new JSONObject("{fwTagDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, fwTagDatas, FWTag.class); } } @@ -2252,4 +1139,4 @@ class TermListData{ public void setActionListDatas(List<Object> 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/MicroServiceDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java index ff62080e2..20e75a08b 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java @@ -21,7 +21,6 @@ package org.onap.policy.pap.xacml.rest.controller; import java.io.IOException; -import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -37,6 +36,7 @@ import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.pap.xacml.rest.util.JsonMessage; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.DCAEuuid; @@ -44,14 +44,15 @@ import org.onap.policy.rest.jpa.MicroServiceAttribute; import org.onap.policy.rest.jpa.MicroServiceConfigName; import org.onap.policy.rest.jpa.MicroServiceLocation; import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.PrefixList; import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.rest.util.MSAttributeObject; import org.onap.policy.rest.util.MSModelUtils; -import org.onap.policy.utils.PolicyUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -73,25 +74,27 @@ public class MicroServiceDictionaryController { private static String dictionaryDBQuery = "dictionaryDBQuery"; private HashMap<String,MSAttributeObject > classMap; private List<String> modelList = new ArrayList<>(); - private static String apiflag = "apiflag"; private static String dictionaryFields ="dictionaryFields"; - private static String update = "update"; private static String duplicateResponseString = "Duplicate"; - private static String successMessage = "Success"; - private static String utf8 = "UTF-8"; - private static String applicationJsonContentType = "application / json"; - private static String existsResponseString = "Exists"; private static String microServiceModelsDictionaryDatas = "microServiceModelsDictionaryDatas"; private static String modelName = "modelName"; private static String microServiceModelsDictionaryData = "microServiceModelsDictionaryData"; private static String description = "description"; private static String version = "version"; private static String classMapData = "classMap"; - /* - * This is an empty constructor - */ - public MicroServiceDictionaryController(){} + private static String dcaeUUIDDatas = "dcaeUUIDDictionaryDatas"; + private static String microServiceConfigNameDatas = "microServiceConfigNameDictionaryDatas"; + private static String microServiceLocationDatas = "microServiceLocationDictionaryDatas"; + private static String microServiceAttributeDatas = "microServiceAttributeDictionaryDatas"; + + public MicroServiceDictionaryController(){ + super(); + } + private DictionaryUtils getDictionaryUtilsInstance(){ + return DictionaryUtils.dictionaryUtils != null ? DictionaryUtils.getDictionaryUtils() : new DictionaryUtils(); + } + @Autowired public MicroServiceDictionaryController(CommonClassDao commonClassDao){ MicroServiceDictionaryController.commonClassDao = commonClassDao; @@ -99,618 +102,288 @@ public class MicroServiceDictionaryController { public static void setCommonClassDao(CommonClassDao commonClassDao) { MicroServiceDictionaryController.commonClassDao = commonClassDao; } - - public UserInfo getUserInfo(String loginId){ - return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - } MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); - private MicroServiceModels newModel; + private MicroServiceModels newModel; - @RequestMapping(value={"/get_DCAEUUIDDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_DCAEUUIDDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getDCAEUUIDDictionaryByNameEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("dcaeUUIDDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DCAEuuid.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, dcaeUUIDDatas, "name", DCAEuuid.class); } - @RequestMapping(value={"/get_DCAEUUIDData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_DCAEUUIDData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getDCAEUUIDDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("dcaeUUIDDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMsg); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, dcaeUUIDDatas, DCAEuuid.class); } - @RequestMapping(value={"/ms_dictionary/save_dcaeUUID"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/ms_dictionary/save_dcaeUUID"}, method={RequestMethod.POST}) public ModelAndView saveDCAEUUIDDictionary(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()); DCAEuuid dCAEuuid; - if (fromAPI) { - dCAEuuid = (DCAEuuid)mapper.readValue(root.get(dictionaryFields).toString(), DCAEuuid.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DCAEuuid.class); - DCAEuuid data = (DCAEuuid) duplicateData.get(0); - int id = data.getId(); - if(id==0){ - isFakeUpdate=true; - dCAEuuid.setId(1); - } else { - dCAEuuid.setId(id); - } - } - } else { - dCAEuuid = (DCAEuuid)mapper.readValue(root.get("dcaeUUIDDictionaryData").toString(), DCAEuuid.class); + if(fromAPI){ + dCAEuuid = mapper.readValue(root.get(dictionaryFields).toString(), DCAEuuid.class); + }else{ + dCAEuuid = mapper.readValue(root.get("dcaeUUIDDictionaryData").toString(), DCAEuuid.class); } - if(dCAEuuid.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DCAEuuid.class); - if(!duplicateData.isEmpty()){ + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DCAEuuid.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + DCAEuuid data = (DCAEuuid) duplicateData.get(0); + if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + dCAEuuid.setId(data.getId()); + }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || + (request.getParameter(operation) == null && (data.getId() != dCAEuuid.getId()))){ duplicateflag = true; - }else{ - commonClassDao.save(dCAEuuid); } - }else{ - if(!isFakeUpdate) { + } + String responseString = null; + if(!duplicateflag){ + if(dCAEuuid.getId() == 0){ + commonClassDao.save(dCAEuuid); + }else{ commonClassDao.update(dCAEuuid); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class)); - } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMessage; - } - } - 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("{dcaeUUIDDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } + } + responseString = mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class)); + }else{ + responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, dcaeUUIDDatas, responseString); + } }catch (Exception e){ - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - LOGGER.error(e); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ms_dictionary/remove_dcaeuuid"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeDCAEUUIDDictionary(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()); - DCAEuuid dCAEuuid = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class); - commonClassDao.delete(dCAEuuid); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class)); - JSONObject j = new JSONObject("{dcaeUUIDDictionaryDatas: " + 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; + @RequestMapping(value={"/ms_dictionary/remove_dcaeuuid"}, method={RequestMethod.POST}) + public void removeDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, dcaeUUIDDatas, DCAEuuid.class); } - - @RequestMapping(value={"/get_MicroServiceConfigNameDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_MicroServiceConfigNameDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceConfigNameByNameDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceCongigNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(MicroServiceConfigName.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, microServiceConfigNameDatas, "name", MicroServiceConfigName.class); } - - - @RequestMapping(value={"/get_MicroServiceConfigNameData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_MicroServiceConfigNameData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceConfigNameDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceCongigNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(MicroServiceConfigName.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMsg); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, microServiceConfigNameDatas, MicroServiceConfigName.class); } - @RequestMapping(value={"/ms_dictionary/save_configName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/ms_dictionary/save_configName"}, method={RequestMethod.POST}) public ModelAndView saveMicroServiceConfigNameDictionary(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()); MicroServiceConfigName microServiceConfigName; - if (fromAPI) { - microServiceConfigName = (MicroServiceConfigName)mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceConfigName.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(microServiceConfigName.getName(), "name", MicroServiceConfigName.class); - MicroServiceConfigName data = (MicroServiceConfigName) duplicateData.get(0); - int id = data.getId(); - - if(id==0){ - isFakeUpdate=true; - microServiceConfigName.setId(1); - } else { - microServiceConfigName.setId(id); - } - } - } else { - microServiceConfigName = (MicroServiceConfigName)mapper.readValue(root.get("microServiceCongigNameDictionaryData").toString(), MicroServiceConfigName.class); + if(fromAPI){ + microServiceConfigName = mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceConfigName.class); + }else{ + microServiceConfigName = mapper.readValue(root.get("microServiceConfigNameDictionaryData").toString(), MicroServiceConfigName.class); } - if(microServiceConfigName.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(microServiceConfigName.getName(), "name", MicroServiceConfigName.class); - if(!duplicateData.isEmpty()){ + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(microServiceConfigName.getName(), "name", MicroServiceConfigName.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + MicroServiceConfigName data = (MicroServiceConfigName) duplicateData.get(0); + if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + microServiceConfigName.setId(data.getId()); + }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || + (request.getParameter(operation) == null && (data.getId() != microServiceConfigName.getId()))){ duplicateflag = true; - }else{ - commonClassDao.save(microServiceConfigName); } - }else{ - if(!isFakeUpdate) { + } + String responseString = null; + if(!duplicateflag){ + if(microServiceConfigName.getId() == 0){ + commonClassDao.save(microServiceConfigName); + }else{ commonClassDao.update(microServiceConfigName); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceConfigName.class)); - } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMessage; - } - } - 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("{microServiceCongigNameDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } + } + responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceConfigName.class)); + }else{ + responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, microServiceConfigNameDatas, responseString); + } }catch (Exception e){ - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - LOGGER.error(e); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ms_dictionary/remove_msConfigName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeMicroServiceConfigNameDictionary(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()); - MicroServiceConfigName microServiceConfigName = (MicroServiceConfigName)mapper.readValue(root.get("data").toString(), MicroServiceConfigName.class); - commonClassDao.delete(microServiceConfigName); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceConfigName.class)); - JSONObject j = new JSONObject("{microServiceCongigNameDictionaryDatas: " + 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; + @RequestMapping(value={"/ms_dictionary/remove_msConfigName"}, method={RequestMethod.POST}) + public void removeMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, microServiceConfigNameDatas, MicroServiceConfigName.class); } - @RequestMapping(value={"/get_MicroServiceLocationDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_MicroServiceLocationDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceLocationByNameDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceLocationDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(MicroServiceLocation.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, microServiceLocationDatas, "name", MicroServiceLocation.class); } - @RequestMapping(value={"/get_MicroServiceLocationData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_MicroServiceLocationData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceLocationDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceLocationDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(MicroServiceLocation.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMsg); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, microServiceLocationDatas, MicroServiceLocation.class); } - @RequestMapping(value={"/ms_dictionary/save_location"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/ms_dictionary/save_location"}, method={RequestMethod.POST}) public ModelAndView saveMicroServiceLocationDictionary(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()); MicroServiceLocation microServiceLocation; - if (fromAPI) { - microServiceLocation = (MicroServiceLocation)mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceLocation.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(microServiceLocation.getName(), "name", MicroServiceLocation.class); - MicroServiceLocation data = (MicroServiceLocation) duplicateData.get(0); - int id = data.getId(); - - if(id==0){ - isFakeUpdate=true; - microServiceLocation.setId(1); - } else { - microServiceLocation.setId(id); - } - } - } else { - microServiceLocation = (MicroServiceLocation)mapper.readValue(root.get("microServiceLocationDictionaryData").toString(), MicroServiceLocation.class); + if(fromAPI){ + microServiceLocation = mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceLocation.class); + }else{ + microServiceLocation = mapper.readValue(root.get("microServiceLocationDictionaryData").toString(), MicroServiceLocation.class); } - if(microServiceLocation.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(microServiceLocation.getName(), "name", MicroServiceLocation.class); - if(!duplicateData.isEmpty()){ + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(microServiceLocation.getName(), "name", MicroServiceLocation.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + MicroServiceLocation data = (MicroServiceLocation) duplicateData.get(0); + if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + microServiceLocation.setId(data.getId()); + }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || + (request.getParameter(operation) == null && (data.getId() != microServiceLocation.getId()))){ duplicateflag = true; - }else{ - commonClassDao.save(microServiceLocation); } - }else{ - if(!isFakeUpdate) { + } + String responseString = null; + if(!duplicateflag){ + if(microServiceLocation.getId() == 0){ + commonClassDao.save(microServiceLocation); + }else{ commonClassDao.update(microServiceLocation); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceLocation.class)); - } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMessage; - } - } - 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("{microServiceLocationDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } + } + responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceLocation.class)); + }else{ + responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, microServiceLocationDatas, responseString); + } }catch (Exception e){ - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - LOGGER.error(e); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ms_dictionary/remove_msLocation"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeMicroServiceLocationDictionary(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()); - MicroServiceLocation microServiceLocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); - commonClassDao.delete(microServiceLocation); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceLocation.class)); - JSONObject j = new JSONObject("{microServiceLocationDictionaryDatas: " + 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; + @RequestMapping(value={"/ms_dictionary/remove_msLocation"}, method={RequestMethod.POST}) + public void removeMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, microServiceLocationDatas, MicroServiceLocation.class); } - @RequestMapping(value={"/get_MicroServiceAttributeDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_MicroServiceAttributeDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceAttributeByNameDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceAttributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(MicroServiceAttribute.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, microServiceAttributeDatas, "name", MicroServiceAttribute.class); } - @RequestMapping(value={"/get_MicroServiceAttributeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_MicroServiceAttributeData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceAttributeDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceAttributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(MicroServiceAttribute.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMsg); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, microServiceAttributeDatas, MicroServiceAttribute.class); } - @RequestMapping(value={"/ms_dictionary/save_modelAttribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/ms_dictionary/save_modelAttribute"}, method={RequestMethod.POST}) public ModelAndView saveMicroServiceAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = 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()); MicroServiceAttribute microServiceAttribute; + String checkValue; if (fromAPI) { - microServiceAttribute = (MicroServiceAttribute)mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceAttribute.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - MicroServiceAttribute initialAttribute = (MicroServiceAttribute)mapper.readValue(root.get("initialFields").toString(), MicroServiceAttribute.class); - - String checkValue = initialAttribute.getName() + ":" + initialAttribute.getValue() + ":" + initialAttribute.getModelName(); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkValue, "name:value:modelName", MicroServiceAttribute.class); - int id=0; - for (int i= 0; i<duplicateData.size(); i++){ - MicroServiceAttribute data = (MicroServiceAttribute) duplicateData.get(0); - id = data.getId(); - } - microServiceAttribute.setId(id); - } - } else { - microServiceAttribute = (MicroServiceAttribute)mapper.readValue(root.get("modelAttributeDictionaryData").toString(), MicroServiceAttribute.class); - } - - if(microServiceAttribute.getId() == 0){ - String checkValue = microServiceAttribute.getName() + ":" + microServiceAttribute.getValue() + ":" + microServiceAttribute.getModelName(); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkValue, "name:value:modelName", MicroServiceAttribute.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(microServiceAttribute); - } - }else{ - commonClassDao.update(microServiceAttribute); - } - - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceAttribute.class)); - } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - responseString = successMessage; - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; + microServiceAttribute = mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceAttribute.class); + MicroServiceAttribute initialAttribute = (MicroServiceAttribute)mapper.readValue(root.get("initialFields").toString(), MicroServiceAttribute.class); + checkValue = initialAttribute.getName() + ":" + initialAttribute.getValue() + ":" + initialAttribute.getModelName(); } else { - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{microServiceAttributeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + microServiceAttribute = mapper.readValue(root.get("modelAttributeDictionaryData").toString(), MicroServiceAttribute.class); + checkValue = microServiceAttribute.getName() + ":" + microServiceAttribute.getValue() + ":" + microServiceAttribute.getModelName(); } + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkValue, "name:value:modelName", MicroServiceAttribute.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + MicroServiceAttribute data = (MicroServiceAttribute) duplicateData.get(0); + if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + microServiceAttribute.setId(data.getId()); + }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || + (request.getParameter(operation) == null && (data.getId() != microServiceAttribute.getId()))){ + duplicateflag = true; + } + } + String responseString = null; + if(!duplicateflag){ + if(microServiceAttribute.getId() == 0){ + commonClassDao.save(microServiceAttribute); + }else{ + commonClassDao.update(microServiceAttribute); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceAttribute.class)); + }else{ + responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, microServiceAttributeDatas, responseString); + } } catch (Exception e){ - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - LOGGER.error(e); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ms_dictionary/remove_modelAttribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeMicroServiceAttributeDictionary(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()); - MicroServiceAttribute microServiceAttribute = (MicroServiceAttribute)mapper.readValue(root.get("data").toString(), MicroServiceAttribute.class); - commonClassDao.delete(microServiceAttribute); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(MicroServiceDictionaryController.commonClassDao.getData(MicroServiceAttribute.class)); - JSONObject j = new JSONObject("{microServiceAttributeDictionaryDatas: " + 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; + @RequestMapping(value={"/ms_dictionary/remove_modelAttribute"}, method={RequestMethod.POST}) + public void removeMicroServiceAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, microServiceAttributeDatas, MicroServiceAttribute.class); } - @RequestMapping(value={"/get_MicroServiceModelsDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_MicroServiceModelsDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryByNameEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put(microServiceModelsDictionaryDatas, mapper.writeValueAsString(commonClassDao.getDataByColumn(MicroServiceModels.class, modelName))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, microServiceModelsDictionaryDatas, modelName, MicroServiceModels.class); } - @RequestMapping(value={"/get_MicroServiceModelsDataByVersion"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_MicroServiceModelsDataByVersion"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryByVersionEntityData(HttpServletRequest request, HttpServletResponse response){ try{ Map<String, Object> model = new HashMap<>(); @@ -734,26 +407,13 @@ public class MicroServiceDictionaryController { } } - @RequestMapping(value={"/get_MicroServiceModelsData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_MicroServiceModelsData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put(microServiceModelsDictionaryDatas, mapper.writeValueAsString(commonClassDao.getData(MicroServiceModels.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMsg); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, microServiceModelsDictionaryDatas, MicroServiceModels.class); } - @RequestMapping(value={"/get_MicroServiceModelsDataServiceVersion"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_MicroServiceModelsDataServiceVersion"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryEntityDataServiceVersion(HttpServletResponse response){ try{ Map<String, Object> model = new HashMap<>(); @@ -781,7 +441,7 @@ public class MicroServiceDictionaryController { } } - @RequestMapping(value={"/get_MicroServiceModelsDataByClass"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_MicroServiceModelsDataByClass"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryClassEntityData(HttpServletResponse response){ try{ Map<String, Object> model = new HashMap<>(); @@ -801,15 +461,12 @@ public class MicroServiceDictionaryController { } } - @RequestMapping(value={"/ms_dictionary/save_model"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/ms_dictionary/save_model"}, method={RequestMethod.POST}) public ModelAndView saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = false; - boolean fromAPI = false; this.newModel = new MicroServiceModels(); - 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()); @@ -855,11 +512,11 @@ public class MicroServiceDictionaryController { String value = new Gson().toJson(mainClass.getSubClass()); this.newModel.setSub_attributes(value); String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndexForAttributes= attributes.indexOf("="); + int equalsIndexForAttributes= attributes.indexOf('='); String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1, attributes.length()-1); this.newModel.setAttributes(atttributesAfterFirstEquals); String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndex= refAttributes.indexOf("="); + int equalsIndex= refAttributes.indexOf('='); String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1, refAttributes.length()-1); this.newModel.setRef_attributes(refAttributesAfterFirstEquals); this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); @@ -867,22 +524,8 @@ public class MicroServiceDictionaryController { }else{ if (fromAPI) { - microServiceModels = (MicroServiceModels)mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceModels.class); + microServiceModels = mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceModels.class); userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - String checkName = microServiceModels.getModelName() + ":" + microServiceModels.getVersion(); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", MicroServiceModels.class); - int id = 0; - for (int i=0; i< duplicateData.size(); i++){ - MicroServiceModels data = (MicroServiceModels) duplicateData.get(0); - id = data.getId(); - } - microServiceModels.setId(id); - microServiceModels.setUserCreatedBy(this.getUserInfo(userId)); - - } } else { if (root.has(microServiceModelsDictionaryData)){ if (root.get(microServiceModelsDictionaryData).has(description)){ @@ -915,7 +558,6 @@ public class MicroServiceDictionaryController { addValuesToNewModel(classMap); } } - } microServiceModels.setAttributes(this.newModel.getAttributes()); microServiceModels.setRef_attributes(this.newModel.getRef_attributes()); @@ -925,81 +567,48 @@ public class MicroServiceDictionaryController { microServiceModels.setVersion(this.newModel.getVersion()); microServiceModels.setEnumValues(this.newModel.getEnumValues()); microServiceModels.setAnnotation(this.newModel.getAnnotation()); - - if(microServiceModels.getId() == 0){ - String checkName = microServiceModels.getModelName() + ":" + microServiceModels.getVersion(); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", MicroServiceModels.class); - if(!duplicateData.isEmpty()){ + + String checkName = microServiceModels.getModelName() + ":" + microServiceModels.getVersion(); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", MicroServiceModels.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + MicroServiceModels data = (MicroServiceModels) duplicateData.get(0); + if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + microServiceModels.setId(data.getId()); + }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || + (request.getParameter(operation) == null && (data.getId() != microServiceModels.getId()))){ duplicateflag = true; - }else{ - microServiceModels.setUserCreatedBy(this.getUserInfo(userId)); - commonClassDao.save(microServiceModels); } + } + UserInfo userInfo = utils.getUserInfo(userId); + + String responseString = null; + if(!duplicateflag){ + microServiceModels.setUserCreatedBy(userInfo); + if(microServiceModels.getId() == 0){ + commonClassDao.save(microServiceModels); + }else{ + commonClassDao.update(microServiceModels); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); }else{ - commonClassDao.update(microServiceModels); - } - String responseString = ""; - if(duplicateflag){ responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceModels.class)); - } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - responseString = successMessage; - } - 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("{microServiceModelsDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + utils.setResponseData(response, microServiceModelsDictionaryDatas, responseString); } }catch (Exception e){ - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - LOGGER.error(e); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ms_dictionary/remove_msModel"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeMicroServiceModelsDictionary(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()); - MicroServiceModels microServiceModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class); - commonClassDao.delete(microServiceModels); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceModels.class)); - JSONObject j = new JSONObject("{microServiceModelsDictionaryDatas: " + 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; + @RequestMapping(value={"/ms_dictionary/remove_msModel"}, method={RequestMethod.POST}) + public void removeMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.removeData(request, response, microServiceModelsDictionaryDatas, MicroServiceModels.class); } private void addValuesToNewModel(HashMap<String,MSAttributeObject > classMap) { @@ -1013,8 +622,7 @@ public class MicroServiceDictionaryController { ArrayList<String> dependency = new ArrayList<>(Arrays.asList(dependTemp.split(","))); dependency = getFullDependencyList(dependency); for (String element : dependency){ - MSAttributeObject temp = new MSAttributeObject(); - temp = classMap.get(element); + MSAttributeObject temp = classMap.get(element); if (temp!=null){ mainClass.addAllRefAttribute(temp.getRefAttribute()); mainClass.addAllAttribute(temp.getAttribute()); 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 f430536a2..40c9d7269 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 @@ -21,32 +21,28 @@ package org.onap.policy.pap.xacml.rest.controller; import java.io.IOException; -import java.io.PrintWriter; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; -import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.GroupPolicyScopeList; +import org.onap.policy.rest.jpa.OnapName; import org.onap.policy.rest.jpa.PolicyScopeClosedLoop; import org.onap.policy.rest.jpa.PolicyScopeResource; import org.onap.policy.rest.jpa.PolicyScopeService; import org.onap.policy.rest.jpa.PolicyScopeType; -import org.onap.policy.rest.jpa.UserInfo; -import org.onap.policy.utils.PolicyUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -59,27 +55,25 @@ public class PolicyScopeDictionaryController { private static final Logger LOGGER = FlexLogger.getLogger(PolicyScopeDictionaryController.class); private static CommonClassDao commonClassDao; - private static String successMapKey = "successMapKey"; - private static String exceptionOccured = "Exception Occured"; - private static String successMessage = "success"; private static String operation = "operation"; - private static String getDictionary = "getDictionary"; - private static String errorMsg = "error"; - private static String dictionaryDBQuery = "dictionaryDBQuery"; - private static String apiflag = "apiflag"; private static String groupPolicyScopeListData1 = "groupPolicyScopeListData1"; private static String policyScope= "PolicyScope"; - private static String update = "update"; private static String duplicateResponseString = "Duplicate"; - private static String successMsg = "Success"; - private static String existsResponseString = "Exists"; - private static String utf8 = "UTF-8"; - private static String applicationJsonContentType = "application / json"; - /* - * This is an empty constructor - */ - public PolicyScopeDictionaryController(){} - + private static String groupPolicyScopeDatas = "groupPolicyScopeListDatas"; + private static String dictionaryFields = "dictionaryFields"; + private static String psCLDatas = "psClosedLoopDictionaryDatas"; + private static String psServiceDatas = "psServiceDictionaryDatas"; + private static String psTypeDatas = "psTypeDictionaryDatas"; + private static String psResourceDatas = "psResourceDictionaryDatas"; + + public PolicyScopeDictionaryController(){ + super(); + } + + private DictionaryUtils getDictionaryUtilsInstance(){ + return DictionaryUtils.dictionaryUtils != null ? DictionaryUtils.getDictionaryUtils() : new DictionaryUtils(); + } + @Autowired public PolicyScopeDictionaryController(CommonClassDao commonClassDao){ PolicyScopeDictionaryController.commonClassDao = commonClassDao; @@ -89,101 +83,45 @@ public class PolicyScopeDictionaryController { PolicyScopeDictionaryController.commonClassDao = commonClassDao; } - public UserInfo getUserInfo(String loginId){ - return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - } - - @RequestMapping(value={"/get_GroupPolicyScopeDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_GroupPolicyScopeDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getGroupPolicyScopeEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("groupPolicyScopeListDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(GroupPolicyScopeList.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(exceptionOccured+e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, groupPolicyScopeDatas, "name", GroupPolicyScopeList.class); } - @RequestMapping(value={"/get_GroupPolicyScopeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_GroupPolicyScopeData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getGroupPolicyScopeEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("groupPolicyScopeListDatas", mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, groupPolicyScopeDatas, GroupPolicyScopeList.class); } - @RequestMapping(value={"/ps_dictionary/save_psGroupPolicyScope"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/ps_dictionary/save_psGroupPolicyScope"}, method={RequestMethod.POST}) public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + DictionaryUtils utils = getDictionaryUtilsInstance(); try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean duplicateGroupFlag = 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()); GroupPolicyScopeList gpdata = null; GroupPolicyScope groupData = null; + boolean duplicateGroupFlag = false; if (fromAPI) { - gpdata = (GroupPolicyScopeList)mapper.readValue(root.get("dictionaryFields").toString(), GroupPolicyScopeList.class); + gpdata = mapper.readValue(root.get(dictionaryFields).toString(), GroupPolicyScopeList.class); try{ - groupData = (GroupPolicyScope)mapper.readValue(root.get(groupPolicyScopeListData1).toString(), GroupPolicyScope.class); + 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); } - - if(!gpdata.getGroupName().startsWith(policyScope)){ - String name = "PolicyScope_" + gpdata.getGroupName(); - gpdata.setGroupName(name); - } - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), "name", GroupPolicyScopeList.class); - int id = 0; - for (int i =0; i< duplicateData.size(); i++){ - GroupPolicyScopeList data = (GroupPolicyScopeList) duplicateData.get(0); - id = data.getId(); - } - - if(id==0){ - isFakeUpdate=true; - gpdata.setId(1); - } else { - gpdata.setId(id); - } - - } } else { - gpdata = (GroupPolicyScopeList)mapper.readValue(root.get("groupPolicyScopeListData").toString(), GroupPolicyScopeList.class); - + gpdata = mapper.readValue(root.get("groupPolicyScopeListData").toString(), GroupPolicyScopeList.class); try{ - groupData = (GroupPolicyScope)mapper.readValue(root.get(groupPolicyScopeListData1).toString(), GroupPolicyScope.class); + groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), GroupPolicyScope.class); }catch(Exception e){ LOGGER.error(e); groupData = new GroupPolicyScope(); @@ -192,11 +130,10 @@ public class PolicyScopeDictionaryController { groupData.setService(root.get(groupPolicyScopeListData1).get("service").toString().replace("\"", "")); groupData.setType(root.get(groupPolicyScopeListData1).get("type").toString().replace("\"", "")); } - if(!gpdata.getGroupName().startsWith(policyScope)){ - String name = "PolicyScope_" + gpdata.getGroupName(); - gpdata.setGroupName(name); - } - + } + if(!gpdata.getGroupName().startsWith(policyScope)){ + String name = "PolicyScope_" + gpdata.getGroupName(); + gpdata.setGroupName(name); } ArrayList<String> valueList = new ArrayList<>(); String resourceValue = groupData.getResource(); @@ -209,714 +146,316 @@ public class PolicyScopeDictionaryController { valueList.add("closedLoopControlName=" + closedLoopValue); String list = StringUtils.replaceEach(valueList.toString(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); gpdata.setGroupList(list); - if(!gpdata.getGroupName().startsWith(policyScope)){ - String name = "PolicyScope_" + gpdata.getGroupName(); - gpdata.setGroupName(name); - } - if(gpdata.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), "name", GroupPolicyScopeList.class); - if(!duplicateData.isEmpty()){ + + List<Object> 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()){ + GroupPolicyScopeList data = (GroupPolicyScopeList) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(), "groupList", GroupPolicyScopeList.class); - if(!duplicateData.isEmpty()){ - duplicateGroupFlag = true; - }else{ - commonClassDao.save(gpdata); - } } - }else{ - if(!isFakeUpdate) { - List<Object> duplicateGroupList = commonClassDao.checkExistingGroupListforUpdate(gpdata.getGroupList(), gpdata.getGroupName()); - if(!duplicateGroupList.isEmpty()) { - duplicateGroupFlag = true; - } else { - commonClassDao.update(gpdata); - } - } } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; + String responseString = null; + if(!duplicateflag && !duplicateGroupFlag){ + if(gpdata.getId() == 0){ + commonClassDao.save(gpdata); + }else{ + commonClassDao.update(gpdata); + } + responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); }else if(duplicateGroupFlag){ responseString = "DuplicateGroup"; }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); + responseString = duplicateResponseString; } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString) && !("DuplicateGroup").equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - } - - 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("{groupPolicyScopeListDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, groupPolicyScopeDatas, 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={"/ps_dictionary/remove_GroupPolicyScope"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePSGroupScopeDictionary(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()); - GroupPolicyScopeList onapData = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); - commonClassDao.delete(onapData); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); - JSONObject j = new JSONObject("{groupPolicyScopeListDatas: " + 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; + @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={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_PSClosedLoopDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPSClosedLoopEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psClosedLoopDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PolicyScopeClosedLoop.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(exceptionOccured+e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, psCLDatas, "name", OnapName.class); } - @RequestMapping(value={"/get_PSClosedLoopData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_PSClosedLoopData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPSClosedLoopEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psClosedLoopDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, psCLDatas, PolicyScopeClosedLoop.class); } - @RequestMapping(value={"/ps_dictionary/save_psClosedLoop"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/ps_dictionary/save_psClosedLoop"}, method={RequestMethod.POST}) public ModelAndView savePSClosedLoopDictionary(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()); PolicyScopeClosedLoop onapData; - if (fromAPI) { - onapData = (PolicyScopeClosedLoop)mapper.readValue(root.get("dictionaryFields").toString(), PolicyScopeClosedLoop.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeClosedLoop.class); - int id = 0; - for (int i =0; i< duplicateData.size(); i++){ - PolicyScopeClosedLoop data = (PolicyScopeClosedLoop) duplicateData.get(0); - id = data.getId(); - } - - if(id==0){ - isFakeUpdate=true; - onapData.setId(1); - } else { - onapData.setId(id); - } - - } - } else { - onapData = (PolicyScopeClosedLoop)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); } - if(onapData.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeClosedLoop.class); - if(!duplicateData.isEmpty()){ + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeClosedLoop.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + PolicyScopeClosedLoop data = (PolicyScopeClosedLoop) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - commonClassDao.save(onapData); } - }else{ - if(!isFakeUpdate) { + } + String responseString = null; + if(!duplicateflag){ + if(onapData.getId() == 0){ + commonClassDao.save(onapData); + }else{ commonClassDao.update(onapData); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = duplicateResponseString; - }else{ + } responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); + }else{ + responseString = duplicateResponseString; } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - } - 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("{psClosedLoopDictionaryDatas: " + responseString + "}"); - - out.write(j.toString()); - - return null; + if(fromAPI){ + return utils.getResultForApi(responseString); + }else{ + utils.setResponseData(response, psCLDatas, responseString); } - }catch (Exception e){ - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - LOGGER.error(e); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_PSClosedLoop"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePSClosedLoopDictionary(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()); - PolicyScopeClosedLoop onapData = (PolicyScopeClosedLoop)mapper.readValue(root.get("data").toString(), PolicyScopeClosedLoop.class); - commonClassDao.delete(onapData); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); - JSONObject j = new JSONObject("{psClosedLoopDictionaryDatas: " + 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; + @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={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_PSServiceDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPSServiceEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psServiceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PolicyScopeService.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(exceptionOccured+e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, psServiceDatas, "name", PolicyScopeService.class); } - @RequestMapping(value={"/get_PSServiceData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_PSServiceData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPSServiceEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psServiceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, psServiceDatas, PolicyScopeService.class); } - @RequestMapping(value={"/ps_dictionary/save_psService"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/ps_dictionary/save_psService"}, method={RequestMethod.POST}) public ModelAndView savePSServiceDictionary(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()); PolicyScopeService onapData; if (fromAPI) { - onapData = (PolicyScopeService)mapper.readValue(root.get("dictionaryFields").toString(), PolicyScopeService.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeService.class); - int id = 0; - for (int i =0; i< duplicateData.size(); i++){ - PolicyScopeService data = (PolicyScopeService) duplicateData.get(0); - id = data.getId(); - } - if(id==0){ - isFakeUpdate=true; - onapData.setId(1); - } else { - onapData.setId(id); - } - } + onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeService.class); } else { - onapData = (PolicyScopeService)mapper.readValue(root.get("psServiceDictionaryData").toString(), PolicyScopeService.class); + onapData = mapper.readValue(root.get("psServiceDictionaryData").toString(), PolicyScopeService.class); } - if(onapData.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeService.class); - if(!duplicateData.isEmpty()){ + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeService.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + PolicyScopeService data = (PolicyScopeService) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - commonClassDao.save(onapData); } - }else{ - if(!isFakeUpdate) { + } + String responseString = null; + if(!duplicateflag){ + if(onapData.getId() == 0){ + commonClassDao.save(onapData); + }else{ commonClassDao.update(onapData); - } - } - - String responseString = ""; - if(duplicateflag){ + } + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); + }else{ responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); - } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - } - 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("{psServiceDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; + utils.setResponseData(response, psServiceDatas, responseString); } }catch (Exception e){ - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - LOGGER.error(e); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_PSService"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePSServiceDictionary(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()); - PolicyScopeService onapData = (PolicyScopeService)mapper.readValue(root.get("data").toString(), PolicyScopeService.class); - commonClassDao.delete(onapData); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); - JSONObject j = new JSONObject("{psServiceDictionaryDatas: " + 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; + @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={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_PSTypeDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPSTypeEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PolicyScopeType.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(exceptionOccured+e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, psTypeDatas, "name", PolicyScopeType.class); } - @RequestMapping(value={"/get_PSTypeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_PSTypeData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPSTypeEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(successMapKey, successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, psTypeDatas, PolicyScopeType.class); } - @RequestMapping(value={"/ps_dictionary/save_psType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/ps_dictionary/save_psType"}, method={RequestMethod.POST}) public ModelAndView savePSTypeDictionary(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()); PolicyScopeType onapData; - if (fromAPI) { - onapData = (PolicyScopeType)mapper.readValue(root.get("dictionaryFields").toString(), PolicyScopeType.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeType.class); - int id = 0; - for (int i =0; i< duplicateData.size(); i++){ - PolicyScopeType data = (PolicyScopeType) duplicateData.get(0); - id = data.getId(); - } - - if(id==0){ - isFakeUpdate=true; - onapData.setId(1); - } else { - onapData.setId(id); - } - - } - } else { - onapData = (PolicyScopeType)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); } - if(onapData.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeType.class); - if(!duplicateData.isEmpty()){ + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeType.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + PolicyScopeType data = (PolicyScopeType) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - commonClassDao.save(onapData); } - }else{ - if(!isFakeUpdate) { + } + String responseString = null; + if(!duplicateflag){ + if(onapData.getId() == 0){ + commonClassDao.save(onapData); + }else{ commonClassDao.update(onapData); - } - } - String responseString = ""; - if(duplicateflag){ + } + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); + }else{ responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); - } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - - } - 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("{psTypeDictionaryDatas: " + responseString + "}"); - - out.write(j.toString()); - - return null; + utils.setResponseData(response, psTypeDatas, responseString); } - }catch (Exception e){ - response.setCharacterEncoding(utf8); - request.setCharacterEncoding(utf8); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - LOGGER.error(e); + utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_PSType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePSTypeDictionary(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()); - PolicyScopeType onapData = (PolicyScopeType)mapper.readValue(root.get("data").toString(), PolicyScopeType.class); - commonClassDao.delete(onapData); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); - JSONObject j = new JSONObject("{psTypeDictionaryDatas: " + 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; + @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={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_PSResourceDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPSResourceEntityDataByName(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psResourceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PolicyScopeResource.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(exceptionOccured+e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getDataByEntity(response, psResourceDatas, "name", PolicyScopeResource.class); } - @RequestMapping(value={"/get_PSResourceData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value={"/get_PSResourceData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPSResourceEntityData(HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psResourceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", successMessage); - response.addHeader(operation, getDictionary); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(errorMsg, dictionaryDBQuery); - LOGGER.error(e); - } + DictionaryUtils utils = getDictionaryUtilsInstance(); + utils.getData(response, psResourceDatas, PolicyScopeResource.class); } - @RequestMapping(value={"/ps_dictionary/save_psResource"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping(value={"/ps_dictionary/save_psResource"}, method={RequestMethod.POST}) public ModelAndView savePSResourceDictionary(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()); PolicyScopeResource onapData; if (fromAPI) { - onapData = (PolicyScopeResource)mapper.readValue(root.get("dictionaryFields").toString(), PolicyScopeResource.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if ((update).equals(request.getParameter(operation))) { - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeResource.class); - PolicyScopeResource data = (PolicyScopeResource) duplicateData.get(0); - int id = data.getId(); - - if(id==0){ - isFakeUpdate=true; - onapData.setId(1); - } else { - onapData.setId(id); - } - } + onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeResource.class); } else { - onapData = (PolicyScopeResource)mapper.readValue(root.get("psResourceDictionaryData").toString(), PolicyScopeResource.class); + onapData = mapper.readValue(root.get("psResourceDictionaryData").toString(), PolicyScopeResource.class); } - if(onapData.getId() == 0){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeResource.class); - if(!duplicateData.isEmpty()){ + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeResource.class); + boolean duplicateflag = false; + if(!duplicateData.isEmpty()){ + PolicyScopeResource data = (PolicyScopeResource) duplicateData.get(0); + 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()))){ duplicateflag = true; - }else{ - commonClassDao.save(onapData); } - }else{ - if(!isFakeUpdate) { + } + String responseString = null; + if(!duplicateflag){ + if(onapData.getId() == 0){ + commonClassDao.save(onapData); + }else{ commonClassDao.update(onapData); - } - } - String responseString = ""; - if(duplicateflag){ + } + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); + }else{ responseString = duplicateResponseString; + } + if(fromAPI){ + return utils.getResultForApi(responseString); }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); - } - - if (fromAPI) { - if (responseString!=null && !(duplicateResponseString).equals(responseString)) { - if(isFakeUpdate){ - responseString = existsResponseString; - } else { - responseString = successMsg; - } - - } - 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("{psResourceDictionaryDatas: " + responseString + "}"); - - out.write(j.toString()); - - return null; + utils.setResponseData(response, psResourceDatas, 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={"/ps_dictionary/remove_PSResource"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePSResourceDictionary(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()); - PolicyScopeResource onapData = (PolicyScopeResource)mapper.readValue(root.get("data").toString(), PolicyScopeResource.class); - commonClassDao.delete(onapData); - response.setCharacterEncoding(utf8); - response.setContentType(applicationJsonContentType); - request.setCharacterEncoding(utf8); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); - JSONObject j = new JSONObject("{psResourceDictionaryDatas: " + 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; + @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); } } 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 new file mode 100644 index 000000000..e18595956 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java @@ -0,0 +1,213 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.util; + +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; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.Category; +import org.onap.policy.rest.jpa.Datatype; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.xacml.api.XACMLErrorConstants; +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 String apiflag = "apiflag"; + private static String operation = "operation"; + private static String duplicateResponseString = "Duplicate"; + private static String utf8 = "UTF-8"; + private static String applicationJsonContentType = "application / json"; + + private static CommonClassDao commonClassDao; + + public static DictionaryUtils dictionaryUtils; + + public static synchronized DictionaryUtils getDictionaryUtils() { + return dictionaryUtils; + } + + public static synchronized void setDictionaryUtils(DictionaryUtils dictionaryUtils) { + DictionaryUtils.dictionaryUtils = dictionaryUtils; + } + + @Autowired + public DictionaryUtils(CommonClassDao commonClassDao){ + DictionaryUtils.commonClassDao = commonClassDao; + } + + public DictionaryUtils(){ + super(); + } + + 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 String appendKey(List<Object> objects, String key1, String appendValue){ + StringBuilder userValue = new StringBuilder(); + int counter = 0; + for(Object attribute : objects){ + if(attribute instanceof LinkedHashMap<?, ?>){ + String key = ((LinkedHashMap<?, ?>) attribute).get(key1).toString(); + if(counter>0){ + userValue.append(appendValue); + } + userValue.append(key); + counter ++; + } + } + return userValue.toString(); + } + + public String appendKeyValue(List<Object> objects, String append1, String append2){ + StringBuilder header = new StringBuilder(); + int counter = 0; + 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){ + header.append(append1); + } + header.append(key).append(append2).append(value); + counter ++; + } + } + return header.toString(); + } + + public Datatype getDataType(String datatype){ + Datatype a = new Datatype(); + if("string".equalsIgnoreCase(datatype)){ + a.setId(26); + }else if("integer".equalsIgnoreCase(datatype)){ + a.setId(12); + }else if("boolean".equalsIgnoreCase(datatype)){ + a.setId(18); + }else if("double".equalsIgnoreCase(datatype)){ + a.setId(25); + }else if("user".equalsIgnoreCase(datatype)){ + a.setId(29); + } + return a; + } + + public Category getCategory(){ + return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource").get(0); + } + + public ModelAndView getResultForApi(String inResponseString){ + String responseString = inResponseString; + if(responseString!=null && !duplicateResponseString.equals(responseString)){ + responseString = "Success"; + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } + + 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 + "}"); + out.write(j.toString()); + } + + public void setErrorResponseData(HttpServletResponse response, Exception e) throws IOException{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding(utf8); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + + @SuppressWarnings("rawtypes") + public void getDataByEntity(HttpServletResponse response, String key, String value, Class className){ + try{ + Map<String, Object> model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + 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){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @SuppressWarnings("rawtypes") + public void getData(HttpServletResponse response, String key, Class className){ + try{ + Map<String, Object> 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(operation, "getDictionary"); + response.getWriter().write(j.toString()); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + 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{ + 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)); + String responseString = mapper.writeValueAsString(commonClassDao.getData(className)); + setResponseData(response, key, responseString); + }catch(Exception e){ + setErrorResponseData(response, e); + } + } + +} |