Sonar fixes for Policy engine
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / controller / ActionPolicyDictionaryController.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.ArrayList;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.LinkedHashMap;
29 import java.util.List;
30 import java.util.Map;
31
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34
35 import org.json.JSONObject;
36 import org.onap.policy.common.logging.flexlogger.FlexLogger;
37 import org.onap.policy.common.logging.flexlogger.Logger;
38 import org.onap.policy.pap.xacml.rest.util.JsonMessage;
39 import org.onap.policy.rest.dao.CommonClassDao;
40 import org.onap.policy.rest.jpa.ActionPolicyDict;
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 ActionPolicyDictionaryController {
54
55         private static final Logger LOGGER  = FlexLogger.getLogger(ActionPolicyDictionaryController.class);
56
57         private static CommonClassDao commonClassDao;
58         private static String utf8 = "UTF-8";
59         private static String attributeName = "attributeName";
60         @Autowired
61         public ActionPolicyDictionaryController(CommonClassDao commonClassDao){
62                 ActionPolicyDictionaryController.commonClassDao = commonClassDao;
63         }
64         /*
65          * This is an empty constructor
66          */     
67         public ActionPolicyDictionaryController(){
68                 
69         }
70
71         public UserInfo getUserInfo(String loginId){
72                 return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId);
73         }
74
75         @RequestMapping(value={"/get_ActionPolicyDictDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
76         public void getActionEntitybyName(HttpServletResponse response){
77                 try{
78                         Map<String, Object> model = new HashMap<>();
79                         ObjectMapper mapper = new ObjectMapper();
80                         model.put("actionPolicyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ActionPolicyDict.class, attributeName)));
81                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
82                         JSONObject j = new JSONObject(msg);
83                         response.getWriter().write(j.toString());
84                 }
85                 catch (Exception e){
86                         LOGGER.error(e.getMessage(),e);
87                 }
88         }
89
90         @RequestMapping(value={"/get_ActionPolicyDictData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
91         public void getActionPolicyDictionaryEntityData(HttpServletResponse response){
92                 try{
93                         Map<String, Object> model = new HashMap<>();
94                         ObjectMapper mapper = new ObjectMapper();
95                         model.put("actionPolicyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ActionPolicyDict.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                 }
102                 catch (Exception e){
103                         LOGGER.error(e.getMessage(),e);
104                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
105                         response.addHeader("error", "dictionaryDBQuery");
106                 }
107         }
108
109         @RequestMapping(value={"/action_dictionary/save_ActionDict"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
110         public ModelAndView saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException   {
111                 try {
112                         boolean duplicateflag = false;
113                         boolean isFakeUpdate = false;
114                         boolean fromAPI = false;
115
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                         ActionPolicyDict actionPolicyDict = null;
123                         ActionAdapter adapter = null;
124                         String userId = null;
125
126                         if(fromAPI) {
127                                 actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("dictionaryFields").toString(), ActionPolicyDict.class);
128                                 adapter = (ActionAdapter)mapper.readValue(root.get("dictionaryFields").toString(), ActionAdapter.class);
129                                 userId = "API";
130
131                                 //check if update operation or create, get id for data to be updated and update attributeData
132                                 if (("update").equals(request.getParameter("operation"))) {
133                                         List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), attributeName, ActionPolicyDict.class);
134                                         ActionPolicyDict data = (ActionPolicyDict) duplicateData.get(0);
135                                         int id = data.getId();
136                                         if(id==0){
137                                                 isFakeUpdate=true;
138                                                 actionPolicyDict.setId(1);
139                                         } else {
140                                                 actionPolicyDict.setId(id);
141                                         }
142                                         actionPolicyDict.setUserCreatedBy(this.getUserInfo(userId));
143                                 }
144                         } else {
145                                 actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionPolicyDict.class);
146                                 adapter = mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionAdapter.class);
147                                 userId = root.get("userid").textValue();
148                         }
149                         String header = "";
150                         int counter = 0;
151                         if(!adapter.getHeaders().isEmpty()){
152                                 for(Object attribute : adapter.getHeaders()){
153                                         if(attribute instanceof LinkedHashMap<?, ?>){
154                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString();
155                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString();
156                                                 if(counter>0){
157                                                         header = header + ":";
158                                                 }
159                                                 header = header + key + "=";
160                                                 header = header + value;
161                                                 counter ++;
162                                         }
163                                 }
164                         }
165                         actionPolicyDict.setHeader(header);
166                         if(actionPolicyDict.getId() == 0){
167                                 List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), attributeName, ActionPolicyDict.class);
168                                 if(!duplicateData.isEmpty()){
169                                         duplicateflag = true;
170                                 }else{
171                                         actionPolicyDict.setUserCreatedBy(this.getUserInfo(userId));
172                                         actionPolicyDict.setUserModifiedBy(this.getUserInfo(userId));
173                                         commonClassDao.save(actionPolicyDict);
174                                 }
175                         }else{
176                                 if(!isFakeUpdate) {
177                                         actionPolicyDict.setUserModifiedBy(this.getUserInfo(userId));
178                                         actionPolicyDict.setModifiedDate(new Date());
179                                         commonClassDao.update(actionPolicyDict); 
180                                 }
181                         } 
182
183                         String responseString = null;
184                         if(duplicateflag) {
185                                 responseString = "Duplicate";
186                         } else {
187                                 responseString = mapper.writeValueAsString(commonClassDao.getData(ActionPolicyDict.class));
188                         }
189
190                         if (fromAPI) {
191                                 if (responseString!=null && !("Duplicate").equals(responseString)) {
192                                         if(isFakeUpdate) {
193                                                 responseString = "Exists";
194                                         } else {
195                                                 responseString = "Success";
196                                         }   
197                                 }
198
199                                 ModelAndView result = new ModelAndView();
200                                 result.setViewName(responseString);
201                                 return result;
202                         } else {
203                                 response.setCharacterEncoding(utf8);
204                                 response.setContentType("application / json");
205                                 request.setCharacterEncoding(utf8); 
206
207                                 PrintWriter out = response.getWriter();
208                                 JSONObject j = new JSONObject("{actionPolicyDictionaryDatas: " + responseString + "}");
209                                 out.write(j.toString());
210
211                                 return null;
212                         }
213                 }
214                 catch (Exception e){
215                         LOGGER.error(e);
216                         response.setCharacterEncoding(utf8);
217                         request.setCharacterEncoding(utf8);
218                         PrintWriter out = response.getWriter();
219                         out.write(e.getMessage());
220                 }
221                 return null;
222         }
223
224         @RequestMapping(value={"/action_dictionary/remove_actionPolicyDict"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
225         public ModelAndView removeActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
226                 try{
227                         ObjectMapper mapper = new ObjectMapper();
228                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
229                         JsonNode root = mapper.readTree(request.getReader());
230                         ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class);
231                         commonClassDao.delete(actionPolicyDict);
232                         response.setCharacterEncoding(utf8);
233                         response.setContentType("application / json");
234                         request.setCharacterEncoding(utf8);
235
236                         PrintWriter out = response.getWriter();
237
238                         String responseString = mapper.writeValueAsString(ActionPolicyDictionaryController.commonClassDao.getData(ActionPolicyDict.class));
239                         JSONObject j = new JSONObject("{actionPolicyDictionaryDatas: " + responseString + "}");
240                         out.write(j.toString());
241
242                         return null;
243                 }
244                 catch (Exception e){
245                         LOGGER.error(e);
246                         response.setCharacterEncoding(utf8);
247                         request.setCharacterEncoding(utf8);
248                         PrintWriter out = response.getWriter();
249                         out.write(e.getMessage());
250                 }
251                 return null;
252         }
253 }
254
255 class ActionAdapter{
256         private List<Object> headers;
257
258         public List<Object> getHeaders() {
259                 return headers;
260         }
261
262         public void setHeaders(List<Object> headers) {
263                 this.headers = headers;
264         }
265 }