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.core.MediaType;
45 import javax.ws.rs.core.MultivaluedHashMap;
47 import org.apache.commons.codec.binary.Base64;
48 import org.apache.commons.lang.StringUtils;
49 import org.apache.cxf.jaxrs.client.WebClient;
50 import org.apache.cxf.jaxrs.impl.ResponseImpl;
51 import org.eclipse.jetty.util.security.Password;
52 import org.json.simple.JSONObject;
53 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
54 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
55 import org.onap.portalapp.portal.scheduler.restobjects.RestObject;
56 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
57 import org.springframework.http.HttpStatus;
58 import org.springframework.stereotype.Service;
59 import org.springframework.web.client.HttpClientErrorException;
61 import com.google.gson.Gson;
62 import com.google.gson.GsonBuilder;
63 import com.google.gson.JsonDeserializer;
65 import lombok.NoArgsConstructor;
67 @SuppressWarnings("MalformedFormatString")
70 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
71 private static final String APPLICATION_JSON = "application/json";
72 private static final String PASSWORD_IS_EMPTY = "Password is Empty";
73 private static final String HTTP_CLIENT_ERROR = " HttpClientErrorException: Exception For the POST ."
74 + " MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON";
76 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
77 private static WebClient client = null;
78 private static Gson gson = null;
80 private MultivaluedHashMap<String, String> commonHeaders;
82 private static void init() {
83 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
84 GsonBuilder builder = new GsonBuilder();
86 // Register an adapter to manage the date types as long values
87 builder.registerTypeAdapter(Date.class,
88 (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()));
90 gson = builder.create();
93 public void initRestClient(String URI) {
94 logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client");
98 final String username;
99 final String password;
101 /* Setting user name based on properties */
102 String retrievedUsername = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
103 if (retrievedUsername.isEmpty()) {
106 username = retrievedUsername;
109 /* Setting password based on properties */
110 String retrievedPassword = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
111 if (retrievedPassword.isEmpty()) {
112 password = StringUtils.EMPTY;
114 if (retrievedPassword.contains("OBF:")) {
115 password = Password.deobfuscate(retrievedPassword);
117 password = retrievedPassword;
121 if (StringUtils.isBlank(password)) {
122 throw new CredentialException(PASSWORD_IS_EMPTY);
124 } catch (Exception ex) {
125 logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex);
127 String authString = username + ":" + password;
128 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
129 String authStringEnc = new String(authEncBytes);
131 commonHeaders = new MultivaluedHashMap<>();
132 commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
135 // if (!username.isEmpty()) {
137 // client = HttpBasicClient.getClient();
140 // client = HttpsBasicClient.getClient();
142 // } catch (Exception e) {
143 // logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client",e.getMessage());
147 client = WebClient.create(URI);
148 client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
150 client.headers(commonHeaders);
152 logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized");
156 @SuppressWarnings("unchecked")
157 public <T> void Get(T t, String sourceId, String path,
158 org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject) {
160 String methodName = "Get";
161 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
163 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
168 //final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get();
169 final ResponseImpl cres = (ResponseImpl)client.get();
171 logger.debug(EELFLoggerDelegate.debugLogger, "The implemenation class of Response : ", cres.getClass().getName());
172 int status = cres.getStatus();
173 restObject.setStatusCode(status);
175 if (cres.getEntity() != null) {
177 String str = (cres).readEntity(String.class);
178 if (t.getClass().isAssignableFrom(String.class)) {
182 t = (T) gson.fromJson(str, t.getClass());
185 } catch (Exception e) {
186 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
190 restObject.set(null);
194 restObject.set(null);
198 } catch (HttpClientErrorException e) {
199 String message = String.format(
200 HTTP_CLIENT_ERROR, methodName, url);
201 logger.error(EELFLoggerDelegate.errorLogger, message, e);
202 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
203 } catch (Exception e) {
204 String message = String.format("Exception For the POST . MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName, url);
206 logger.error(EELFLoggerDelegate.errorLogger, message, e);
207 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
215 @SuppressWarnings("unchecked")
216 public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) {
218 String methodName = "Post";
219 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
220 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url);
226 // Change the content length
227 final ResponseImpl cres = (ResponseImpl)client.post(requestDetails.toJSONString());
229 if (cres != null && cres.getEntity() != null) {
232 String str = (cres).readEntity(String.class);
233 if (t.getClass().isAssignableFrom(String.class)) {
237 t = (T) gson.fromJson(str, t.getClass());
240 } catch (Exception e) {
241 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
245 restObject.set(null);
248 int status = cres != null ? cres.getStatus() : 0;
249 restObject.setStatusCode(status);
251 if (status >= 200 && status <= 299) {
252 String message = String.format(" REST api POST was successful!", methodName);
253 logger.debug(EELFLoggerDelegate.debugLogger, message);
256 String message = String.format(" FAILED with http status . MethodName: %APPLICATION_JSON, Status: %APPLICATION_JSON, Url: %APPLICATION_JSON",
257 methodName, status, url);
258 logger.debug(EELFLoggerDelegate.debugLogger, message);
261 } catch (HttpClientErrorException e) {
262 String message = String.format(
263 HTTP_CLIENT_ERROR, methodName, url);
264 logger.error(EELFLoggerDelegate.errorLogger, message, e);
265 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
266 } catch (Exception e) {
267 String message = String.format(
268 HTTP_CLIENT_ERROR, methodName, url);
269 logger.error(EELFLoggerDelegate.errorLogger, message, e);
270 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
276 public void logRequest(JSONObject requestDetails) {
277 throw new UnsupportedOperationException();