1886b8b5d9d09e5e248cb57e4d8459fde01f2abc
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / scheduler / SchedulerRestInterface.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.portal.scheduler;
39
40 import java.lang.reflect.Type;
41 import java.util.Collections;
42 import java.util.Date;
43
44 import javax.security.auth.login.CredentialException;
45 import javax.ws.rs.client.Client;
46 import javax.ws.rs.client.Entity;
47 import javax.ws.rs.core.MediaType;
48 import javax.ws.rs.core.MultivaluedHashMap;
49 import javax.ws.rs.core.Response;
50
51 import org.apache.commons.codec.binary.Base64;
52 import org.apache.commons.lang.StringUtils;
53 import org.apache.cxf.jaxrs.impl.ResponseImpl;
54 import org.eclipse.jetty.util.security.Password;
55 import org.json.simple.JSONObject;
56 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
57 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
58 import org.onap.portalapp.portal.scheduler.client.HttpBasicClient;
59 import org.onap.portalapp.portal.scheduler.client.HttpsBasicClient;
60 import org.onap.portalapp.portal.scheduler.restobjects.RestObject;
61 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
62 import org.springframework.http.HttpStatus;
63 import org.springframework.stereotype.Service;
64 import org.springframework.web.client.HttpClientErrorException;
65
66 import com.fasterxml.jackson.databind.ObjectMapper;
67 import com.google.gson.Gson;
68 import com.google.gson.GsonBuilder;
69 import com.google.gson.JsonDeserializationContext;
70 import com.google.gson.JsonDeserializer;
71 import com.google.gson.JsonElement;
72 import com.google.gson.JsonParseException;
73
74 @Service
75 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
76
77         private static final String PASSWORD_IS_EMPTY = "Password is Empty";
78
79         private static Client client = null;
80
81         private MultivaluedHashMap<String, Object> commonHeaders;
82
83         /** The logger. */
84         static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
85
86         public SchedulerRestInterface() {
87                 super();
88         }
89
90         Gson gson = null;
91
92         private final ObjectMapper mapper = new ObjectMapper();
93
94         private void init() {
95                 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
96                 GsonBuilder builder = new GsonBuilder();
97
98                 // Register an adapter to manage the date types as long values
99                 builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
100                         public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
101                                         throws JsonParseException {
102                                 return new Date(json.getAsJsonPrimitive().getAsLong());
103                         }
104                 });
105
106                 gson = builder.create();
107         }
108
109         public void initRestClient() {
110                 logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client");
111
112                 init();
113
114                 final String username;
115                 final String password;
116
117                 String methodName = "initRestClient";
118                 /* Setting user name based on properties */
119                 String retrievedUsername = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
120                 if (retrievedUsername.isEmpty()) {
121                         username = "";
122                 } else {
123                         username = retrievedUsername;
124                 }
125
126                 /* Setting password based on properties */
127                 String retrievedPassword = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
128                 if (retrievedPassword.isEmpty()) {
129                         password = StringUtils.EMPTY;
130                 } else {
131                         if (retrievedPassword.contains("OBF:")) {
132                                 password = Password.deobfuscate(retrievedPassword);
133                         } else {
134                                 password = retrievedPassword;
135                         }
136                 }
137                 try {
138                         if (StringUtils.isBlank(password)) {
139                                 throw new CredentialException(PASSWORD_IS_EMPTY);
140                         }
141                 } catch (Exception ex) {
142                         logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex);
143                 }
144                 String authString = username + ":" + password;
145                 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
146                 String authStringEnc = new String(authEncBytes);
147
148                 commonHeaders = new MultivaluedHashMap<String, Object>();
149                 commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authStringEnc)));
150
151                 try {
152                         if (!username.isEmpty()) {
153
154                                 client = HttpBasicClient.getClient();
155                         } else {
156
157                                 client = HttpsBasicClient.getClient();
158                         }
159                 } catch (Exception e) {
160                         logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client",e.getMessage());
161
162                 }
163                 logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized");
164
165         }
166
167         @SuppressWarnings("unchecked")
168         public <T> void Get(T t, String sourceId, String path,
169                         org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject) throws Exception {
170
171                 String methodName = "Get";
172                 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
173
174                 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
175                 try {
176                         initRestClient();
177
178                         final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders).get();
179
180                         int status = cres.getStatus();
181                         restObject.setStatusCode(status);
182
183                         if (cres != null && cres.getEntity() != null) {
184                                 try {
185                                         String str = ((ResponseImpl) cres).readEntity(String.class);
186                                         if (t.getClass().getName().equals(String.class.getName())) {
187                                                 t = (T) str;
188
189                                         } else {
190                                                 t = (T) gson.fromJson(str, t.getClass());
191                                         }
192
193                                 } catch (Exception e) {
194                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
195                                 }
196                         } else {
197                                 t = null;
198                                 restObject.set(t);
199                         }
200
201                         // t = (T) cres.readEntity(t.getClass());
202
203                         if (t.equals("")) {
204                                 restObject.set(null);
205                         } else {
206                                 restObject.set(t);
207                         }
208                 } catch (HttpClientErrorException e) {
209                         String message = String.format(
210                                         " HttpClientErrorException: Exception For the POST  . MethodName: %s, Url: %s", methodName, url);
211                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
212                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
213                 } catch (Exception e) {
214                         String message = String.format("Exception For the POST . MethodName: %s, Url: %s", methodName, url);
215
216                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
217                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
218
219                         throw e;
220
221                 }
222
223         }
224
225         @SuppressWarnings("unchecked")
226         public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) throws Exception {
227
228                 String methodName = "Post";
229                 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
230                 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url);
231
232                 try {
233
234                         initRestClient();
235
236                         // Change the content length
237                         final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders)
238                                         .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
239
240                         if (cres != null && cres.getEntity() != null) {
241
242                                 try {
243                                         String str = ((ResponseImpl) cres).readEntity(String.class);
244                                         if (t.getClass().getName().equals(String.class.getName())) {
245                                                 t = (T) str;
246
247                                         } else {
248                                                 t = (T) gson.fromJson(str, t.getClass());
249                                         }
250
251                                 } catch (Exception e) {
252                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
253                                 }
254                                 // t = (T) cres.readEntity(t.getClass());
255                                 restObject.set(t);
256                         } else {
257                                 t = null;
258                                 restObject.set(t);
259                         }
260
261                         int status = cres.getStatus();
262                         restObject.setStatusCode(status);
263
264                         if (status >= 200 && status <= 299) {
265                                 String message = String.format(" REST api POST was successful!", methodName);
266                                 logger.debug(EELFLoggerDelegate.debugLogger, message);
267
268                         } else {
269                                 String message = String.format(" FAILED with http status  . MethodName: %s, Status: %s, Url: %s",
270                                                 methodName, status, url);
271                                 logger.debug(EELFLoggerDelegate.debugLogger, message);
272                         }
273
274                 } catch (HttpClientErrorException e) {
275                         String message = String.format(
276                                         " HttpClientErrorException: Exception For the POST  . MethodName: %s, Url: %s", methodName, url);
277                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
278                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
279                 } catch (Exception e) {
280                         String message = String.format(
281                                         " HttpClientErrorException: Exception For the POST  . MethodName: %s, Url: %s", methodName, url);
282                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
283                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
284                         throw e;
285                 }
286         }
287
288         @Override
289         public void logRequest(JSONObject requestDetails) {
290         }
291
292         @SuppressWarnings("unchecked")
293         public <T> void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject<T> restObject) {
294
295                 String methodName = "Delete";
296                 String url = "";
297                 Response cres = null;
298
299                 try {
300                         initRestClient();
301
302                         url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
303
304                         cres = client.target(url).request().accept("application/json").headers(commonHeaders)
305                                         // .entity(r)
306                                         .build("DELETE", Entity.entity(requestDetails, MediaType.APPLICATION_JSON)).invoke();
307                         // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON));
308                         // .delete(Entity.entity(r, MediaType.APPLICATION_JSON));
309
310                         int status = cres.getStatus();
311                         restObject.setStatusCode(status);
312                         if (cres.getEntity() != null) {
313                                 t = (T) cres.readEntity(t.getClass());
314                                 restObject.set(t);
315                         }
316
317                 } catch (HttpClientErrorException e) {
318                         logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception For the Delete",
319                                         methodName, url, e);
320                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
321                 } catch (Exception e) {
322                         logger.error(EELFLoggerDelegate.errorLogger, "Exception For the Delete", methodName, url, e);
323                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
324                         throw e;
325                 }
326         }
327
328         public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
329                 return clazz.newInstance();
330         }
331
332 }