[POLICY-73] replace openecomp for policy-engine
[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 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.PrintWriter;
24 import java.util.Date;
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.onap.policy.common.logging.flexlogger.FlexLogger;
35 import org.onap.policy.common.logging.flexlogger.Logger;
36 import org.onap.policy.pap.xacml.rest.adapters.GridData;
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.DescriptiveScope;
40 import org.onap.policy.rest.jpa.UserInfo;
41 import org.onap.policy.xacml.api.XACMLErrorConstants;
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 DescriptiveDictionaryController {
54
55         private static final Logger LOGGER  = FlexLogger.getLogger(DescriptiveDictionaryController.class);
56         
57         private static CommonClassDao commonClassDao;
58         
59         @Autowired
60         public DescriptiveDictionaryController(CommonClassDao commonClassDao){
61                 DescriptiveDictionaryController.commonClassDao = commonClassDao;
62         }
63         
64         public DescriptiveDictionaryController(){}
65         
66         public UserInfo getUserInfo(String loginId){
67                 UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId);
68                 return name;    
69         }
70
71         @RequestMapping(value={"/get_DescriptiveScopeByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
72         public void getDescriptiveDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){
73                 try{
74                         Map<String, Object> model = new HashMap<>();
75                         ObjectMapper mapper = new ObjectMapper();
76                         model.put("descriptiveScopeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DescriptiveScope.class, "descriptiveScopeName")));
77                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
78                         JSONObject j = new JSONObject(msg);
79                         response.getWriter().write(j.toString());
80                 }
81                 catch (Exception e){
82                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
83                 }
84         }
85         
86         @RequestMapping(value={"/get_DescriptiveScope"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
87         public void getDescriptiveDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
88                 try{
89                         Map<String, Object> model = new HashMap<>();
90                         ObjectMapper mapper = new ObjectMapper();
91                         model.put("descriptiveScopeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)));
92                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
93                         JSONObject j = new JSONObject(msg);
94             response.addHeader("successMapKey", "success"); 
95             response.addHeader("operation", "getDictionary");
96                         response.getWriter().write(j.toString());
97                 }
98                 catch (Exception e){
99             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
100             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
101             response.addHeader("error", "dictionaryDBQuery");
102                 }
103         }
104         
105         @RequestMapping(value={"/descriptive_dictionary/save_descriptive"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
106         public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
107                 try {
108                         boolean duplicateflag = false;
109             boolean isFakeUpdate = false;
110             boolean fromAPI = false;
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             DescriptiveScope descriptiveScope;
118             GridData data;
119             String userId = null;
120             if (fromAPI) {
121                 descriptiveScope = (DescriptiveScope)mapper.readValue(root.get("dictionaryFields").toString(), DescriptiveScope.class);
122                 data = (GridData)mapper.readValue(root.get("dictionaryFields").toString(), GridData.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(descriptiveScope.getScopeName(), "descriptiveScopeName", DescriptiveScope.class);
128                         int id = 0;
129                         DescriptiveScope dbdata = (DescriptiveScope) duplicateData.get(0);
130                         id = dbdata.getId();
131                         if(id==0){
132                                 isFakeUpdate=true;
133                                 descriptiveScope.setId(1);
134                         } else {
135                                 descriptiveScope.setId(id);
136                         }
137                         descriptiveScope.setUserCreatedBy(this.getUserInfo(userId));
138                 }
139             } else {
140                 descriptiveScope = (DescriptiveScope)mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), DescriptiveScope.class);
141                 data = (GridData)mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), GridData.class);
142                 userId = root.get("userid").textValue();
143             }
144                         String header = "";
145                         int counter = 0;
146                         if(data.getAttributes().size() > 0){
147                                 for(Object attribute : data.getAttributes()){
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 + "AND";
153                                                 }
154                                                 header = header + key + ":";
155                                                 header = header + value;
156                                                 counter ++;
157                                         }
158                                 }
159                         }
160                         descriptiveScope.setSearch(header);
161                         if(descriptiveScope.getId() == 0){
162                                 List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), "descriptiveScopeName", DescriptiveScope.class);
163                                 if(!duplicateData.isEmpty()){
164                                         duplicateflag = true;
165                                 }else{
166                                         descriptiveScope.setUserCreatedBy(this.getUserInfo(userId));
167                                         descriptiveScope.setUserModifiedBy(this.getUserInfo(userId));
168                                         commonClassDao.save(descriptiveScope);
169                                 }
170                         }else{
171                                 if(!isFakeUpdate){
172                                         descriptiveScope.setUserModifiedBy(this.getUserInfo(userId));
173                                         descriptiveScope.setModifiedDate(new Date());
174                                         commonClassDao.update(descriptiveScope); 
175                                 }
176                         } 
177             String responseString = "";
178             if(duplicateflag){
179                 responseString = "Duplicate";
180             }else{
181                 responseString =  mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.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                 ModelAndView result = new ModelAndView();
193                 result.setViewName(responseString);
194                 return result;
195             } else {
196                 response.setCharacterEncoding("UTF-8");
197                 response.setContentType("application / json");
198                 request.setCharacterEncoding("UTF-8");
199  
200                 PrintWriter out = response.getWriter();
201                 JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
202                 out.write(j.toString());
203                 return null;
204             }
205  
206         }catch (Exception e){
207                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
208                         response.setCharacterEncoding("UTF-8");
209                         request.setCharacterEncoding("UTF-8");
210                         PrintWriter out = response.getWriter();
211                         out.write(e.getMessage());
212                 }
213                 return null;
214         }
215
216         @RequestMapping(value={"/descriptive_dictionary/remove_descriptiveScope"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
217         public ModelAndView removeDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception {
218                 try{
219                         ObjectMapper mapper = new ObjectMapper();
220                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
221                         JsonNode root = mapper.readTree(request.getReader());
222                         DescriptiveScope descriptiveScope = (DescriptiveScope)mapper.readValue(root.get("data").toString(), DescriptiveScope.class);
223                         commonClassDao.delete(descriptiveScope);
224                         response.setCharacterEncoding("UTF-8");
225                         response.setContentType("application / json");
226                         request.setCharacterEncoding("UTF-8");
227
228                         PrintWriter out = response.getWriter();
229
230                         String responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class));
231                         JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
232                         out.write(j.toString());
233
234                         return null;
235                 }
236                 catch (Exception e){
237                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
238                         response.setCharacterEncoding("UTF-8");
239                         request.setCharacterEncoding("UTF-8");
240                         PrintWriter out = response.getWriter();
241                         out.write(e.getMessage());
242                 }
243                 return null;
244         }
245 }
246