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