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