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