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