b383518061b31c6899c08a144e33e86c079a84b3
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / controller / DescriptiveDictionaryController.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.io.UnsupportedEncodingException;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.LinkedHashMap;
29 import java.util.List;
30 import java.util.Map;
31
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34
35 import org.json.JSONObject;
36 import org.onap.policy.common.logging.flexlogger.FlexLogger;
37 import org.onap.policy.common.logging.flexlogger.Logger;
38 import org.onap.policy.pap.xacml.rest.adapters.GridData;
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.DescriptiveScope;
42 import org.onap.policy.rest.jpa.UserInfo;
43 import org.onap.policy.utils.PolicyUtils;
44 import org.onap.policy.xacml.api.XACMLErrorConstants;
45 import org.springframework.beans.factory.annotation.Autowired;
46 import org.springframework.http.MediaType;
47 import org.springframework.stereotype.Controller;
48 import org.springframework.web.bind.annotation.RequestMapping;
49 import org.springframework.web.servlet.ModelAndView;
50
51 import com.fasterxml.jackson.databind.DeserializationFeature;
52 import com.fasterxml.jackson.databind.JsonNode;
53 import com.fasterxml.jackson.databind.ObjectMapper;
54
55 @Controller
56 public class DescriptiveDictionaryController {
57
58         private static final Logger LOGGER  = FlexLogger.getLogger(DescriptiveDictionaryController.class);
59         
60         private static CommonClassDao commonClassDao;
61         
62         @Autowired
63         public DescriptiveDictionaryController(CommonClassDao commonClassDao){
64                 DescriptiveDictionaryController.commonClassDao = commonClassDao;
65         }
66         
67         public void setCommonClassDao(CommonClassDao commonClassDao){
68                 DescriptiveDictionaryController.commonClassDao = commonClassDao;
69         }
70         
71         public DescriptiveDictionaryController(){
72                 //Empty Constructor
73         }
74         
75         public UserInfo getUserInfo(String loginId){
76                 return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId);
77         }
78
79         @RequestMapping(value={"/get_DescriptiveScopeByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
80         public void getDescriptiveDictionaryByNameEntityData(HttpServletResponse response){
81                 try{
82                         Map<String, Object> model = new HashMap<>();
83                         ObjectMapper mapper = new ObjectMapper();
84                         model.put("descriptiveScopeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DescriptiveScope.class, "descriptiveScopeName")));
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(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
91                 }
92         }
93         
94         @RequestMapping(value={"/get_DescriptiveScope"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
95         public void getDescriptiveDictionaryEntityData(HttpServletResponse response){
96                 try{
97                         Map<String, Object> model = new HashMap<>();
98                         ObjectMapper mapper = new ObjectMapper();
99                         model.put("descriptiveScopeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.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(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
108             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
109             response.addHeader("error", "dictionaryDBQuery");
110                 }
111         }
112         
113         @RequestMapping(value={"/descriptive_dictionary/save_descriptive"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
114         public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response)throws UnsupportedEncodingException, IOException{
115                 try {
116                         boolean duplicateflag = false;
117             boolean isFakeUpdate = false;
118             boolean fromAPI = false;
119             if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) {
120                 fromAPI = true;
121             }
122                         ObjectMapper mapper = new ObjectMapper();
123                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
124                         JsonNode root = mapper.readTree(request.getReader());
125             DescriptiveScope descriptiveScope;
126             GridData data;
127             String userId = null;
128             if (fromAPI) {
129                 descriptiveScope = mapper.readValue(root.get("dictionaryFields").toString(), DescriptiveScope.class);
130                 data = mapper.readValue(root.get("dictionaryFields").toString(), GridData.class);
131                 userId = "API";
132                 
133                 //check if update operation or create, get id for data to be updated and update attributeData
134                 if (request.getParameter("operation").equals("update")) {
135                         List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), "descriptiveScopeName", DescriptiveScope.class);
136                         int id = 0;
137                         DescriptiveScope dbdata = (DescriptiveScope) duplicateData.get(0);
138                         id = dbdata.getId();
139                         if(id==0){
140                                 isFakeUpdate=true;
141                                 descriptiveScope.setId(1);
142                         } else {
143                                 descriptiveScope.setId(id);
144                         }
145                         descriptiveScope.setUserCreatedBy(this.getUserInfo(userId));
146                 }
147             } else {
148                 descriptiveScope = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), DescriptiveScope.class);
149                 data = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), GridData.class);
150                 userId = root.get("userid").textValue();
151             }
152                         StringBuilder header = new StringBuilder();
153                         int counter = 0;
154                         if(!data.getAttributes().isEmpty()){
155                                 for(Object attribute : data.getAttributes()){
156                                         if(attribute instanceof LinkedHashMap<?, ?>){
157                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString();
158                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString();
159                                                 if(counter>0){
160                                                         header.append("AND");
161                                                 }
162                                                 header.append(key).append(":").append(value);
163                                                 counter ++;
164                                         }
165                                 }
166                         }
167                         descriptiveScope.setSearch(header.toString());
168                         if(descriptiveScope.getId() == 0){
169                                 List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), "descriptiveScopeName", DescriptiveScope.class);
170                                 if(!duplicateData.isEmpty()){
171                                         duplicateflag = true;
172                                 }else{
173                                         descriptiveScope.setUserCreatedBy(this.getUserInfo(userId));
174                                         descriptiveScope.setUserModifiedBy(this.getUserInfo(userId));
175                                         commonClassDao.save(descriptiveScope);
176                                 }
177                         }else{
178                                 if(!isFakeUpdate){
179                                         descriptiveScope.setUserModifiedBy(this.getUserInfo(userId));
180                                         descriptiveScope.setModifiedDate(new Date());
181                                         commonClassDao.update(descriptiveScope); 
182                                 }
183                         } 
184             String responseString = "";
185             if(duplicateflag){
186                 responseString = "Duplicate";
187             }else{
188                 responseString =  mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class));
189             }
190             
191             if (fromAPI) {
192                 if (responseString!=null && !responseString.equals("Duplicate")) {
193                         if(isFakeUpdate){
194                                 responseString = "Exists";
195                         } else {
196                                 responseString = "Success";
197                         }
198                 }
199                 ModelAndView result = new ModelAndView();
200                 result.setViewName(responseString);
201                 return result;
202             } else {
203                 response.setCharacterEncoding("UTF-8");
204                 response.setContentType("application / json");
205                 request.setCharacterEncoding("UTF-8");
206  
207                 PrintWriter out = response.getWriter();
208                 JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
209                 out.write(j.toString());
210                 return null;
211             }
212  
213         }catch (Exception e){
214                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
215                         response.setCharacterEncoding("UTF-8");
216                         request.setCharacterEncoding("UTF-8");
217                         PrintWriter out = response.getWriter();
218                         out.write(PolicyUtils.CATCH_EXCEPTION);
219                 }
220                 return null;
221         }
222
223         @RequestMapping(value={"/descriptive_dictionary/remove_descriptiveScope"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
224         public void removeDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
225                 try{
226                         ObjectMapper mapper = new ObjectMapper();
227                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
228                         JsonNode root = mapper.readTree(request.getReader());
229                         DescriptiveScope descriptiveScope = mapper.readValue(root.get("data").toString(), DescriptiveScope.class);
230                         commonClassDao.delete(descriptiveScope);
231                         response.setCharacterEncoding("UTF-8");
232                         response.setContentType("application / json");
233                         request.setCharacterEncoding("UTF-8");
234
235                         PrintWriter out = response.getWriter();
236
237                         String responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class));
238                         JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
239                         out.write(j.toString());
240                 }
241                 catch (Exception e){
242                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
243                         response.setCharacterEncoding("UTF-8");
244                         request.setCharacterEncoding("UTF-8");
245                         PrintWriter out = response.getWriter();
246                         out.write(PolicyUtils.CATCH_EXCEPTION);
247                 }
248         }
249 }
250