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