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