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