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