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 com.google.gson.Gson;
41 import com.google.gson.GsonBuilder;
42 import com.google.gson.JsonDeserializer;
43 import java.util.Collections;
44 import java.util.Date;
45 import javax.security.auth.login.CredentialException;
46 import javax.ws.rs.client.Client;
47 import javax.ws.rs.client.Entity;
48 import javax.ws.rs.core.MediaType;
49 import javax.ws.rs.core.MultivaluedHashMap;
50 import javax.ws.rs.core.Response;
51 import lombok.NoArgsConstructor;
52 import org.apache.commons.codec.binary.Base64;
53 import org.apache.commons.lang.StringUtils;
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 @SuppressWarnings("MalformedFormatString")
69 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
70 private static final String APPLICATION_JSON = "application/json";
71 private static final String PASSWORD_IS_EMPTY = "Password is Empty";
72 private static final String HTTP_CLIENT_ERROR = " HttpClientErrorException: Exception For the POST ."
73 + " MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON";
75 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
76 private static Client client = null;
77 private static Gson gson = null;
79 private MultivaluedHashMap<String, Object> commonHeaders;
81 private static void init() {
82 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
83 GsonBuilder builder = new GsonBuilder();
85 // Register an adapter to manage the date types as long values
86 builder.registerTypeAdapter(Date.class,
87 (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()));
89 gson = builder.create();
92 public void initRestClient() {
93 logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client");
97 final String username;
98 final String password;
100 /* Setting user name based on properties */
101 String retrievedUsername = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
102 if (retrievedUsername.isEmpty()) {
105 username = retrievedUsername;
108 /* Setting password based on properties */
109 String retrievedPassword = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
110 if (retrievedPassword.isEmpty()) {
111 password = StringUtils.EMPTY;
113 if (retrievedPassword.contains("OBF:")) {
114 password = Password.deobfuscate(retrievedPassword);
116 password = retrievedPassword;
120 if (StringUtils.isBlank(password)) {
121 throw new CredentialException(PASSWORD_IS_EMPTY);
123 } catch (Exception ex) {
124 logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex);
126 String authString = username + ":" + password;
127 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
128 String authStringEnc = new String(authEncBytes);
130 commonHeaders = new MultivaluedHashMap<>();
131 commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
134 if (!username.isEmpty()) {
136 client = HttpBasicClient.getClient();
139 client = HttpsBasicClient.getClient();
141 } catch (Exception e) {
142 logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client",e.getMessage());
145 logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized");
149 @SuppressWarnings("unchecked")
150 public <T> void Get(T t, String sourceId, String path,
151 org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject) {
153 String methodName = "Get";
154 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
156 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
160 final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get();
162 int status = cres.getStatus();
163 restObject.setStatusCode(status);
165 if (cres.getEntity() != null) {
167 String str = (cres).readEntity(String.class);
168 if (t.getClass().getName().equals(String.class.getName())) {
172 t = (T) gson.fromJson(str, t.getClass());
175 } catch (Exception e) {
176 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
180 restObject.set(null);
184 restObject.set(null);
188 } catch (HttpClientErrorException e) {
189 String message = String.format(
190 HTTP_CLIENT_ERROR, methodName, url);
191 logger.error(EELFLoggerDelegate.errorLogger, message, e);
192 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
193 } catch (Exception e) {
194 String message = String.format("Exception For the POST . MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName, url);
196 logger.error(EELFLoggerDelegate.errorLogger, message, e);
197 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
205 @SuppressWarnings("unchecked")
206 public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) {
208 String methodName = "Post";
209 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
210 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url);
216 // Change the content length
217 final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders)
218 .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
220 if (cres != null && cres.getEntity() != null) {
223 String str = (cres).readEntity(String.class);
224 if (t.getClass().getName().equals(String.class.getName())) {
228 t = (T) gson.fromJson(str, t.getClass());
231 } catch (Exception e) {
232 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
236 restObject.set(null);
239 int status = cres != null ? cres.getStatus() : 0;
240 restObject.setStatusCode(status);
242 if (status >= 200 && status <= 299) {
243 String message = String.format(" REST api POST was successful!", methodName);
244 logger.debug(EELFLoggerDelegate.debugLogger, message);
247 String message = String.format(" FAILED with http status . MethodName: %APPLICATION_JSON, Status: %APPLICATION_JSON, Url: %APPLICATION_JSON",
248 methodName, status, url);
249 logger.debug(EELFLoggerDelegate.debugLogger, message);
252 } catch (HttpClientErrorException e) {
253 String message = String.format(
254 HTTP_CLIENT_ERROR, methodName, url);
255 logger.error(EELFLoggerDelegate.errorLogger, message, e);
256 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
257 } catch (Exception e) {
258 String message = String.format(
259 HTTP_CLIENT_ERROR, methodName, url);
260 logger.error(EELFLoggerDelegate.errorLogger, message, e);
261 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
267 public void logRequest(JSONObject requestDetails) {
268 throw new UnsupportedOperationException();
271 @SuppressWarnings("unchecked")
272 public <T> void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject<T> restObject) {
274 String methodName = "Delete";
281 url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
283 cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders)
285 .build("DELETE", Entity.entity(requestDetails, MediaType.APPLICATION_JSON)).invoke();
287 int status = cres.getStatus();
288 restObject.setStatusCode(status);
289 if (cres.getEntity() != null) {
290 t = (T) cres.readEntity(t.getClass());
294 } catch (HttpClientErrorException e) {
295 logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception For the Delete",
297 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
298 } catch (Exception e) {
299 logger.error(EELFLoggerDelegate.errorLogger, "Exception For the Delete", methodName, url, e);
300 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());