Merge changes I3845ca4f,I7ae1ad11
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / controller / DictionaryController.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.IOException;
24 import java.io.PrintWriter;
25 import java.util.ArrayList;
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.apache.commons.logging.Log;
36 import org.apache.commons.logging.LogFactory;
37 import org.json.JSONObject;
38 import org.onap.policy.pap.xacml.rest.util.JsonMessage;
39 import org.onap.policy.rest.dao.CommonClassDao;
40 import org.onap.policy.rest.jpa.Attribute;
41 import org.onap.policy.rest.jpa.Category;
42 import org.onap.policy.rest.jpa.Datatype;
43 import org.onap.policy.rest.jpa.OnapName;
44 import org.onap.policy.rest.jpa.UserInfo;
45 import org.onap.policy.xacml.api.XACMLErrorConstants;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.http.MediaType;
48 import org.springframework.stereotype.Controller;
49 import org.springframework.web.bind.annotation.RequestMapping;
50 import org.springframework.web.bind.annotation.RequestMethod;
51 import org.springframework.web.servlet.ModelAndView;
52
53 import com.fasterxml.jackson.databind.DeserializationFeature;
54 import com.fasterxml.jackson.databind.JsonNode;
55 import com.fasterxml.jackson.databind.ObjectMapper;
56
57 @Controller
58 public class DictionaryController {
59         
60         private static final Log LOGGER = LogFactory.getLog(DictionaryController.class);
61
62         private static CommonClassDao commonClassDao;
63         private static String xacmlId = "xacmlId";
64         private static String apiflag = "apiflag";
65         private static String operation = "operation";
66         private static String dictionaryFields ="dictionaryFields";
67         private static String duplicateResponseString = "Duplicate";
68         private static String utf8 = "UTF-8";
69         private static String applicationJsonContentType = "application / json";
70         private static String onapName = "onapName";
71         @Autowired
72         public DictionaryController(CommonClassDao commonClassDao){
73                 DictionaryController.commonClassDao = commonClassDao;
74         }
75         /*
76          * This is an empty constructor
77          */
78         public DictionaryController(){}
79         
80         public UserInfo getUserInfo(String loginId){
81                 return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId);
82         }
83         
84         
85         public Category getCategory(){
86                 List<Object> list = commonClassDao.getData(Category.class);
87                 for (int i = 0; i < list.size() ; i++) {
88                         Category value = (Category) list.get(i);
89                         if (("resource").equals(value.getShortName())) {
90                                 return value;
91                         }
92                 }
93                 return null;    
94         }
95
96         @RequestMapping(value={"/get_AttributeDatabyAttributeName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
97         public void getAttributeDictionaryEntityDatabyAttributeName(HttpServletResponse response){
98                 try{
99                         Map<String, Object> model = new HashMap<>();
100                         ObjectMapper mapper = new ObjectMapper();
101                         model.put("attributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(Attribute.class, xacmlId)));
102                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
103                         JSONObject j = new JSONObject(msg);
104                         response.getWriter().write(j.toString());
105                 }
106                 catch (Exception e){
107                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
108                 }
109         }
110         
111         //Attribute Dictionary
112         @RequestMapping(value="/get_AttributeData", method= RequestMethod.GET , produces=MediaType.APPLICATION_JSON_VALUE)
113         public void getAttributeDictionaryEntityData(HttpServletResponse response){
114                 try{
115                         Map<String, Object> model = new HashMap<>();
116                         ObjectMapper mapper = new ObjectMapper();
117                         model.put("attributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(Attribute.class)));
118                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
119                         JSONObject j = new JSONObject(msg);
120             response.addHeader("successMapKey", "success"); 
121             response.addHeader(operation, "getDictionary");
122                         response.getWriter().write(j.toString());
123                 }
124                 catch (Exception e){
125             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
126             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
127             response.addHeader("error", "dictionaryDBQuery");
128                 }
129         }
130         
131         @RequestMapping(value={"/attribute_dictionary/save_attribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
132         public ModelAndView saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
133                 try {
134                         boolean duplicateflag = false;
135             boolean isFakeUpdate = false;
136             boolean fromAPI = false;
137             if (request.getParameter(apiflag)!=null && ("api").equalsIgnoreCase(request.getParameter(apiflag))) {
138                 fromAPI = true;
139             }
140                         ObjectMapper mapper = new ObjectMapper();
141                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
142                         JsonNode root = mapper.readTree(request.getReader());
143             Attribute attributeData = null;
144             AttributeValues attributeValueData = null;
145             String userId = null;
146             if (fromAPI) {
147                 attributeData = (Attribute)mapper.readValue(root.get(dictionaryFields).toString(), Attribute.class);
148                 attributeValueData = (AttributeValues)mapper.readValue(root.get(dictionaryFields).toString(), AttributeValues.class);
149                 userId = "API";
150                 
151                 //check if update operation or create, get id for data to be updated and update attributeData
152                 if (("update").equals(request.getParameter(operation))) {
153                         List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class);
154                         Attribute data = (Attribute) duplicateData.get(0);
155                         int id = data.getId();
156                         if(id==0){
157                                 isFakeUpdate=true;
158                                 attributeData.setId(1);
159                         } else {
160                                 attributeData.setId(id);
161                         }
162                         attributeData.setUserCreatedBy(this.getUserInfo(userId));
163                 }
164             } else {
165                 attributeData = (Attribute)mapper.readValue(root.get("attributeDictionaryData").toString(), Attribute.class);
166                 attributeValueData = (AttributeValues)mapper.readValue(root.get("attributeDictionaryData").toString(), AttributeValues.class);
167                 userId = root.get("userid").textValue();
168             }
169                         String userValue = "";
170                         int counter = 0;
171                         if(!attributeValueData.getUserDataTypeValues().isEmpty()){
172                                 for(Object attribute : attributeValueData.getUserDataTypeValues()){
173                                         if(attribute instanceof LinkedHashMap<?, ?>){
174                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("attributeValues").toString();
175                                                 if(counter>0){
176                                                         userValue = userValue + ",";
177                                                 }
178                                                 userValue = userValue + key ;
179                                                 counter ++;
180                                         }
181                                 }
182                         }
183                         attributeData.setAttributeValue(userValue);
184                         if(attributeData.getDatatypeBean().getShortName() != null){
185                                 String datatype = attributeData.getDatatypeBean().getShortName();
186                                 Datatype a = new Datatype();
187                                 if(("string").equalsIgnoreCase(datatype)){
188                                         a.setId(26);    
189                                 }else if(("integer").equalsIgnoreCase(datatype)){
190                                         a.setId(12);    
191                                 }else if(("boolean").equalsIgnoreCase(datatype)){
192                                         a.setId(18);    
193                                 }else if(("double").equalsIgnoreCase(datatype)){
194                                         a.setId(25);    
195                                 }else if(("user").equalsIgnoreCase(datatype)){
196                                         a.setId(29);    
197                                 }
198                                 attributeData.setDatatypeBean(a);
199                         }
200                         if(attributeData.getId() == 0){
201                                 List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class);
202                                 if(!duplicateData.isEmpty()){
203                                         duplicateflag = true;
204                                 }else{
205                                         attributeData.setCategoryBean(this.getCategory());
206                                         attributeData.setUserCreatedBy(this.getUserInfo(userId));
207                                         attributeData.setUserModifiedBy(this.getUserInfo(userId));
208                                         commonClassDao.save(attributeData);
209                                 }
210                         }else{
211                                 if(!isFakeUpdate) {
212                                         attributeData.setUserModifiedBy(this.getUserInfo(userId));
213                                         attributeData.setModifiedDate(new Date());
214                                         commonClassDao.update(attributeData); 
215                                 }
216                         } 
217             String responseString = null;
218             if(duplicateflag) {
219                 responseString = duplicateResponseString;
220             } else {
221                 responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class));
222             }
223             
224             if (fromAPI) {
225                 if (responseString!=null && !(duplicateResponseString).equals(responseString)) {
226                     if(isFakeUpdate) {
227                         responseString = "Exists";
228                     } else {
229                         responseString = "Success";
230                     }
231                 }
232                 ModelAndView result = new ModelAndView();
233                 result.setViewName(responseString);
234                 return result;
235             } else {
236                 response.setCharacterEncoding(utf8);
237                 response.setContentType(applicationJsonContentType);
238                 request.setCharacterEncoding(utf8);
239  
240                 PrintWriter out = response.getWriter();
241                 JSONObject j = new JSONObject("{attributeDictionaryDatas: " + responseString + "}");
242                 out.write(j.toString());
243                 return null;
244             }
245         }catch (Exception e){
246                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
247                         response.setCharacterEncoding(utf8);
248                         request.setCharacterEncoding(utf8);
249                         PrintWriter out = response.getWriter();
250                         out.write(e.getMessage());
251                 }
252                 return null;
253         }
254
255         @RequestMapping(value={"/attribute_dictionary/remove_attribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
256         public ModelAndView removeAttributeDictionary(HttpServletRequest request, HttpServletResponse response)throws IOException {
257                 try{
258                         ObjectMapper mapper = new ObjectMapper();
259                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
260                         JsonNode root = mapper.readTree(request.getReader());
261                         Attribute attributeData = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class);
262                         commonClassDao.delete(attributeData);
263                         response.setCharacterEncoding(utf8);
264                         response.setContentType(applicationJsonContentType);
265                         request.setCharacterEncoding(utf8);
266
267                         PrintWriter out = response.getWriter();
268                         String responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class));
269                         JSONObject j = new JSONObject("{attributeDictionaryDatas: " + responseString + "}");
270                         out.write(j.toString());
271                         return null;
272                 }
273                 catch (Exception e){
274                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
275                         response.setCharacterEncoding(utf8);
276                         request.setCharacterEncoding(utf8);
277                         PrintWriter out = response.getWriter();
278                         out.write(e.getMessage());
279                 }
280                 return null;
281         }
282         
283         //OnapName Dictionary
284         @RequestMapping(value={"/get_OnapNameDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
285         public void getOnapNameDictionaryByNameEntityData(HttpServletResponse response){
286                 LOGGER.info("get_OnapNameDataByName is called");
287                 try{
288                         Map<String, Object> model = new HashMap<>();
289                         ObjectMapper mapper = new ObjectMapper();
290                         model.put("onapNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(OnapName.class, onapName)));
291                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
292                         JSONObject j = new JSONObject(msg);
293                         response.getWriter().write(j.toString());
294                 }
295                 catch (Exception e){
296                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
297                 }
298         }
299         
300         @RequestMapping(value={"/get_OnapNameData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
301         public void getOnapNameDictionaryEntityData(HttpServletResponse response){
302                 try{
303                         Map<String, Object> model = new HashMap<>();
304                         ObjectMapper mapper = new ObjectMapper();
305                         model.put("onapNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(OnapName.class)));
306                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
307                         JSONObject j = new JSONObject(msg);
308             response.addHeader("successMapKey", "success"); 
309             response.addHeader(operation, "getDictionary");
310                         response.getWriter().write(j.toString());
311                 }
312                 catch (Exception e){
313             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
314             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
315             response.addHeader("error", "dictionaryDBQuery");
316                 }
317         }
318
319         @RequestMapping(value={"/onap_dictionary/save_onapName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
320         public ModelAndView saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
321                 try {
322                         boolean duplicateflag = false;
323                         boolean isFakeUpdate = false;
324                         boolean fromAPI = false;
325                         if (request.getParameter(apiflag)!=null && ("api").equalsIgnoreCase(request.getParameter(apiflag))) {
326                                 fromAPI = true;
327                         }
328                         ObjectMapper mapper = new ObjectMapper();
329                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
330                         JsonNode root = mapper.readTree(request.getReader());
331                         OnapName onapData;
332                         String userId = null;
333                         if (fromAPI) {
334                                 onapData = (OnapName)mapper.readValue(root.get(dictionaryFields).toString(), OnapName.class);
335                                 userId = "API";
336
337                                 //check if update operation or create, get id for data to be updated
338                                 if (("update").equals(request.getParameter(operation))) {
339                                         List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(onapData.getOnapName(), onapName, OnapName.class);
340                                         OnapName data = (OnapName) duplicateData.get(0);
341                                         int id = data.getId();
342                                         if(id==0){
343                                                 isFakeUpdate=true;
344                                                 onapData.setId(1);
345                                         } else {
346                                                 onapData.setId(id);
347                                         }
348                                         onapData.setUserCreatedBy(this.getUserInfo(userId));
349                                 }
350                         } else {
351                                 onapData = (OnapName)mapper.readValue(root.get("onapNameDictionaryData").toString(), OnapName.class);
352                                 userId = root.get("userid").textValue();
353                         }
354                         if(onapData.getId() == 0){
355                                 List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(onapData.getOnapName(), onapName, OnapName.class);
356                                 if(!duplicateData.isEmpty()){
357                                         duplicateflag = true;
358                                 }else{
359                                         onapData.setUserCreatedBy(getUserInfo(userId));
360                                         onapData.setUserModifiedBy(getUserInfo(userId));
361                                         commonClassDao.save(onapData);
362                                 }
363                         }else{
364                                 if(!isFakeUpdate){
365                                         onapData.setUserModifiedBy(this.getUserInfo(userId));
366                                         onapData.setModifiedDate(new Date());
367                                         commonClassDao.update(onapData);
368                                 }
369                         } 
370                         String responseString = null;
371                         if(duplicateflag) {
372                                 responseString = duplicateResponseString;
373                         } else {
374                                 responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class));
375                         }
376                         if (fromAPI) {
377                                 if (responseString!=null && !(duplicateResponseString).equals(responseString)) {
378                                         if(isFakeUpdate){
379                                                 responseString = "Exists";
380                                         } else {
381                                                 responseString = "Success";
382                                         }
383                                 }
384
385                                 ModelAndView result = new ModelAndView();
386                                 result.setViewName(responseString);
387                                 return result;
388                         } else {
389                                 response.setCharacterEncoding(utf8);
390                                 response.setContentType(applicationJsonContentType);
391                                 request.setCharacterEncoding(utf8);
392
393                                 PrintWriter out = response.getWriter();
394                                 JSONObject j = new JSONObject("{onapNameDictionaryDatas: " + responseString + "}");
395                                 out.write(j.toString());
396                                 return null;
397                         }
398                 }catch (Exception e){
399                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
400                         response.setCharacterEncoding(utf8);
401                         request.setCharacterEncoding(utf8);
402                         PrintWriter out = response.getWriter();
403                         out.write(e.getMessage());
404                 }
405                 return null;
406         }
407
408         @RequestMapping(value={"/onap_dictionary/remove_onap"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
409         public ModelAndView removeOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
410                 try{
411                         ObjectMapper mapper = new ObjectMapper();
412                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
413                         JsonNode root = mapper.readTree(request.getReader());
414                         OnapName onapData = (OnapName)mapper.readValue(root.get("data").toString(), OnapName.class);
415                         commonClassDao.delete(onapData);
416                         response.setCharacterEncoding(utf8);
417                         response.setContentType(applicationJsonContentType);
418                         request.setCharacterEncoding(utf8);
419
420                         PrintWriter out = response.getWriter();
421
422                         String responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class));
423                         JSONObject j = new JSONObject("{onapNameDictionaryDatas: " + responseString + "}");
424                         out.write(j.toString());
425
426                         return null;
427                 }
428                 catch (Exception e){
429                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
430                         response.setCharacterEncoding(utf8);
431                         request.setCharacterEncoding(utf8);
432                         PrintWriter out = response.getWriter();
433                         out.write(e.getMessage());
434                 }
435                 return null;
436         }
437
438 }
439
440 class AttributeValues{
441         private List<Object> userDataTypeValues;
442
443         public List<Object> getUserDataTypeValues() {
444                 return userDataTypeValues;
445         }
446
447         public void setUserDataTypeValues(List<Object> userDataTypeValues) {
448                 this.userDataTypeValues = userDataTypeValues;
449         }
450 }
451