2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ===================================================================
10 * Unless otherwise specified, all software contained herein is licensed
11 * under the Apache License, Version 2.0 (the "License");
12 * you may not use this software except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * Unless otherwise specified, all documentation contained herein is licensed
24 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25 * you may not use this documentation except in compliance with the License.
26 * You may obtain a copy of the License at
28 * https://creativecommons.org/licenses/by/4.0/
30 * Unless required by applicable law or agreed to in writing, documentation
31 * distributed under the License is distributed on an "AS IS" BASIS,
32 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33 * See the License for the specific language governing permissions and
34 * limitations under the License.
36 * ============LICENSE_END============================================
41 package org.onap.portal.service;
43 import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
45 import com.google.gson.Gson;
46 import java.net.MalformedURLException;
48 import java.util.Base64;
49 import javax.servlet.http.HttpServletResponse;
50 import javax.ws.rs.core.MediaType;
51 import javax.ws.rs.core.Response;
52 import org.apache.commons.lang.StringUtils;
53 import org.apache.cxf.jaxrs.client.WebClient;
54 import org.apache.cxf.jaxrs.impl.ResponseImpl;
55 import org.apache.cxf.transport.http.HTTPException;
56 import org.onap.portal.domain.db.fn.FnApp;
57 import org.onap.portal.logging.aop.EPMetricsLog;
58 import org.onap.portal.logging.format.EPAppMessagesEnum;
59 import org.onap.portal.logging.logic.EPLogUtil;
60 import org.onap.portal.service.fn.old.AppsCacheService;
61 import org.onap.portal.utils.EPCommonSystemProperties;
62 import org.onap.portal.utils.EcompPortalUtils;
63 import org.onap.portal.utils.SystemType;
64 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
65 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
66 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
67 import org.onap.portalsdk.core.util.SystemProperties;
69 import org.springframework.beans.factory.annotation.Autowired;
70 import org.springframework.stereotype.Service;
73 public class ApplicationsRestClientService {
75 private static final String PASSWORD_HEADER = "password";
76 private static final String APP_USERNAME_HEADER = "username";
77 private static final String BASIC_AUTHENTICATION_HEADER = "Authorization";
79 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ApplicationsRestClientService.class);
83 private final AppsCacheService appsCacheService;
86 public ApplicationsRestClientService(AppsCacheService appsCacheService) {
87 this.appsCacheService = appsCacheService;
90 private static boolean isHttpSuccess(int status) {
91 return status / 100 == 2;
95 private void verifyResponse(Response response, String restPath) throws HTTPException {
96 int status = response.getStatus();
97 logger.debug(EELFLoggerDelegate.debugLogger, "http response status=" + status);
98 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(status));
99 if (!isHttpSuccess(status)) {
101 "Failed. Status=" + status + restPath + "; [" + ((ResponseImpl) response).getStatusInfo()
102 .getReasonPhrase().toString()
106 // must not be null to avoid NPE in HTTPException constructor
107 url = new URL("http://null");
108 if (((ResponseImpl) response).getLocation() != null) {
109 url = ((ResponseImpl) response).getLocation().toURL();
111 } catch (MalformedURLException e) {
112 // never mind. it is only for the debug message.
113 logger.warn(EELFLoggerDelegate.errorLogger, "Failed to build URL", e);
115 logger.error(EELFLoggerDelegate.errorLogger,
116 "http response failed. " + restPath + errMsg + "; url=" + url);
117 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeIncorrectHttpStatusError);
118 throw new HTTPException(status, errMsg, url);
122 private WebClient createClientForApp(long appId, String restPath) {
123 return createClientFor(appId, restPath, SystemType.APPLICATION);
126 private static WebClient createClientForPath(String baseUri, String path) {
127 logger.info(EELFLoggerDelegate.debugLogger, "Creating web client for " + baseUri + " + " + path);
128 WebClient client = WebClient.create(baseUri);
129 client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
134 //TODO Need to implement the mylogins once the endpoint is confirmed
136 private WebClient createClientFor(long appSystemId, String restPath, SystemType type) {
137 logger.debug(EELFLoggerDelegate.debugLogger,
138 "creating client for appId=" + appSystemId + "; restPath=" + restPath);
139 FnApp externalApp = null;
141 if (type == SystemType.APPLICATION) {
142 externalApp = appsCacheService.getApp(appSystemId);
147 if (externalApp != null) {
148 String appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
149 String username = (type == SystemType.APPLICATION) ? externalApp.getAppUsername() : "";
150 String encriptedPwd = (type == SystemType.APPLICATION) ? externalApp.getAppPassword() : "";
152 String appName = (type == SystemType.APPLICATION) ? externalApp.getAppName() : "";
153 String decreptedAppPwd = StringUtils.EMPTY;
156 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP);
157 if (appBaseUri != null && appBaseUri.contains("https")) {
158 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS);
160 MDC.put(EPCommonSystemProperties.FULL_URL, appBaseUri + restPath);
161 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, appName);
162 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, restPath);
164 if (!encriptedPwd.isEmpty() || encriptedPwd != null || StringUtils.isEmpty(encriptedPwd)) {
166 decreptedAppPwd = CipherUtil.decryptPKC(encriptedPwd,
167 SystemProperties.getProperty(SystemProperties.Decryption_Key));
168 } catch (Exception e) {
169 logger.error(EELFLoggerDelegate.errorLogger, "createClientFor failed to decrypt", e);
172 WebClient client = createClientForPath(appBaseUri, restPath);
174 if (externalApp.getAppPassword().isEmpty() || externalApp.getAppPassword() == null) {
175 logger.debug(EELFLoggerDelegate.debugLogger,
176 "Entering in the externalApp get app password contains null : {}");
178 externalApp = appsCacheService.getApp(1L);
179 logger.debug(EELFLoggerDelegate.debugLogger, "external App Information : {}", externalApp);
181 String mechidUsername = externalApp.getAppUsername();
182 logger.debug(EELFLoggerDelegate.debugLogger, "external App mechidUsername Information : {}",
185 String password = externalApp.getAppPassword();
186 String decreptedexternalAppPwd = StringUtils.EMPTY;
188 decreptedexternalAppPwd = CipherUtil.decryptPKC(password,
189 SystemProperties.getProperty(SystemProperties.Decryption_Key));
190 } catch (CipherUtilException e) {
191 logger.error(EELFLoggerDelegate.errorLogger,
192 "failed to decreptedexternalAppPwd when external app pwd is null", e);
195 username = mechidUsername;
196 decreptedAppPwd = decreptedexternalAppPwd;
199 logger.debug(EELFLoggerDelegate.debugLogger,
200 "Entering in the externalApp get app password is not null : {}");
202 // support basic authentication for some partners
203 String encoding = Base64.getEncoder()
204 .encodeToString((username + ":" + decreptedAppPwd).getBytes());
205 String encodingStr = "Basic " + encoding;
206 client.header(BASIC_AUTHENTICATION_HEADER, encodingStr);
209 // But still keep code downward compatible for non compliant apps
210 client.header(APP_USERNAME_HEADER, username);
211 client.header(PASSWORD_HEADER, decreptedAppPwd);
213 String encoding = Base64.getEncoder()
214 .encodeToString((username + ":" + decreptedAppPwd).getBytes());
215 String encodingStr = "Basic " + encoding;
216 client.header(BASIC_AUTHENTICATION_HEADER, encodingStr);
217 client.header(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID));
218 client.header(SystemProperties.USERAGENT_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
219 logger.debug(EELFLoggerDelegate.debugLogger,
221 "check the partner application URL App %d found, baseUri=[%s], Headers: [%s=%s]",
222 appSystemId, appBaseUri,
223 APP_USERNAME_HEADER, username));
229 public <T> T post(Class<T> clazz, long appId, Object payload, String restPath, SystemType type)
230 throws HTTPException {
231 WebClient client = null;
232 Response response = null;
235 client = createClientFor(appId, restPath, type);
236 EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST request =", payload);
239 if (client != null) {
240 response = client.post(payload);
242 logger.error(EELFLoggerDelegate.errorLogger,
243 "Unable to create the Webclient to make the '" + restPath + "' API call.");
245 } catch (Exception e) {
246 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,
247 Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
248 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e);
249 logger.error(EELFLoggerDelegate.errorLogger,
250 "Exception occurred while making the POST REST API call", e);
253 if (response != null) {
254 //verifyResponse(response);
255 verifyResponse(response, restPath);
256 // String contentType = response.getHeaderString("Content-Type");
258 String str = ((ResponseImpl) response).readEntity(String.class);
259 EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST result =", str);
261 t = (T) gson.fromJson(str, clazz);
263 //t = gson.fromJson(str, clazz);
264 } catch (Exception e) {
265 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
272 public <T> T post(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException {
273 return post(clazz, appId, payload, restPath, SystemType.APPLICATION);
276 public <T> T put(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException {
277 WebClient client = null;
278 Response response = null;
281 logger.debug(EELFLoggerDelegate.debugLogger,
282 "Entering to createClientForApp method for payload: {} and restPath: {} and appId: {}",
283 payload.toString(), restPath, appId);
285 client = createClientForApp(appId, restPath);
286 EcompPortalUtils.logAndSerializeObject(logger, restPath, "PUT request =", payload);
288 logger.debug(EELFLoggerDelegate.debugLogger,
289 "Finished createClientForApp method for payload: {} and restPath: {} and appId: {}",
290 payload.toString(), restPath, appId);
293 if (client != null) {
294 logger.debug(EELFLoggerDelegate.debugLogger,
295 "Entering to PUT for payload: {} and restPath: {} and appId: {}",
296 payload.toString(), restPath, appId);
298 response = client.put(payload);
300 logger.debug(EELFLoggerDelegate.debugLogger,
301 "Finished to PUT for payload: {} and restPath: {} and appId: {}",
302 payload.toString(), restPath, appId);
305 logger.error(EELFLoggerDelegate.errorLogger,
306 "Unable to create the Webclient to make the '" + restPath + "' API call.");
308 } catch (Exception e) {
309 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,
310 Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
311 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e);
312 logger.error(EELFLoggerDelegate.errorLogger,
313 "Exception occurred while making the PUT REST API call", e);
316 if (response != null) {
317 //verifyResponse(response);
318 verifyResponse(response, restPath);
319 String str = ((ResponseImpl) response).readEntity(String.class);
320 EcompPortalUtils.logAndSerializeObject(logger, restPath, "PUT result =", str);
322 t = gson.fromJson(str, clazz);
323 } catch (Exception e) {
324 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
330 protected Response getResponse(long appId, String restPath) {
331 WebClient webClient = null;
332 Response response = null;
334 webClient = createClientForApp(appId, restPath);
335 EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET request =", "no-payload");
338 if (webClient != null) {
339 response = webClient.get();
341 logger.error(EELFLoggerDelegate.errorLogger,
342 "Unable to create the Webclient to make the '" + restPath + "' API call.");
344 } catch (Exception e) {
345 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,
346 Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
347 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e);
348 logger.error(EELFLoggerDelegate.errorLogger,
349 "Exception occurred while making the GET REST API call", e);
354 public <T> T get(Class<T> clazz, long appId, String restPath) throws HTTPException {
356 Response response = getResponse(appId, restPath);
358 if (response != null) {
359 //verifyResponse(response);
360 verifyResponse(response, restPath);
361 /* It is not recommendable to use the implementation class org.apache.cxf.jaxrs.impl.ResponseImpl in the code,
362 but had to force this in-order to prevent conflict with the ResponseImpl class of Jersey Client which
363 doesn't work as expected. Created Portal-253 for tracking */
364 String str = ((ResponseImpl) response).readEntity(String.class);
366 EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET result =", str);
368 t = gson.fromJson(str, clazz);
369 } catch (Exception e) {
370 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
377 public String getIncomingJsonString(final Long appId, final String restPath) throws HTTPException {
378 Response response = getResponse(appId, restPath);
380 if (response != null) {
381 //verifyResponse(response);
382 verifyResponse(response,restPath);
383 /* It is not recommendable to use the implementation class org.apache.cxf.jaxrs.impl.ResponseImpl in the code,
384 but had to force this in-order to prevent conflict with the ResponseImpl class of Jersey Client which
385 doesn't work as expected. Created Portal-253 for tracking */
386 String incomingJson = ((ResponseImpl)response).readEntity(String.class);