Commit includes ControlLoopPolicy API and bugfixes
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / controller / DescriptiveDictionaryController.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.HashMap;
25 import java.util.LinkedHashMap;
26 import java.util.List;
27 import java.util.Map;
28
29 import javax.servlet.http.HttpServletRequest;
30 import javax.servlet.http.HttpServletResponse;
31
32 import org.json.JSONObject;
33 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
34 import org.openecomp.policy.common.logging.flexlogger.Logger;
35 import org.openecomp.policy.pap.xacml.rest.adapters.GridData;
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.DescriptiveScope;
39 import org.openecomp.policy.rest.jpa.UserInfo;
40 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
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 DescriptiveDictionaryController {
53
54         private static final Logger LOGGER  = FlexLogger.getLogger(DescriptiveDictionaryController.class);
55         
56         private static CommonClassDao commonClassDao;
57         
58         @Autowired
59         public DescriptiveDictionaryController(CommonClassDao commonClassDao){
60                 DescriptiveDictionaryController.commonClassDao = commonClassDao;
61         }
62         
63         public DescriptiveDictionaryController(){}
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_DescriptiveScopeByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
71         public void getDescriptiveDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){
72                 try{
73                         Map<String, Object> model = new HashMap<>();
74                         ObjectMapper mapper = new ObjectMapper();
75                         model.put("descriptiveScopeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DescriptiveScope.class, "descriptiveScopeName")));
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(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
82                 }
83         }
84         
85         @RequestMapping(value={"/get_DescriptiveScope"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
86         public void getDescriptiveDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
87                 try{
88                         Map<String, Object> model = new HashMap<>();
89                         ObjectMapper mapper = new ObjectMapper();
90                         model.put("descriptiveScopeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.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(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
99             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
100             response.addHeader("error", "dictionaryDBQuery");
101                 }
102         }
103         
104         @RequestMapping(value={"/descriptive_dictionary/save_descriptive"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
105         public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
106                 try {
107                         boolean duplicateflag = false;
108             boolean isFakeUpdate = false;
109             boolean fromAPI = false;
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             DescriptiveScope descriptiveScope;
117             GridData data;
118             String userId = null;
119             if (fromAPI) {
120                 descriptiveScope = (DescriptiveScope)mapper.readValue(root.get("dictionaryFields").toString(), DescriptiveScope.class);
121                 data = (GridData)mapper.readValue(root.get("dictionaryFields").toString(), GridData.class);
122                 userId = "API";
123                 
124                 //check if update operation or create, get id for data to be updated and update attributeData
125                 if (request.getParameter("operation").equals("update")) {
126                         List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), "descriptiveScopeName", DescriptiveScope.class);
127                         int id = 0;
128                         DescriptiveScope dbdata = (DescriptiveScope) duplicateData.get(0);
129                         id = dbdata.getId();
130                         if(id==0){
131                                 isFakeUpdate=true;
132                                 descriptiveScope.setId(1);
133                         } else {
134                                 descriptiveScope.setId(id);
135                         }
136                         descriptiveScope.setUserCreatedBy(this.getUserInfo(userId));
137                 }
138             } else {
139                 descriptiveScope = (DescriptiveScope)mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), DescriptiveScope.class);
140                 data = (GridData)mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), GridData.class);
141                 userId = root.get("userid").textValue();
142             }
143                         String header = "";
144                         int counter = 0;
145                         if(data.getAttributes().size() > 0){
146                                 for(Object attribute : data.getAttributes()){
147                                         if(attribute instanceof LinkedHashMap<?, ?>){
148                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString();
149                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString();
150                                                 if(counter>0){
151                                                         header = header + "AND";
152                                                 }
153                                                 header = header + key + ":";
154                                                 header = header + value;
155                                                 counter ++;
156                                         }
157                                 }
158                         }
159                         descriptiveScope.setSearch(header);
160                         if(descriptiveScope.getId() == 0){
161                                 List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), "descriptiveScopeName", DescriptiveScope.class);
162                                 if(!duplicateData.isEmpty()){
163                                         duplicateflag = true;
164                                 }else{
165                                         descriptiveScope.setUserCreatedBy(this.getUserInfo(userId));
166                                         descriptiveScope.setUserModifiedBy(this.getUserInfo(userId));
167                                         commonClassDao.save(descriptiveScope);
168                                 }
169                         }else{
170                                 if(!isFakeUpdate){
171                                         descriptiveScope.setUserModifiedBy(this.getUserInfo(userId));
172                                         commonClassDao.update(descriptiveScope); 
173                                 }
174                         } 
175             String responseString = "";
176             if(duplicateflag){
177                 responseString = "Duplicate";
178             }else{
179                 responseString =  mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class));
180             }
181             
182             if (fromAPI) {
183                 if (responseString!=null && !responseString.equals("Duplicate")) {
184                         if(isFakeUpdate){
185                                 responseString = "Exists";
186                         } else {
187                                 responseString = "Success";
188                         }
189                 }
190                 ModelAndView result = new ModelAndView();
191                 result.setViewName(responseString);
192                 return result;
193             } else {
194                 response.setCharacterEncoding("UTF-8");
195                 response.setContentType("application / json");
196                 request.setCharacterEncoding("UTF-8");
197  
198                 PrintWriter out = response.getWriter();
199                 JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
200                 out.write(j.toString());
201                 return null;
202             }
203  
204         }catch (Exception e){
205                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
206                         response.setCharacterEncoding("UTF-8");
207                         request.setCharacterEncoding("UTF-8");
208                         PrintWriter out = response.getWriter();
209                         out.write(e.getMessage());
210                 }
211                 return null;
212         }
213
214         @RequestMapping(value={"/descriptive_dictionary/remove_descriptiveScope"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
215         public ModelAndView removeDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception {
216                 try{
217                         ObjectMapper mapper = new ObjectMapper();
218                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
219                         JsonNode root = mapper.readTree(request.getReader());
220                         DescriptiveScope descriptiveScope = (DescriptiveScope)mapper.readValue(root.get("data").toString(), DescriptiveScope.class);
221                         commonClassDao.delete(descriptiveScope);
222                         response.setCharacterEncoding("UTF-8");
223                         response.setContentType("application / json");
224                         request.setCharacterEncoding("UTF-8");
225
226                         PrintWriter out = response.getWriter();
227
228                         String responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class));
229                         JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
230                         out.write(j.toString());
231
232                         return null;
233                 }
234                 catch (Exception e){
235                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
236                         response.setCharacterEncoding("UTF-8");
237                         request.setCharacterEncoding("UTF-8");
238                         PrintWriter out = response.getWriter();
239                         out.write(e.getMessage());
240                 }
241                 return null;
242         }
243 }
244