Merge "Fix critical sonar for ONAP-PAP-REST"
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / controller / DecisionPolicyDictionaryController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-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.onap.policy.pap.xacml.rest.controller;
22
23 import java.io.IOException;
24 import java.io.PrintWriter;
25 import java.io.UnsupportedEncodingException;
26 import java.util.ArrayList;
27 import java.util.Date;
28 import java.util.HashMap;
29 import java.util.LinkedHashMap;
30 import java.util.List;
31 import java.util.Map;
32
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35
36 import org.json.JSONObject;
37 import org.onap.policy.common.logging.flexlogger.FlexLogger;
38 import org.onap.policy.common.logging.flexlogger.Logger;
39 import org.onap.policy.pap.xacml.rest.util.JsonMessage;
40 import org.onap.policy.rest.dao.CommonClassDao;
41 import org.onap.policy.rest.jpa.Datatype;
42 import org.onap.policy.rest.jpa.DecisionSettings;
43 import org.onap.policy.rest.jpa.RainyDayTreatments;
44 import org.onap.policy.rest.jpa.UserInfo;
45 import org.onap.policy.xacml.api.XACMLErrorConstants;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.http.MediaType;
48 import org.springframework.stereotype.Controller;
49 import org.springframework.web.bind.annotation.RequestMapping;
50 import org.springframework.web.servlet.ModelAndView;
51
52 import com.fasterxml.jackson.databind.DeserializationFeature;
53 import com.fasterxml.jackson.databind.JsonNode;
54 import com.fasterxml.jackson.databind.ObjectMapper;
55
56 @Controller
57 public class DecisionPolicyDictionaryController {
58
59         private static final Logger LOGGER  = FlexLogger.getLogger(DecisionPolicyDictionaryController.class);
60         
61         private static CommonClassDao commonClassDao;
62         
63         @Autowired
64         public DecisionPolicyDictionaryController(CommonClassDao commonClassDao){
65                 DecisionPolicyDictionaryController.commonClassDao = commonClassDao;
66         }
67         
68         public DecisionPolicyDictionaryController(){}
69         
70         public UserInfo getUserInfo(String loginId){
71                 UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId);
72                 return name;    
73         }
74         
75         @RequestMapping(value={"/get_SettingsDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
76         public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){
77                 try{
78                         Map<String, Object> model = new HashMap<>();
79                         ObjectMapper mapper = new ObjectMapper();
80                         model.put("settingsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DecisionSettings.class, "xacmlId")));
81                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
82                         JSONObject j = new JSONObject(msg);
83                         response.getWriter().write(j.toString());
84                 }
85                 catch (Exception e){
86                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
87                 }
88         }
89
90         
91         @RequestMapping(value={"/get_SettingsDictionaryData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
92         public void getSettingsDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
93                 try{
94                         Map<String, Object> model = new HashMap<>();
95                         ObjectMapper mapper = new ObjectMapper();
96                         model.put("settingsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)));
97                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
98                         JSONObject j = new JSONObject(msg);
99             response.addHeader("successMapKey", "success"); 
100             response.addHeader("operation", "getDictionary");
101                         response.getWriter().write(j.toString());
102                 }
103                 catch (Exception e){
104             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
105             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
106             response.addHeader("error", "dictionaryDBQuery");
107                 }
108         }
109         
110         @RequestMapping(value={"/decision_dictionary/save_Settings"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
111         public ModelAndView saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException{
112                 try {
113                         boolean duplicateflag = false;
114             boolean isFakeUpdate = false;
115             boolean fromAPI = false;
116             if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) {
117                 fromAPI = true;
118             }
119                         ObjectMapper mapper = new ObjectMapper();
120                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
121                         JsonNode root = mapper.readTree(request.getReader());
122                         DecisionSettings decisionSettings;
123             String userId = null;
124             
125             if (fromAPI) {
126                 decisionSettings = (DecisionSettings)mapper.readValue(root.get("dictionaryFields").toString(), DecisionSettings.class);
127                 userId = "API";
128
129                 //check if update operation or create, get id for data to be updated and update attributeData
130                 if (request.getParameter("operation").equals("update")) {
131                         List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), "xacmlId", DecisionSettings.class);
132                         int id = 0;
133                         DecisionSettings data = (DecisionSettings) duplicateData.get(0);
134                         id = data.getId();
135                         if(id==0){
136                                 isFakeUpdate=true;
137                                 decisionSettings.setId(1);
138                         } else {
139                                 decisionSettings.setId(id);
140                         }
141                         decisionSettings.setUserCreatedBy(this.getUserInfo(userId));
142                 }
143             } else {
144                 decisionSettings = (DecisionSettings)mapper.readValue(root.get("settingsDictionaryData").toString(), DecisionSettings.class);
145                 userId = root.get("userid").textValue();
146             }
147                         if(decisionSettings.getDatatypeBean().getShortName() != null){
148                                 String datatype = decisionSettings.getDatatypeBean().getShortName();
149                                 Datatype a = new Datatype();
150                                 if(datatype.equalsIgnoreCase("string")){
151                                         a.setId(26);    
152                                 }else if(datatype.equalsIgnoreCase("integer")){
153                                         a.setId(12);    
154                                 }else if(datatype.equalsIgnoreCase("boolean")){
155                                         a.setId(18);    
156                                 }else if(datatype.equalsIgnoreCase("double")){
157                                         a.setId(25);    
158                                 }else if(datatype.equalsIgnoreCase("user")){
159                                         a.setId(29);    
160                                 }
161                                 decisionSettings.setDatatypeBean(a);
162                         }
163                         if(decisionSettings.getId() == 0){
164                                 List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), "xacmlId", DecisionSettings.class);
165                                 if(!duplicateData.isEmpty()){
166                                         duplicateflag = true;
167                                 }else{
168                                         decisionSettings.setUserCreatedBy(this.getUserInfo(userId));
169                                         decisionSettings.setUserModifiedBy(this.getUserInfo(userId));
170                                         commonClassDao.save(decisionSettings);
171                                 }
172                         }else{
173                                 if(!isFakeUpdate) {
174                                         decisionSettings.setUserModifiedBy(this.getUserInfo(userId));
175                                         decisionSettings.setModifiedDate(new Date());
176                                         commonClassDao.update(decisionSettings); 
177                                 }
178                         }
179             String responseString = "";
180             if(duplicateflag){
181                 responseString = "Duplicate";
182             }else{
183                 responseString =  mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class));
184             }
185           
186             if (fromAPI) {
187                 if (responseString!=null && !responseString.equals("Duplicate")) {
188                     if(isFakeUpdate){
189                         responseString = "Exists";
190                     } else {
191                         responseString = "Success";
192                     }
193                 }
194                 ModelAndView result = new ModelAndView();
195                 result.setViewName(responseString);
196                 return result;
197             } else {
198                 response.setCharacterEncoding("UTF-8");
199                 response.setContentType("application / json");
200                 request.setCharacterEncoding("UTF-8");
201  
202                 PrintWriter out = response.getWriter();
203                 JSONObject j = new JSONObject("{settingsDictionaryDatas: " + responseString + "}");
204                 out.write(j.toString());
205                 return null;
206             }
207  
208         }catch (Exception e){
209                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
210                         response.setCharacterEncoding("UTF-8");
211                         request.setCharacterEncoding("UTF-8");
212                         PrintWriter out = response.getWriter();
213                         out.write(e.getMessage());
214                 }
215                 return null;
216         }
217
218         @RequestMapping(value={"/settings_dictionary/remove_settings"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
219         public ModelAndView removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException {
220                 try{
221                         ObjectMapper mapper = new ObjectMapper();
222                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
223                         JsonNode root = mapper.readTree(request.getReader());
224                         DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class);
225                         commonClassDao.delete(decisionSettings);
226                         response.setCharacterEncoding("UTF-8");
227                         response.setContentType("application / json");
228                         request.setCharacterEncoding("UTF-8");
229
230                         PrintWriter out = response.getWriter();
231
232                         String responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class));
233                         JSONObject j = new JSONObject("{settingsDictionaryDatas: " + responseString + "}");
234                         out.write(j.toString());
235
236                         return null;
237                 }
238                 catch (Exception e){
239                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
240                         response.setCharacterEncoding("UTF-8");
241                         request.setCharacterEncoding("UTF-8");
242                         PrintWriter out = response.getWriter();
243                         out.write(e.getMessage());
244                 }
245                 return null;
246         }
247         
248         
249         
250         @RequestMapping(value={"/get_RainyDayDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
251         public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){
252                 try{
253                         Map<String, Object> model = new HashMap<>();
254                         ObjectMapper mapper = new ObjectMapper();
255                         model.put("rainyDayDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(RainyDayTreatments.class, "bbid")));
256                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
257                         JSONObject j = new JSONObject(msg);
258                         response.getWriter().write(j.toString());
259                 }
260                 catch (Exception e){
261                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
262                 }
263         }
264
265         
266         @RequestMapping(value={"/get_RainyDayDictionaryData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
267         public void getRainyDayDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
268                 try{
269                         Map<String, Object> model = new HashMap<>();
270                         ObjectMapper mapper = new ObjectMapper();
271                         model.put("rainyDayDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)));
272                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
273                         JSONObject j = new JSONObject(msg);
274             response.addHeader("successMapKey", "success"); 
275             response.addHeader("operation", "getDictionary");
276                         response.getWriter().write(j.toString());
277                 }
278                 catch (Exception e){
279             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
280             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
281             response.addHeader("error", "dictionaryDBQuery");
282                 }
283         }
284         
285         @RequestMapping(value={"/decision_dictionary/save_RainyDay"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
286         public ModelAndView saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException{
287                 try {
288                         boolean duplicateflag = false;
289             boolean isFakeUpdate = false;
290             boolean fromAPI = false;
291             if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) {
292                 fromAPI = true;
293             }
294                         ObjectMapper mapper = new ObjectMapper();
295                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
296                         JsonNode root = mapper.readTree(request.getReader());
297                         RainyDayTreatments decisionRainyDay;
298             TreatmentValues treatmentsData = null;
299             if (fromAPI) {
300                 decisionRainyDay = (RainyDayTreatments)mapper.readValue(root.get("dictionaryFields").toString(), RainyDayTreatments.class);
301                 treatmentsData = (TreatmentValues)mapper.readValue(root.get("dictionaryFields").toString(), TreatmentValues.class);
302                 //check if update operation or create, get id for data to be updated and update attributeData
303                 if (request.getParameter("operation").equals("update")) {
304                         List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(decisionRainyDay.getBbid()+":"+decisionRainyDay.getWorkstep(), "bbid:workstep", RainyDayTreatments.class);
305                         int id = 0;
306                         RainyDayTreatments data = (RainyDayTreatments) duplicateData.get(0);
307                         id = data.getId();
308                         if(id==0){
309                                 isFakeUpdate=true;
310                         } else {
311                                 decisionRainyDay.setId(id);
312                         }
313                 }
314             } else {
315                 decisionRainyDay = (RainyDayTreatments)mapper.readValue(root.get("rainyDayDictionaryData").toString(), RainyDayTreatments.class);
316                 treatmentsData = (TreatmentValues)mapper.readValue(root.get("rainyDayDictionaryData").toString(), TreatmentValues.class);
317             }
318             
319                         String userValue = "";
320                         int counter = 0;
321                         if(treatmentsData.getUserDataTypeValues().size() > 0){
322                                 for(Object treatment : treatmentsData.getUserDataTypeValues()){
323                                         if(treatment instanceof LinkedHashMap<?, ?>){
324                                                 String key = ((LinkedHashMap<?, ?>) treatment).get("treatment").toString();
325                                                 if(counter>0){
326                                                         userValue = userValue + ",";
327                                                 }
328                                                 userValue = userValue + key ;
329                                                 counter ++;
330                                         }
331                                 }
332                         }
333                         decisionRainyDay.setTreatments(userValue);
334                         
335                         if(decisionRainyDay.getId() == 0){
336                         List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(decisionRainyDay.getBbid()+":"+decisionRainyDay.getWorkstep(), "bbid:workstep", RainyDayTreatments.class);
337                                 if(!duplicateData.isEmpty()){
338                                         duplicateflag = true;
339                                 }else{
340                                         commonClassDao.save(decisionRainyDay);
341                                 }
342                         }else{
343                                 if(!isFakeUpdate) {
344                                         commonClassDao.update(decisionRainyDay); 
345                                 }
346                         }
347             String responseString = "";
348             if(duplicateflag){
349                 responseString = "Duplicate";
350             }else{
351                 responseString =  mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class));
352             }
353           
354             if (fromAPI) {
355                 if (responseString!=null && !responseString.equals("Duplicate")) {
356                     if(isFakeUpdate){
357                         responseString = "Exists";
358                     } else {
359                         responseString = "Success";
360                     }
361                 }
362                 ModelAndView result = new ModelAndView();
363                 result.setViewName(responseString);
364                 return result;
365             } else {
366                 response.setCharacterEncoding("UTF-8");
367                 response.setContentType("application / json");
368                 request.setCharacterEncoding("UTF-8");
369  
370                 PrintWriter out = response.getWriter();
371                 JSONObject j = new JSONObject("{rainyDayDictionaryDatas: " + responseString + "}");
372                 out.write(j.toString());
373                 return null;
374             }
375  
376         }catch (Exception e){
377                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
378                         response.setCharacterEncoding("UTF-8");
379                         request.setCharacterEncoding("UTF-8");
380                         PrintWriter out = response.getWriter();
381                         out.write(e.getMessage());
382                 }
383                 return null;
384         }
385
386         @RequestMapping(value={"/decision_dictionary/remove_rainyDay"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
387         public ModelAndView removeRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException {
388                 try{
389                         ObjectMapper mapper = new ObjectMapper();
390                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
391                         JsonNode root = mapper.readTree(request.getReader());
392                         RainyDayTreatments decisionRainyDay = (RainyDayTreatments)mapper.readValue(root.get("data").toString(), RainyDayTreatments.class);
393                         commonClassDao.delete(decisionRainyDay);
394                         response.setCharacterEncoding("UTF-8");
395                         response.setContentType("application / json");
396                         request.setCharacterEncoding("UTF-8");
397
398                         PrintWriter out = response.getWriter();
399
400                         String responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class));
401                         JSONObject j = new JSONObject("{rainyDayDictionaryDatas: " + responseString + "}");
402                         out.write(j.toString());
403
404                         return null;
405                 }
406                 catch (Exception e){
407                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
408                         response.setCharacterEncoding("UTF-8");
409                         request.setCharacterEncoding("UTF-8");
410                         PrintWriter out = response.getWriter();
411                         out.write(e.getMessage());
412                 }
413                 return null;
414         }
415         
416 }
417
418 class TreatmentValues { 
419         private ArrayList<Object> userDataTypeValues;
420
421         public ArrayList<Object> getUserDataTypeValues() {
422                 return userDataTypeValues;
423         }
424
425         public void setUserDataTypeValues(ArrayList<Object> userDataTypeValues) {
426                 this.userDataTypeValues = userDataTypeValues;
427         }
428 }