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