Merge "Sonar fix forONAP-PAP-REST critical sonar issues"
[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.io.UnsupportedEncodingException;
26 import java.util.Date;
27 import java.util.HashMap;
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.RiskType;
40 import org.onap.policy.rest.jpa.SafePolicyWarning;
41 import org.onap.policy.rest.jpa.UserInfo;
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         
59         @Autowired
60         public SafePolicyController(CommonClassDao commonClassDao){
61                 SafePolicyController.commonClassDao = commonClassDao;
62         }
63         
64         public SafePolicyController(){} 
65         
66         public UserInfo getUserInfo(String loginId){
67                 UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId);
68                 return name;    
69         }
70         
71         private static String DUPLICATE = "Duplicate";
72
73         @RequestMapping(value = { "/get_RiskTypeDataByName" }, method = {
74                         org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
75         public void getRiskTypeDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response) {
76                 try {
77                         Map<String, Object> model = new HashMap<>();
78                         ObjectMapper mapper = new ObjectMapper();
79                         model.put("riskTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(RiskType.class, "name")));
80                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
81                         JSONObject j = new JSONObject(msg);
82                         response.getWriter().write(j.toString());
83                 } catch (Exception e) {
84                         LOGGER.error("Exception Occured"+e);
85                 }
86         }
87
88         @RequestMapping(value = { "/get_RiskTypeData" }, method = {
89                         org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
90         public void getOnapNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response) {
91                 try {
92                         Map<String, Object> model = new HashMap<>();
93                         ObjectMapper mapper = new ObjectMapper();
94                         model.put("riskTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(RiskType.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                 } catch (Exception e) {
101             LOGGER.error(e);
102             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
103             response.addHeader("error", "dictionaryDBQuery");
104                 }
105         }
106
107         @RequestMapping(value = { "/sp_dictionary/save_riskType" }, method = {
108                         org.springframework.web.bind.annotation.RequestMethod.POST })
109         public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response)
110                         throws UnsupportedEncodingException, IOException {
111                 try {
112                         boolean duplicateflag = false;
113             boolean isFakeUpdate = false;
114             boolean fromAPI = false;
115             if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) {
116                 fromAPI = true;
117             }
118                         ObjectMapper mapper = new ObjectMapper();
119                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
120                         JsonNode root = mapper.readTree(request.getReader());
121             RiskType riskTypeData;
122             String userId = null;
123             if (fromAPI) {
124                 riskTypeData = (RiskType) mapper.readValue(root.get("dictionaryFields").toString(),
125                         RiskType.class);
126                 userId = "API";
127                 
128                 //check if update operation or create, get id for data to be updated and update attributeData
129                 if ("update".equalsIgnoreCase(request.getParameter("operation"))){
130                     List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class);
131                     int id = 0;
132                     RiskType data = (RiskType) duplicateData.get(0);
133                     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 = DUPLICATE;
168             }else{
169                 responseString = mapper.writeValueAsString(commonClassDao.getData(RiskType.class));
170             }
171             
172             if (fromAPI) {
173                 if (responseString!=null && !responseString.equals(DUPLICATE)) {
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("UTF-8");
185                 response.setContentType("application / json");
186                 request.setCharacterEncoding("UTF-8");
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("UTF-8");
196                         request.setCharacterEncoding("UTF-8");
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 UnsupportedEncodingException, 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("UTF-8");
214                         response.setContentType("application / json");
215                         request.setCharacterEncoding("UTF-8");
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("UTF-8");
227                         request.setCharacterEncoding("UTF-8");
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(HttpServletRequest request, 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(HttpServletRequest request, 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 UnsupportedEncodingException, IOException {
274                 try {
275                         boolean duplicateflag = false;
276             boolean isFakeUpdate = false;
277             boolean fromAPI = false;
278             if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) {
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 (request.getParameter("operation").equals("update")) {
291                     List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class);
292                     int id = 0;
293                     SafePolicyWarning data = (SafePolicyWarning) duplicateData.get(0);
294                     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 = DUPLICATE;
322             }else{
323                 responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class));
324             }
325             
326             if (fromAPI) {
327                 if (responseString!=null && !responseString.equals(DUPLICATE)) {
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("UTF-8");
339                 response.setContentType("application / json");
340                 request.setCharacterEncoding("UTF-8");
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("UTF-8");
351                         request.setCharacterEncoding("UTF-8");
352                         PrintWriter out = response.getWriter();
353                         out.write(e.getMessage());
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 UnsupportedEncodingException, 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("UTF-8");
370                         response.setContentType("application / json");
371                         request.setCharacterEncoding("UTF-8");
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                         System.out.println(e);
382                         response.setCharacterEncoding("UTF-8");
383                         request.setCharacterEncoding("UTF-8");
384                         PrintWriter out = response.getWriter();
385                         out.write(e.getMessage());
386                 }
387                 return null;
388         }
389
390 }