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