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