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