Merge "Fix a Bug on Editor Screen"
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / controller / SafePolicyController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2018 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.util.Date;
26 import java.util.HashMap;
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.onap.policy.common.logging.flexlogger.FlexLogger;
35 import org.onap.policy.common.logging.flexlogger.Logger;
36 import org.onap.policy.pap.xacml.rest.util.JsonMessage;
37 import org.onap.policy.rest.dao.CommonClassDao;
38 import org.onap.policy.rest.jpa.RiskType;
39 import org.onap.policy.rest.jpa.SafePolicyWarning;
40 import org.onap.policy.rest.jpa.UserInfo;
41 import org.onap.policy.utils.PolicyUtils;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.http.MediaType;
44 import org.springframework.stereotype.Controller;
45 import org.springframework.web.bind.annotation.RequestMapping;
46 import org.springframework.web.bind.annotation.RequestMethod;
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 SafePolicyController {
55
56         private static final Logger LOGGER  = FlexLogger.getLogger(SafePolicyController.class);
57         
58         private static CommonClassDao commonClassDao;
59         private static String duplicateResponseString = "Duplicate";
60         private static String operation = "operation";
61         private static String apiflag = "apiflag";
62         private static String utf8 = "UTF-8";
63         private static String applicationJsonContentType = "application / json";
64
65         @Autowired
66         public SafePolicyController(CommonClassDao commonClassDao){
67                 SafePolicyController.commonClassDao = commonClassDao;
68         }
69         
70         public void setCommonClassDao(CommonClassDao commonClassDao){
71                 SafePolicyController.commonClassDao = commonClassDao;
72         }
73         
74         public SafePolicyController(){
75                 //Empty Constructor
76         }       
77         
78         public UserInfo getUserInfo(String loginId){
79                 return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId);
80         }
81         
82         @RequestMapping(value = { "/get_RiskTypeDataByName" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
83         public void getRiskTypeDictionaryByNameEntityData(HttpServletResponse response) {
84                 try {
85                         Map<String, Object> model = new HashMap<>();
86                         ObjectMapper mapper = new ObjectMapper();
87                         model.put("riskTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(RiskType.class, "name")));
88                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
89                         JSONObject j = new JSONObject(msg);
90                         response.getWriter().write(j.toString());
91                 } catch (Exception e) {
92                         LOGGER.error("Exception Occured"+e);
93                 }
94         }
95
96         @RequestMapping(value = { "/get_RiskTypeData" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
97         public void getRiskTypeDictionaryEntityData(HttpServletResponse response) {
98                 try {
99                         Map<String, Object> model = new HashMap<>();
100                         ObjectMapper mapper = new ObjectMapper();
101                         model.put("riskTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(RiskType.class)));
102                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
103                         JSONObject j = new JSONObject(msg);
104             response.addHeader("successMapKey", "success"); 
105             response.addHeader(operation, "getDictionary");
106                         response.getWriter().write(j.toString());
107                 } catch (Exception e) {
108             LOGGER.error(e);
109             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
110             response.addHeader("error", "dictionaryDBQuery");
111                 }
112         }
113
114         @RequestMapping(value = { "/sp_dictionary/save_riskType" }, method = {RequestMethod.POST })
115         public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
116                 try {
117                         boolean duplicateflag = false;
118             boolean isFakeUpdate = false;
119             boolean fromAPI = false;
120             if (request.getParameter(apiflag)!=null && ("api").equalsIgnoreCase(request.getParameter(apiflag))) {
121                 fromAPI = true;
122             }
123                         ObjectMapper mapper = new ObjectMapper();
124                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
125                         JsonNode root = mapper.readTree(request.getReader());
126             RiskType riskTypeData;
127             String userId = null;
128             if (fromAPI) {
129                 riskTypeData = mapper.readValue(root.get("dictionaryFields").toString(),
130                         RiskType.class);
131                 userId = "API";
132                 
133                 //check if update operation or create, get id for data to be updated and update attributeData
134                 if ("update".equalsIgnoreCase(request.getParameter(operation))){
135                     List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class);
136                     RiskType data = (RiskType) duplicateData.get(0);
137                     int id = data.getId();
138                     
139                     if(id==0){
140                         isFakeUpdate=true;
141                         riskTypeData.setId(1);
142                     } else {
143                         riskTypeData.setId(id);
144                     }
145                     
146                     riskTypeData.setUserCreatedBy(this.getUserInfo(userId));
147                 }
148             } else {
149                 riskTypeData = mapper.readValue(root.get("riskTypeDictionaryData").toString(), RiskType.class);
150                 userId = root.get("userid").textValue();
151             }
152                          
153                         if (riskTypeData.getId() == 0) {
154                                 List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class);
155                                 if(!duplicateData.isEmpty()){
156                                         duplicateflag = true;
157                                 }else{
158                                         riskTypeData.setUserCreatedBy(getUserInfo(userId));
159                                         riskTypeData.setUserModifiedBy(getUserInfo(userId));
160                                         commonClassDao.save(riskTypeData);
161                                 }
162                         } else {
163                                 if (!isFakeUpdate) {
164                                         riskTypeData.setUserModifiedBy(this.getUserInfo(userId));
165                                         riskTypeData.setModifiedDate(new Date());
166                                         commonClassDao.update(riskTypeData);
167                                 }
168                         }
169             String responseString = "";
170             if(duplicateflag){
171                 responseString = duplicateResponseString;
172             }else{
173                 responseString = mapper.writeValueAsString(commonClassDao.getData(RiskType.class));
174             }
175             
176             if (fromAPI) {
177                 if (responseString!=null && !responseString.equals(duplicateResponseString)) {
178                     if(isFakeUpdate){
179                         responseString = "Exists";
180                     } else {
181                         responseString = "Success";
182                     }
183                 }
184                 ModelAndView result = new ModelAndView();
185                 result.setViewName(responseString);
186                 return result;
187             } else {
188                 response.setCharacterEncoding(utf8);
189                 response.setContentType(applicationJsonContentType);
190                 request.setCharacterEncoding(utf8);
191  
192                 PrintWriter out = response.getWriter();
193                 JSONObject j = new JSONObject("{riskTypeDictionaryDatas: " + responseString + "}");
194                 out.write(j.toString());
195                 return null;
196             }
197         }catch (Exception e) {
198                 LOGGER.error(e);
199                         response.setCharacterEncoding(utf8);
200                         request.setCharacterEncoding(utf8);
201                         PrintWriter out = response.getWriter();
202                         out.write(PolicyUtils.CATCH_EXCEPTION);
203                 }
204                 return null;
205         }
206
207         @RequestMapping(value = { "/sp_dictionary/remove_riskType" }, method = {RequestMethod.POST })
208         public ModelAndView removeRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
209                 try {
210                         ObjectMapper mapper = new ObjectMapper();
211                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
212                         JsonNode root = mapper.readTree(request.getReader());
213                         RiskType onapData = mapper.readValue(root.get("data").toString(), RiskType.class);
214                         commonClassDao.delete(onapData);
215                         response.setCharacterEncoding(utf8);
216                         response.setContentType(applicationJsonContentType);
217                         request.setCharacterEncoding(utf8);
218
219                         PrintWriter out = response.getWriter();
220
221                         String responseString = mapper.writeValueAsString(commonClassDao.getData(RiskType.class));
222                         JSONObject j = new JSONObject("{riskTypeDictionaryDatas: " + responseString + "}");
223                         out.write(j.toString());
224
225                         return null;
226                 } catch (Exception e) {
227                         LOGGER.error(e);
228                         response.setCharacterEncoding(utf8);
229                         request.setCharacterEncoding(utf8);
230                         PrintWriter out = response.getWriter();
231                         out.write(PolicyUtils.CATCH_EXCEPTION);
232                 }
233                 return null;
234         }
235
236         @RequestMapping(value = { "/get_SafePolicyWarningDataByName" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
237         public void getSafePolicyWarningEntityDataByName(HttpServletResponse response) {
238                 try {
239                         Map<String, Object> model = new HashMap<>();
240                         ObjectMapper mapper = new ObjectMapper();
241                         model.put("safePolicyWarningDatas",
242                                         mapper.writeValueAsString(commonClassDao.getDataByColumn(SafePolicyWarning.class, "name")));
243                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
244                         JSONObject j = new JSONObject(msg);
245                         response.getWriter().write(j.toString());
246                 } catch (Exception e) {
247                         LOGGER.error("Exception Occured"+e);
248                 }
249         }
250
251         @RequestMapping(value = { "/get_SafePolicyWarningData" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
252         public void getSafePolicyWarningeEntityData(HttpServletResponse response) {
253                 try {
254                         Map<String, Object> model = new HashMap<>();
255                         ObjectMapper mapper = new ObjectMapper();
256                         model.put("safePolicyWarningDatas",
257                                         mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)));
258                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
259                         JSONObject j = new JSONObject(msg);
260             response.addHeader("successMapKey", "success"); 
261             response.addHeader(operation, "getDictionary");
262                         response.getWriter().write(j.toString());
263                 } catch (Exception e) {
264                         LOGGER.error(e);
265             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
266             response.addHeader("error", "dictionaryDBQuery");
267                 }
268         }
269
270         @RequestMapping(value = { "/sp_dictionary/save_safePolicyWarning" }, method = {RequestMethod.POST })
271         public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
272                 try {
273                         boolean duplicateflag = false;
274             boolean isFakeUpdate = false;
275             boolean fromAPI = false;
276             if (request.getParameter(apiflag)!=null && ("api").equalsIgnoreCase(request.getParameter(apiflag))) {
277                 fromAPI = true;
278             }
279                         ObjectMapper mapper = new ObjectMapper();
280                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
281                         JsonNode root = mapper.readTree(request.getReader());
282                         SafePolicyWarning safePolicyWarning;
283             if (fromAPI) {
284                 safePolicyWarning = mapper.readValue(root.get("dictionaryFields").toString(), SafePolicyWarning.class);
285                 
286                 //check if update operation or create, get id for data to be updated and update attributeData
287                 if (("update").equals(request.getParameter(operation))) {
288                     List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class);
289                     SafePolicyWarning data = (SafePolicyWarning) duplicateData.get(0);
290                     int id = data.getId();
291                     
292                     if(id==0){
293                         isFakeUpdate=true;
294                         safePolicyWarning.setId(1);
295                     } else {
296                         safePolicyWarning.setId(id);
297                     } 
298                 }
299             } else {
300                 safePolicyWarning = mapper.readValue(root.get("safePolicyWarningData").toString(), SafePolicyWarning.class);
301             }
302
303                         if (safePolicyWarning.getId() == 0) {
304                                 List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class);
305                                 if(!duplicateData.isEmpty()){
306                                         duplicateflag = true;
307                                 }else{
308                                         commonClassDao.save(safePolicyWarning);
309                                 }
310                         } else {
311                                 if(!isFakeUpdate) {
312                                         commonClassDao.update(safePolicyWarning);
313                                 }
314                         }
315             String responseString = "";
316             if(duplicateflag){
317                 responseString = duplicateResponseString;
318             }else{
319                 responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class));
320             }
321             
322             if (fromAPI) {
323                 if (responseString!=null && !responseString.equals(duplicateResponseString)) {
324                     if(isFakeUpdate){
325                         responseString = "Exists";
326                     } else {
327                         responseString = "Success";
328                     }
329                 }
330                 ModelAndView result = new ModelAndView();
331                 result.setViewName(responseString);
332                 return result;
333             } else {
334                 response.setCharacterEncoding(utf8);
335                 response.setContentType(applicationJsonContentType);
336                 request.setCharacterEncoding(utf8);
337  
338                 PrintWriter out = response.getWriter();
339                 JSONObject j = new JSONObject("{safePolicyWarningDatas: " + responseString + "}");
340                 out.write(j.toString());
341                 return null;
342             }
343  
344         }catch (Exception e) {
345                 LOGGER.error(e);
346                         response.setCharacterEncoding(utf8);
347                         request.setCharacterEncoding(utf8);
348                         PrintWriter out = response.getWriter();
349                         out.write(PolicyUtils.CATCH_EXCEPTION);
350                 }
351                 return null;
352         }
353
354         @RequestMapping(value = { "/sp_dictionary/remove_SafePolicyWarning" }, method = {RequestMethod.POST })
355         public void removeSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
356                 try {
357                         ObjectMapper mapper = new ObjectMapper();
358                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
359                         JsonNode root = mapper.readTree(request.getReader());
360                         SafePolicyWarning safePolicyWarningData = mapper.readValue(root.get("data").toString(),
361                                         SafePolicyWarning.class);
362                         commonClassDao.delete(safePolicyWarningData);
363                         response.setCharacterEncoding(utf8);
364                         response.setContentType(applicationJsonContentType);
365                         request.setCharacterEncoding(utf8);
366
367                         PrintWriter out = response.getWriter();
368
369                         String responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class));
370                         JSONObject j = new JSONObject("{safePolicyWarningDatas: " + responseString + "}");
371                         out.write(j.toString());
372                 } catch (Exception e) {
373                         LOGGER.error(e);
374                         response.setCharacterEncoding(utf8);
375                         request.setCharacterEncoding(utf8);
376                         PrintWriter out = response.getWriter();
377                         out.write(PolicyUtils.CATCH_EXCEPTION);
378                 }
379         }
380
381 }