Merge "Model enhancement to support embedded JSON"
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / util / DictionaryUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2018-2019 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.util;
22
23 import com.fasterxml.jackson.databind.DeserializationFeature;
24 import com.fasterxml.jackson.databind.JsonNode;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import java.io.IOException;
27 import java.io.PrintWriter;
28 import java.util.HashMap;
29 import java.util.LinkedHashMap;
30 import java.util.List;
31 import java.util.Map;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.json.JSONObject;
37 import org.onap.policy.rest.dao.CommonClassDao;
38 import org.onap.policy.rest.jpa.Category;
39 import org.onap.policy.rest.jpa.Datatype;
40 import org.onap.policy.rest.jpa.UserInfo;
41 import org.onap.policy.xacml.api.XACMLErrorConstants;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.stereotype.Service;
44 import org.springframework.web.servlet.ModelAndView;
45
46 @Service
47 public class DictionaryUtils {
48
49     private static final Log LOGGER = LogFactory.getLog(DictionaryUtils.class);
50
51     private static String apiflag = "apiflag";
52     private static String operation = "operation";
53     private static String duplicateResponseString = "Duplicate";
54     private static String utf8 = "UTF-8";
55     private static String applicationJsonContentType = "application / json";
56
57     private static CommonClassDao commonClassDao;
58
59     private static DictionaryUtils dictionaryUtils;
60
61     public static synchronized DictionaryUtils getDictionaryUtils() {
62         return dictionaryUtils != null ? dictionaryUtils : new DictionaryUtils();
63     }
64
65     public static synchronized void setDictionaryUtils(DictionaryUtils dictionaryUtils) {
66         DictionaryUtils.dictionaryUtils = dictionaryUtils;
67     }
68
69     @Autowired
70     public DictionaryUtils(CommonClassDao commonClassDao) {
71         DictionaryUtils.commonClassDao = commonClassDao;
72     }
73
74     public DictionaryUtils() {
75         super();
76     }
77
78     public UserInfo getUserInfo(String loginId) {
79         return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId);
80     }
81
82     public boolean isRequestFromAPI(HttpServletRequest request) {
83         return request.getParameter(apiflag) != null
84                 && "api".equalsIgnoreCase(request.getParameter(apiflag));
85     }
86
87     public String appendKey(List<Object> objects, String key1, String appendValue) {
88         StringBuilder userValue = new StringBuilder();
89         int counter = 0;
90         for (Object attribute : objects) {
91             if (attribute instanceof LinkedHashMap<?, ?>) {
92                 String key = ((LinkedHashMap<?, ?>) attribute).get(key1).toString();
93                 if (counter > 0) {
94                     userValue.append(appendValue);
95                 }
96                 userValue.append(key);
97                 counter++;
98             }
99         }
100         return userValue.toString();
101     }
102
103     public String appendKeyValue(List<Object> objects, String append1, String append2) {
104         StringBuilder header = new StringBuilder();
105         int counter = 0;
106         for (Object attribute : objects) {
107             if (attribute instanceof LinkedHashMap<?, ?>) {
108                 String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString();
109                 String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString();
110                 if (counter > 0) {
111                     header.append(append1);
112                 }
113                 header.append(key).append(append2).append(value);
114                 counter++;
115             }
116         }
117         return header.toString();
118     }
119
120     public Datatype getDataType(String datatype) {
121         Datatype a = new Datatype();
122         if ("string".equalsIgnoreCase(datatype)) {
123             a.setId(26);
124         } else if ("integer".equalsIgnoreCase(datatype)) {
125             a.setId(12);
126         } else if ("boolean".equalsIgnoreCase(datatype)) {
127             a.setId(18);
128         } else if ("double".equalsIgnoreCase(datatype)) {
129             a.setId(25);
130         } else if ("user".equalsIgnoreCase(datatype)) {
131             a.setId(29);
132         }
133         return a;
134     }
135
136     public Category getCategory() {
137         return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource")
138                 .get(0);
139     }
140
141     public ModelAndView getResultForApi(String inResponseString) {
142         String responseString = inResponseString;
143         if (responseString != null && !duplicateResponseString.equals(responseString)) {
144             responseString = "Success";
145         }
146         ModelAndView result = new ModelAndView();
147         result.setViewName(responseString);
148         return result;
149     }
150
151     public void setResponseData(HttpServletResponse response, String key, String responseString)
152             throws IOException {
153         response.setCharacterEncoding(utf8);
154         response.setContentType(applicationJsonContentType);
155
156         PrintWriter out = response.getWriter();
157         JSONObject j = new JSONObject("{" + key + ":" + responseString + "}");
158         out.write(j.toString());
159     }
160
161     public void setErrorResponseData(HttpServletResponse response, Exception e) throws IOException {
162         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
163         response.setCharacterEncoding(utf8);
164         PrintWriter out = response.getWriter();
165         out.write(e.getMessage());
166     }
167
168     @SuppressWarnings("rawtypes")
169     public void getDataByEntity(HttpServletResponse response, String key, String value,
170             Class className) {
171         try {
172             Map<String, Object> model = new HashMap<>();
173             ObjectMapper mapper = new ObjectMapper();
174             model.put(key,
175                     mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value)));
176             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
177             JSONObject j = new JSONObject(msg);
178             response.getWriter().write(j.toString());
179         } catch (Exception e) {
180             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
181         }
182     }
183
184     @SuppressWarnings("rawtypes")
185     public void getData(HttpServletResponse response, String key, Class className) {
186         try {
187             Map<String, Object> model = new HashMap<>();
188             ObjectMapper mapper = new ObjectMapper();
189             model.put(key, mapper.writeValueAsString(commonClassDao.getData(className)));
190             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
191             JSONObject j = new JSONObject(msg);
192             response.addHeader("successMapKey", "success");
193             response.addHeader(operation, "getDictionary");
194             response.getWriter().write(j.toString());
195         } catch (Exception e) {
196             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
197             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
198             response.addHeader("error", "dictionaryDBQuery");
199         }
200     }
201
202     @SuppressWarnings("unchecked")
203     public void removeData(HttpServletRequest request, HttpServletResponse response, String key,
204             @SuppressWarnings("rawtypes") Class className) throws IOException {
205         try {
206             ObjectMapper mapper = new ObjectMapper();
207             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
208             JsonNode root = mapper.readTree(request.getReader());
209             commonClassDao
210                     .delete(mapper.readValue(root.get("data").toString(), className));
211             String responseString = mapper.writeValueAsString(commonClassDao.getData(className));
212             setResponseData(response, key, responseString);
213         } catch (Exception e) {
214             setErrorResponseData(response, e);
215         }
216     }
217
218 }