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