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