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