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