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