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