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.util.Collections;
41 import java.util.Date;
43 import javax.security.auth.login.CredentialException;
44 import javax.ws.rs.client.Entity;
45 import javax.ws.rs.core.MediaType;
46 import javax.ws.rs.core.MultivaluedHashMap;
48 import org.apache.commons.codec.binary.Base64;
49 import org.apache.commons.lang.StringUtils;
50 import org.apache.cxf.jaxrs.client.WebClient;
51 import org.apache.cxf.jaxrs.impl.ResponseImpl;
52 import org.eclipse.jetty.util.security.Password;
53 import org.json.simple.JSONObject;
54 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
55 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
56 import org.onap.portalapp.portal.scheduler.restobjects.RestObject;
57 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
58 import org.springframework.http.HttpStatus;
59 import org.springframework.stereotype.Service;
60 import org.springframework.web.client.HttpClientErrorException;
62 import com.google.gson.Gson;
63 import com.google.gson.GsonBuilder;
64 import com.google.gson.JsonDeserializer;
66 import lombok.NoArgsConstructor;
68 @SuppressWarnings("MalformedFormatString")
71 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
72 private static final String APPLICATION_JSON = "application/json";
73 private static final String PASSWORD_IS_EMPTY = "Password is Empty";
74 private static final String HTTP_CLIENT_ERROR = " HttpClientErrorException: Exception For the POST ."
75 + " MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON";
77 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
78 private static WebClient client = null;
79 private static Gson gson = null;
81 private MultivaluedHashMap<String, String> commonHeaders;
83 private static void init() {
84 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
85 GsonBuilder builder = new GsonBuilder();
87 // Register an adapter to manage the date types as long values
88 builder.registerTypeAdapter(Date.class,
89 (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()));
91 gson = builder.create();
94 public void initRestClient(String URI) {
95 logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client");
99 final String username;
100 final String password;
102 /* Setting user name based on properties */
103 String retrievedUsername = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
104 if (retrievedUsername.isEmpty()) {
107 username = retrievedUsername;
110 /* Setting password based on properties */
111 String retrievedPassword = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
112 if (retrievedPassword.isEmpty()) {
113 password = StringUtils.EMPTY;
115 if (retrievedPassword.contains("OBF:")) {
116 password = Password.deobfuscate(retrievedPassword);
118 password = retrievedPassword;
122 if (StringUtils.isBlank(password)) {
123 throw new CredentialException(PASSWORD_IS_EMPTY);
125 } catch (Exception ex) {
126 logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex);
128 String authString = username + ":" + password;
129 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
130 String authStringEnc = new String(authEncBytes);
132 commonHeaders = new MultivaluedHashMap<>();
133 commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
136 // if (!username.isEmpty()) {
138 // client = HttpBasicClient.getClient();
141 // client = HttpsBasicClient.getClient();
143 // } catch (Exception e) {
144 // logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client",e.getMessage());
148 client = WebClient.create(URI);
149 client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
151 client.headers(commonHeaders);
153 logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized");
160 @SuppressWarnings("unchecked")
161 public <T> void Get(T t, String sourceId, String path,
162 org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject) {
164 String methodName = "Get";
165 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
167 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
172 //final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get();
173 final ResponseImpl cres = (ResponseImpl)client.get();
175 logger.debug(EELFLoggerDelegate.debugLogger, "The implemenation class of Response : ", cres.getClass().getName());
176 int status = cres.getStatus();
177 restObject.setStatusCode(status);
179 if (cres.getEntity() != null) {
181 String str = (cres).readEntity(String.class);
182 if (t.getClass().getName().equals(String.class.getName())) {
186 t = (T) gson.fromJson(str, t.getClass());
189 } catch (Exception e) {
190 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
194 restObject.set(null);
198 restObject.set(null);
202 } catch (HttpClientErrorException e) {
203 String message = String.format(
204 HTTP_CLIENT_ERROR, methodName, url);
205 logger.error(EELFLoggerDelegate.errorLogger, message, e);
206 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
207 } catch (Exception e) {
208 String message = String.format("Exception For the POST . MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName, url);
210 logger.error(EELFLoggerDelegate.errorLogger, message, e);
211 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
219 @SuppressWarnings("unchecked")
220 public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) {
222 String methodName = "Post";
223 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
224 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url);
230 // Change the content length
231 final ResponseImpl cres = (ResponseImpl)client.post(requestDetails.toJSONString());
233 if (cres != null && cres.getEntity() != null) {
236 String str = (cres).readEntity(String.class);
237 if (t.getClass().getName().equals(String.class.getName())) {
241 t = (T) gson.fromJson(str, t.getClass());
244 } catch (Exception e) {
245 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
249 restObject.set(null);
252 int status = cres != null ? cres.getStatus() : 0;
253 restObject.setStatusCode(status);
255 if (status >= 200 && status <= 299) {
256 String message = String.format(" REST api POST was successful!", methodName);
257 logger.debug(EELFLoggerDelegate.debugLogger, message);
260 String message = String.format(" FAILED with http status . MethodName: %APPLICATION_JSON, Status: %APPLICATION_JSON, Url: %APPLICATION_JSON",
261 methodName, status, url);
262 logger.debug(EELFLoggerDelegate.debugLogger, message);
265 } catch (HttpClientErrorException e) {
266 String message = String.format(
267 HTTP_CLIENT_ERROR, methodName, url);
268 logger.error(EELFLoggerDelegate.errorLogger, message, e);
269 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
270 } catch (Exception e) {
271 String message = String.format(
272 HTTP_CLIENT_ERROR, methodName, url);
273 logger.error(EELFLoggerDelegate.errorLogger, message, e);
274 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
280 public void logRequest(JSONObject requestDetails) {
281 throw new UnsupportedOperationException();