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.onap.portalsdk.core.onboarding.exception.CipherUtilException;
58 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
59 import org.onap.portalsdk.core.onboarding.util.KeyConstants;
60 import org.onap.portalsdk.core.onboarding.util.KeyProperties;
61 import org.springframework.http.HttpStatus;
62 import org.springframework.stereotype.Service;
63 import org.springframework.web.client.HttpClientErrorException;
65 import com.google.gson.Gson;
66 import com.google.gson.GsonBuilder;
67 import com.google.gson.JsonDeserializer;
69 import lombok.NoArgsConstructor;
71 @SuppressWarnings("MalformedFormatString")
74 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
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 WebClient client = null;
82 private static Gson gson = null;
84 private MultivaluedHashMap<String, String> 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(String URI) {
98 logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client");
102 final String username;
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;
120 password = CipherUtil.decryptPKC(retrievedPassword,
121 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
122 } catch (CipherUtilException e) {
123 logger.error(EELFLoggerDelegate.errorLogger, "failed to decrypt; Using as is", e);
124 password = retrievedPassword;
129 if (StringUtils.isBlank(password)) {
130 throw new CredentialException(PASSWORD_IS_EMPTY);
132 } catch (Exception ex) {
133 logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex);
135 String authString = username + ":" + password;
136 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
137 String authStringEnc = new String(authEncBytes);
139 commonHeaders = new MultivaluedHashMap<>();
140 commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
143 // if (!username.isEmpty()) {
145 // client = HttpBasicClient.getClient();
148 // client = HttpsBasicClient.getClient();
150 // } catch (Exception e) {
151 // logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest
152 // client",e.getMessage());
156 client = WebClient.create(URI);
157 client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
159 client.headers(commonHeaders);
161 logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized");
165 @SuppressWarnings("unchecked")
166 public <T> void Get(T t, String sourceId, String path,
167 org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject) {
169 String methodName = "Get";
170 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
172 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
176 // final Response cres =
177 // client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get();
178 final ResponseImpl cres = (ResponseImpl) client.get();
180 logger.debug(EELFLoggerDelegate.debugLogger, "The implemenation class of Response : ",
181 cres.getClass().getName());
182 int status = cres.getStatus();
183 restObject.setStatusCode(status);
185 if (cres.getEntity() != null) {
187 String str = (cres).readEntity(String.class);
188 if (t.getClass().isAssignableFrom(String.class)) {
192 t = (T) gson.fromJson(str, t.getClass());
195 } catch (Exception e) {
196 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
200 restObject.set(null);
204 restObject.set(null);
208 } catch (HttpClientErrorException e) {
209 String message = String.format(HTTP_CLIENT_ERROR, methodName, url);
210 logger.error(EELFLoggerDelegate.errorLogger, message, e);
211 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
212 } catch (Exception e) {
213 String message = String.format(
214 "Exception For the POST . MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName, url);
216 logger.error(EELFLoggerDelegate.errorLogger, message, e);
217 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
225 @SuppressWarnings("unchecked")
226 public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) {
228 String methodName = "Post";
229 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
230 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url);
236 // Change the content length
237 final ResponseImpl cres = (ResponseImpl) client.post(requestDetails.toJSONString());
239 if (cres != null && cres.getEntity() != null) {
242 String str = (cres).readEntity(String.class);
243 if (t.getClass().isAssignableFrom(String.class)) {
247 t = (T) gson.fromJson(str, t.getClass());
250 } catch (Exception e) {
251 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
255 restObject.set(null);
258 int status = cres != null ? cres.getStatus() : 0;
259 restObject.setStatusCode(status);
261 if (status >= 200 && status <= 299) {
262 String message = String.format(" REST api POST was successful!", methodName);
263 logger.debug(EELFLoggerDelegate.debugLogger, message);
266 String message = String.format(
267 " FAILED with http status . MethodName: %APPLICATION_JSON, Status: %APPLICATION_JSON, Url: %APPLICATION_JSON",
268 methodName, status, url);
269 logger.debug(EELFLoggerDelegate.debugLogger, message);
272 } catch (HttpClientErrorException e) {
273 String message = String.format(HTTP_CLIENT_ERROR, methodName, url);
274 logger.error(EELFLoggerDelegate.errorLogger, message, e);
275 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
276 } catch (Exception e) {
277 String message = String.format(HTTP_CLIENT_ERROR, methodName, url);
278 logger.error(EELFLoggerDelegate.errorLogger, message, e);
279 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
285 public void logRequest(JSONObject requestDetails) {
286 throw new UnsupportedOperationException();