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");
159 @SuppressWarnings("unchecked")
160 public <T> void Get(T t, String sourceId, String path,
161 org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject) {
163 String methodName = "Get";
164 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
166 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
171 //final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get();
172 final ResponseImpl cres = (ResponseImpl)client.get();
174 logger.debug(EELFLoggerDelegate.debugLogger, "The implemenation class of Response : ", cres.getClass().getName());
175 int status = cres.getStatus();
176 restObject.setStatusCode(status);
178 if (cres.getEntity() != null) {
180 String str = (cres).readEntity(String.class);
181 if (t.getClass().getName().equals(String.class.getName())) {
185 t = (T) gson.fromJson(str, t.getClass());
188 } catch (Exception e) {
189 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
193 restObject.set(null);
197 restObject.set(null);
201 } catch (HttpClientErrorException e) {
202 String message = String.format(
203 HTTP_CLIENT_ERROR, methodName, url);
204 logger.error(EELFLoggerDelegate.errorLogger, message, e);
205 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
206 } catch (Exception e) {
207 String message = String.format("Exception For the POST . MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName, url);
209 logger.error(EELFLoggerDelegate.errorLogger, message, e);
210 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
218 @SuppressWarnings("unchecked")
219 public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) {
221 String methodName = "Post";
222 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
223 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url);
229 // Change the content length
230 final ResponseImpl cres = (ResponseImpl)client.post(requestDetails.toJSONString());
232 if (cres != null && cres.getEntity() != null) {
235 String str = (cres).readEntity(String.class);
236 if (t.getClass().getName().equals(String.class.getName())) {
240 t = (T) gson.fromJson(str, t.getClass());
243 } catch (Exception e) {
244 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
248 restObject.set(null);
251 int status = cres != null ? cres.getStatus() : 0;
252 restObject.setStatusCode(status);
254 if (status >= 200 && status <= 299) {
255 String message = String.format(" REST api POST was successful!", methodName);
256 logger.debug(EELFLoggerDelegate.debugLogger, message);
259 String message = String.format(" FAILED with http status . MethodName: %APPLICATION_JSON, Status: %APPLICATION_JSON, Url: %APPLICATION_JSON",
260 methodName, status, url);
261 logger.debug(EELFLoggerDelegate.debugLogger, message);
264 } catch (HttpClientErrorException e) {
265 String message = String.format(
266 HTTP_CLIENT_ERROR, methodName, url);
267 logger.error(EELFLoggerDelegate.errorLogger, message, e);
268 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
269 } catch (Exception e) {
270 String message = String.format(
271 HTTP_CLIENT_ERROR, methodName, url);
272 logger.error(EELFLoggerDelegate.errorLogger, message, e);
273 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
279 public void logRequest(JSONObject requestDetails) {
280 throw new UnsupportedOperationException();