2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.scheduler;
40 import java.lang.reflect.Type;
41 import java.util.Collections;
42 import java.util.Date;
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;
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;
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;
75 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
77 private static final String PASSWORD_IS_EMPTY = "Password is Empty";
79 private static Client client = null;
81 private MultivaluedHashMap<String, Object> commonHeaders;
84 static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
86 public SchedulerRestInterface() {
92 private final ObjectMapper mapper = new ObjectMapper();
95 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
96 GsonBuilder builder = new GsonBuilder();
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());
106 gson = builder.create();
109 public void initRestClient() {
110 logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client");
114 final String username;
115 final String password;
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()) {
123 username = retrievedUsername;
126 /* Setting password based on properties */
127 String retrievedPassword = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
128 if (retrievedPassword.isEmpty()) {
129 password = StringUtils.EMPTY;
131 if (retrievedPassword.contains("OBF:")) {
132 password = Password.deobfuscate(retrievedPassword);
134 password = retrievedPassword;
138 if (StringUtils.isBlank(password)) {
139 throw new CredentialException(PASSWORD_IS_EMPTY);
141 } catch (Exception ex) {
142 logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex);
144 String authString = username + ":" + password;
145 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
146 String authStringEnc = new String(authEncBytes);
148 commonHeaders = new MultivaluedHashMap<String, Object>();
149 commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authStringEnc)));
152 if (!username.isEmpty()) {
154 client = HttpBasicClient.getClient();
157 client = HttpsBasicClient.getClient();
159 } catch (Exception e) {
160 logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client",e.getMessage());
163 logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized");
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 {
171 String methodName = "Get";
172 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
174 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
178 final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders).get();
180 int status = cres.getStatus();
181 restObject.setStatusCode(status);
183 if (cres != null && cres.getEntity() != null) {
185 String str = ((ResponseImpl) cres).readEntity(String.class);
186 if (t.getClass().getName().equals(String.class.getName())) {
190 t = (T) gson.fromJson(str, t.getClass());
193 } catch (Exception e) {
194 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
201 // t = (T) cres.readEntity(t.getClass());
204 restObject.set(null);
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);
216 logger.error(EELFLoggerDelegate.errorLogger, message, e);
217 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
225 @SuppressWarnings("unchecked")
226 public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) throws Exception {
228 String methodName = "Post";
229 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
230 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url);
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));
240 if (cres != null && cres.getEntity() != null) {
243 String str = ((ResponseImpl) cres).readEntity(String.class);
244 if (t.getClass().getName().equals(String.class.getName())) {
248 t = (T) gson.fromJson(str, t.getClass());
251 } catch (Exception e) {
252 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
254 // t = (T) cres.readEntity(t.getClass());
261 int status = cres.getStatus();
262 restObject.setStatusCode(status);
264 if (status >= 200 && status <= 299) {
265 String message = String.format(" REST api POST was successful!", methodName);
266 logger.debug(EELFLoggerDelegate.debugLogger, message);
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);
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());
289 public void logRequest(JSONObject requestDetails) {
292 @SuppressWarnings("unchecked")
293 public <T> void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject<T> restObject) {
295 String methodName = "Delete";
297 Response cres = null;
302 url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
304 cres = client.target(url).request().accept("application/json").headers(commonHeaders)
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));
310 int status = cres.getStatus();
311 restObject.setStatusCode(status);
312 if (cres.getEntity() != null) {
313 t = (T) cres.readEntity(t.getClass());
317 } catch (HttpClientErrorException e) {
318 logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception For the Delete",
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());
328 public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
329 return clazz.newInstance();