2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ===================================================================
10 * Unless otherwise specified, all software contained herein is licensed
11 * under the Apache License, Version 2.0 (the "License");
12 * you may not use this software except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * Unless otherwise specified, all documentation contained herein is licensed
24 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25 * you may not use this documentation except in compliance with the License.
26 * You may obtain a copy of the License at
28 * https://creativecommons.org/licenses/by/4.0/
30 * Unless required by applicable law or agreed to in writing, documentation
31 * distributed under the License is distributed on an "AS IS" BASIS,
32 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33 * See the License for the specific language governing permissions and
34 * limitations under the License.
36 * ============LICENSE_END============================================
41 package org.onap.portal.scheduler;
43 import com.google.gson.Gson;
44 import com.google.gson.GsonBuilder;
45 import com.google.gson.JsonDeserializer;
46 import java.util.Collections;
47 import java.util.Date;
48 import javax.security.auth.login.CredentialException;
49 import javax.ws.rs.client.Client;
50 import javax.ws.rs.client.Entity;
51 import javax.ws.rs.core.MediaType;
52 import javax.ws.rs.core.MultivaluedHashMap;
53 import javax.ws.rs.core.Response;
54 import lombok.NoArgsConstructor;
55 import org.apache.commons.codec.binary.Base64;
56 import org.apache.commons.lang.StringUtils;
57 import org.eclipse.jetty.util.security.Password;
58 import org.json.JSONObject;
59 import org.onap.portal.logging.format.EPAppMessagesEnum;
60 import org.onap.portal.logging.logic.EPLogUtil;
61 import org.onap.portal.scheduler.client.HttpBasicClient;
62 import org.onap.portal.scheduler.client.HttpsBasicClient;
63 import org.onap.portal.scheduler.restobjects.GetTimeSlotsRestObject;
64 import org.onap.portal.scheduler.restobjects.RestObject;
65 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
66 import org.springframework.http.HttpStatus;
67 import org.springframework.stereotype.Service;
68 import org.springframework.web.client.HttpClientErrorException;
70 @SuppressWarnings("MalformedFormatString")
73 public class SchedulerRestInterface {
75 private static final String APPLICATION_JSON = "application/json";
76 private static final String PASSWORD_IS_EMPTY = "Password is Empty";
77 private static final String HTTP_CLIENT_ERROR = " HttpClientErrorException: Exception For the POST ."
78 + " MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON";
80 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
81 private static Client client = null;
82 private static Gson gson = null;
84 private MultivaluedHashMap<String, Object> commonHeaders;
86 private static void init() {
87 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
88 GsonBuilder builder = new GsonBuilder();
90 // Register an adapter to manage the date types as long values
91 builder.registerTypeAdapter(Date.class,
92 (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()));
94 gson = builder.create();
97 public void initRestClient() {
98 logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client");
102 final String username;
103 final String password;
105 /* Setting user name based on properties */
106 String retrievedUsername = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
107 if (retrievedUsername.isEmpty()) {
110 username = retrievedUsername;
113 /* Setting password based on properties */
114 String retrievedPassword = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
115 if (retrievedPassword.isEmpty()) {
116 password = StringUtils.EMPTY;
118 if (retrievedPassword.contains("OBF:")) {
119 password = Password.deobfuscate(retrievedPassword);
121 password = retrievedPassword;
125 if (StringUtils.isBlank(password)) {
126 throw new CredentialException(PASSWORD_IS_EMPTY);
128 } catch (Exception ex) {
129 logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex);
131 String authString = username + ":" + password;
132 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
133 String authStringEnc = new String(authEncBytes);
135 commonHeaders = new MultivaluedHashMap<>();
136 commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
139 if (!username.isEmpty()) {
141 client = HttpBasicClient.getClient();
144 client = HttpsBasicClient.getClient();
146 } catch (Exception e) {
147 logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client", e.getMessage());
150 logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized");
154 public <T> void get(String t, String sourceId, String path, GetTimeSlotsRestObject<String> restObject) {
156 String methodName = "Get";
157 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
159 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
163 final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get();
165 int status = cres.getStatus();
166 restObject.setStatusCode(status);
168 if (cres.getEntity() != null) {
170 String str = (cres).readEntity(String.class);
171 if (t.getClass().getName().equals(String.class.getName())) {
174 t = gson.fromJson(str, t.getClass());
177 } catch (Exception e) {
178 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
182 restObject.setT(null);
186 restObject.setT(null);
190 } catch (HttpClientErrorException e) {
191 String message = String.format(
192 HTTP_CLIENT_ERROR, methodName, url);
193 logger.error(EELFLoggerDelegate.errorLogger, message, e);
194 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
195 } catch (Exception e) {
196 String message = String
197 .format("Exception For the POST . MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName,
200 logger.error(EELFLoggerDelegate.errorLogger, message, e);
201 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
209 public <T> void post(String t, JSONObject requestDetails, String path, RestObject<String> restObject) {
211 String methodName = "Post";
212 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
213 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url);
219 // Change the content length
220 final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders)
221 .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
223 if (cres != null && cres.getEntity() != null) {
226 String str = (cres).readEntity(String.class);
227 if (t.getClass().getName().equals(String.class.getName())) {
231 t = gson.fromJson(str, t.getClass());
234 } catch (Exception e) {
235 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
239 restObject.setT(null);
242 int status = cres != null ? cres.getStatus() : 0;
243 restObject.setStatusCode(status);
245 if (status >= 200 && status <= 299) {
246 String message = String.format(" REST api POST was successful!", methodName);
247 logger.debug(EELFLoggerDelegate.debugLogger, message);
250 String message = String.format(
251 " FAILED with http status . MethodName: %APPLICATION_JSON, Status: %APPLICATION_JSON, Url: %APPLICATION_JSON",
252 methodName, status, url);
253 logger.debug(EELFLoggerDelegate.debugLogger, message);
256 } catch (HttpClientErrorException e) {
257 String message = String.format(
258 HTTP_CLIENT_ERROR, methodName, url);
259 logger.error(EELFLoggerDelegate.errorLogger, message, e);
260 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
261 } catch (Exception e) {
262 String message = String.format(
263 HTTP_CLIENT_ERROR, methodName, url);
264 logger.error(EELFLoggerDelegate.errorLogger, message, e);
265 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
270 public <T> void delete(String t, JSONObject requestDetails, String sourceID, String path, RestObject<String> restObject) {
272 String methodName = "Delete";
279 url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
281 cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders)
282 .build("DELETE", Entity.entity(requestDetails, MediaType.APPLICATION_JSON)).invoke();
284 int status = cres.getStatus();
285 restObject.setStatusCode(status);
286 if (cres.getEntity() != null) {
287 t = cres.readEntity(t.getClass());
291 } catch (HttpClientErrorException e) {
292 logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception For the Delete",
294 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
295 } catch (Exception e) {
296 logger.error(EELFLoggerDelegate.errorLogger, "Exception For the Delete", methodName, url, e);
297 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());