60ed95a0763afd07b5ea78b562aad316e5434447
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / controller / DecisionPolicyDictionaryController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.pap.xacml.rest.controller;
22
23 import java.io.PrintWriter;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30
31 import org.json.JSONObject;
32 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
33 import org.openecomp.policy.common.logging.flexlogger.Logger;
34 import org.openecomp.policy.pap.xacml.rest.util.JsonMessage;
35 import org.openecomp.policy.rest.dao.CommonClassDao;
36 import org.openecomp.policy.rest.jpa.Datatype;
37 import org.openecomp.policy.rest.jpa.DecisionSettings;
38 import org.openecomp.policy.rest.jpa.UserInfo;
39 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.http.MediaType;
42 import org.springframework.stereotype.Controller;
43 import org.springframework.web.bind.annotation.RequestMapping;
44 import org.springframework.web.servlet.ModelAndView;
45
46 import com.fasterxml.jackson.databind.DeserializationFeature;
47 import com.fasterxml.jackson.databind.JsonNode;
48 import com.fasterxml.jackson.databind.ObjectMapper;
49
50 @Controller
51 public class DecisionPolicyDictionaryController {
52
53         private static final Logger LOGGER  = FlexLogger.getLogger(DecisionPolicyDictionaryController.class);
54         
55         private static CommonClassDao commonClassDao;
56         
57         @Autowired
58         public DecisionPolicyDictionaryController(CommonClassDao commonClassDao){
59                 DecisionPolicyDictionaryController.commonClassDao = commonClassDao;
60         }
61         
62         public DecisionPolicyDictionaryController(){}
63         
64         public UserInfo getUserInfo(String loginId){
65                 UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId);
66                 return name;    
67         }
68         
69         @RequestMapping(value={"/get_SettingsDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
70         public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){
71                 try{
72                         Map<String, Object> model = new HashMap<String, Object>();
73                         ObjectMapper mapper = new ObjectMapper();
74                         model.put("settingsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DecisionSettings.class, "xacmlId")));
75                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
76                         JSONObject j = new JSONObject(msg);
77                         response.getWriter().write(j.toString());
78                 }
79                 catch (Exception e){
80                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
81                 }
82         }
83
84         
85         @RequestMapping(value={"/get_SettingsDictionaryData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
86         public void getSettingsDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
87                 try{
88                         Map<String, Object> model = new HashMap<String, Object>();
89                         ObjectMapper mapper = new ObjectMapper();
90                         model.put("settingsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)));
91                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
92                         JSONObject j = new JSONObject(msg);
93             response.addHeader("successMapKey", "success"); 
94             response.addHeader("operation", "getDictionary");
95                         response.getWriter().write(j.toString());
96                 }
97                 catch (Exception e){
98             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
99             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
100             response.addHeader("error", "dictionaryDBQuery");
101                 }
102         }
103         
104         @RequestMapping(value={"/decision_dictionary/save_Settings"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
105         public ModelAndView saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
106                 try {
107                         boolean duplicateflag = false;
108             boolean isFakeUpdate = false;
109             boolean fromAPI = false;
110             if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) {
111                 fromAPI = true;
112             }
113                         ObjectMapper mapper = new ObjectMapper();
114                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
115                         JsonNode root = mapper.readTree(request.getReader());
116                         DecisionSettings decisionSettings;
117             String userId = null;
118             
119             if (fromAPI) {
120                 decisionSettings = (DecisionSettings)mapper.readValue(root.get("dictionaryFields").toString(), DecisionSettings.class);
121                 userId = "API";
122
123                 //check if update operation or create, get id for data to be updated and update attributeData
124                 if (request.getParameter("operation").equals("update")) {
125                         List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), "xacmlId", DecisionSettings.class);
126                         int id = 0;
127                         DecisionSettings data = (DecisionSettings) duplicateData.get(0);
128                         id = data.getId();
129                         if(id==0){
130                                 isFakeUpdate=true;
131                                 decisionSettings.setId(1);
132                         } else {
133                                 decisionSettings.setId(id);
134                         }
135                         decisionSettings.setUserCreatedBy(this.getUserInfo(userId));
136                 }
137             } else {
138                 decisionSettings = (DecisionSettings)mapper.readValue(root.get("settingsDictionaryData").toString(), DecisionSettings.class);
139                 userId = root.get("userid").textValue();
140             }
141                         if(decisionSettings.getDatatypeBean().getShortName() != null){
142                                 String datatype = decisionSettings.getDatatypeBean().getShortName();
143                                 Datatype a = new Datatype();
144                                 if(datatype.equalsIgnoreCase("string")){
145                                         a.setId(26);    
146                                 }else if(datatype.equalsIgnoreCase("integer")){
147                                         a.setId(12);    
148                                 }else if(datatype.equalsIgnoreCase("boolean")){
149                                         a.setId(18);    
150                                 }else if(datatype.equalsIgnoreCase("double")){
151                                         a.setId(25);    
152                                 }else if(datatype.equalsIgnoreCase("user")){
153                                         a.setId(29);    
154                                 }
155                                 decisionSettings.setDatatypeBean(a);
156                         }
157                         if(decisionSettings.getId() == 0){
158                                 List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), "xacmlId", DecisionSettings.class);
159                                 if(!duplicateData.isEmpty()){
160                                         duplicateflag = true;
161                                 }else{
162                                         decisionSettings.setUserCreatedBy(this.getUserInfo(userId));
163                                         decisionSettings.setUserModifiedBy(this.getUserInfo(userId));
164                                         commonClassDao.save(decisionSettings);
165                                 }
166                         }else{
167                                 if(!isFakeUpdate) {
168                                         decisionSettings.setUserModifiedBy(this.getUserInfo(userId));
169                                         commonClassDao.update(decisionSettings); 
170                                 }
171                         }
172             String responseString = "";
173             if(duplicateflag){
174                 responseString = "Duplicate";
175             }else{
176                 responseString =  mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class));
177             }
178           
179             if (fromAPI) {
180                 if (responseString!=null && !responseString.equals("Duplicate")) {
181                     if(isFakeUpdate){
182                         responseString = "Exists";
183                     } else {
184                         responseString = "Success";
185                     }
186                 }
187                 ModelAndView result = new ModelAndView();
188                 result.setViewName(responseString);
189                 return result;
190             } else {
191                 response.setCharacterEncoding("UTF-8");
192                 response.setContentType("application / json");
193                 request.setCharacterEncoding("UTF-8");
194  
195                 PrintWriter out = response.getWriter();
196                 JSONObject j = new JSONObject("{settingsDictionaryDatas: " + responseString + "}");
197                 out.write(j.toString());
198                 return null;
199             }
200  
201         }catch (Exception e){
202                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
203                         response.setCharacterEncoding("UTF-8");
204                         request.setCharacterEncoding("UTF-8");
205                         PrintWriter out = response.getWriter();
206                         out.write(e.getMessage());
207                 }
208                 return null;
209         }
210
211         @RequestMapping(value={"/settings_dictionary/remove_settings"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
212         public ModelAndView removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception {
213                 try{
214                         ObjectMapper mapper = new ObjectMapper();
215                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
216                         JsonNode root = mapper.readTree(request.getReader());
217                         DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class);
218                         commonClassDao.delete(decisionSettings);
219                         response.setCharacterEncoding("UTF-8");
220                         response.setContentType("application / json");
221                         request.setCharacterEncoding("UTF-8");
222
223                         PrintWriter out = response.getWriter();
224
225                         String responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class));
226                         JSONObject j = new JSONObject("{settingsDictionaryDatas: " + responseString + "}");
227                         out.write(j.toString());
228
229                         return null;
230                 }
231                 catch (Exception e){
232                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
233                         response.setCharacterEncoding("UTF-8");
234                         request.setCharacterEncoding("UTF-8");
235                         PrintWriter out = response.getWriter();
236                         out.write(e.getMessage());
237                 }
238                 return null;
239         }
240         
241 }