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");
157 @SuppressWarnings("unchecked")
158 public <T> void Get(T t, String sourceId, String path,
159 org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject) {
161 String methodName = "Get";
162 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
164 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
169 //final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get();
170 final ResponseImpl cres = (ResponseImpl)client.get();
172 logger.debug(EELFLoggerDelegate.debugLogger, "The implemenation class of Response : ", cres.getClass().getName());
173 int status = cres.getStatus();
174 restObject.setStatusCode(status);
176 if (cres.getEntity() != null) {
178 String str = (cres).readEntity(String.class);
179 if (t.getClass().isAssignableFrom(String.class)) {
183 t = (T) gson.fromJson(str, t.getClass());
186 } catch (Exception e) {
187 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
191 restObject.set(null);
195 restObject.set(null);
199 } catch (HttpClientErrorException e) {
200 String message = String.format(
201 HTTP_CLIENT_ERROR, methodName, url);
202 logger.error(EELFLoggerDelegate.errorLogger, message, e);
203 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
204 } catch (Exception e) {
205 String message = String.format("Exception For the POST . MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName, url);
207 logger.error(EELFLoggerDelegate.errorLogger, message, e);
208 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
216 @SuppressWarnings("unchecked")
217 public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) {
219 String methodName = "Post";
220 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
221 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url);
227 // Change the content length
228 final ResponseImpl cres = (ResponseImpl)client.post(requestDetails.toJSONString());
230 if (cres != null && cres.getEntity() != null) {
233 String str = (cres).readEntity(String.class);
234 if (t.getClass().isAssignableFrom(String.class)) {
238 t = (T) gson.fromJson(str, t.getClass());
241 } catch (Exception e) {
242 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
246 restObject.set(null);
249 int status = cres != null ? cres.getStatus() : 0;
250 restObject.setStatusCode(status);
252 if (status >= 200 && status <= 299) {
253 String message = String.format(" REST api POST was successful!", methodName);
254 logger.debug(EELFLoggerDelegate.debugLogger, message);
257 String message = String.format(" FAILED with http status . MethodName: %APPLICATION_JSON, Status: %APPLICATION_JSON, Url: %APPLICATION_JSON",
258 methodName, status, url);
259 logger.debug(EELFLoggerDelegate.debugLogger, message);
262 } catch (HttpClientErrorException e) {
263 String message = String.format(
264 HTTP_CLIENT_ERROR, methodName, url);
265 logger.error(EELFLoggerDelegate.errorLogger, message, e);
266 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
267 } catch (Exception e) {
268 String message = String.format(
269 HTTP_CLIENT_ERROR, methodName, url);
270 logger.error(EELFLoggerDelegate.errorLogger, message, e);
271 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
277 public void logRequest(JSONObject requestDetails) {
278 throw new UnsupportedOperationException();