2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 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============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
38 package org.openecomp.portalapp.portal.service;
40 import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
42 import java.lang.reflect.Type;
43 import java.net.MalformedURLException;
45 import java.util.Base64;
46 import java.util.Date;
48 import javax.annotation.PostConstruct;
49 import javax.servlet.http.HttpServletResponse;
50 import javax.ws.rs.core.MediaType;
51 import javax.ws.rs.core.Response;
53 import org.apache.cxf.jaxrs.client.WebClient;
54 import org.apache.cxf.transport.http.HTTPException;
55 import org.openecomp.portalapp.portal.domain.EPApp;
56 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
57 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
58 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
59 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
60 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
61 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
62 import org.openecomp.portalapp.util.SystemType;
63 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
64 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
65 import org.openecomp.portalsdk.core.util.SystemProperties;
67 import org.springframework.beans.factory.annotation.Autowired;
68 import org.springframework.context.annotation.EnableAspectJAutoProxy;
69 import org.springframework.stereotype.Service;
71 import com.fasterxml.jackson.databind.ObjectMapper;
72 import com.google.gson.Gson;
73 import com.google.gson.GsonBuilder;
74 import com.google.gson.JsonDeserializationContext;
75 import com.google.gson.JsonDeserializer;
76 import com.google.gson.JsonElement;
77 import com.google.gson.JsonParseException;
79 @Service("applicationsRestClientService")
80 @org.springframework.context.annotation.Configuration
81 @EnableAspectJAutoProxy
83 public class ApplicationsRestClientServiceImpl implements ApplicationsRestClientService {
85 private static final String PASSWORD_HEADER = "password";
87 private static final String APP_USERNAME_HEADER = "username";
89 private static final String BASIC_AUTHENTICATION_HEADER = "Authorization";
91 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ApplicationsRestClientServiceImpl.class);
94 private AppsCacheService appsCacheService;
98 private final ObjectMapper mapper = new ObjectMapper();
101 private void init() {
102 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
103 GsonBuilder builder = new GsonBuilder();
105 // Register an adapter to manage the date types as long values
106 builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
107 public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
108 throws JsonParseException {
109 return new Date(json.getAsJsonPrimitive().getAsLong());
113 gson = builder.create();
116 // TODO: do we need to do additional logging for remote API calls?
117 private static WebClient createClientForPath(String baseUri, String path) {
118 logger.info(EELFLoggerDelegate.debugLogger, "Creating web client for " + baseUri + " + " + path);
119 WebClient client = WebClient.create(baseUri);
120 client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
126 private void verifyResponse(Response response) throws HTTPException {
127 int status = response.getStatus();
128 logger.debug(EELFLoggerDelegate.debugLogger, "http response status=" + status);
129 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(status));
130 if (!isHttpSuccess(status)) {
131 String errMsg = "Failed. Status=" + status + "; [" + response.getStatusInfo().getReasonPhrase().toString()
135 // must not be null to avoid NPE in HTTPException constructor
136 url = new URL("http://null");
137 if (response.getLocation() != null)
138 url = response.getLocation().toURL();
139 } catch (MalformedURLException e) {
140 // never mind. it is only for the debug message.
141 logger.warn(EELFLoggerDelegate.errorLogger, "Failed to build URL", e);
143 logger.error(EELFLoggerDelegate.errorLogger, "http response failed. " + errMsg + "; url=" + url);
144 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeIncorrectHttpStatusError);
145 throw new HTTPException(status, errMsg, url);
149 private static boolean isHttpSuccess(int status) {
150 return status / 100 == 2;
154 private WebClient createClientForApp(long appId, String restPath) {
155 return createClientFor(appId, restPath, SystemType.APPLICATION);
158 //TODO Need to implement the mylogins once the endpoint is confirmed
160 private WebClient createClientFor(long appSystemId, String restPath, SystemType type) {
161 logger.debug(EELFLoggerDelegate.debugLogger, "creating client for appId=" + appSystemId + "; restPath=" + restPath);
162 EPApp externalApp = null;
164 if(type == SystemType.APPLICATION){
165 externalApp = appsCacheService.getApp(appSystemId);
170 if (externalApp != null) {
171 String appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
172 String username = (type == SystemType.APPLICATION) ? externalApp.getUsername(): "";
173 String encriptedPwd = (type == SystemType.APPLICATION) ? externalApp.getAppPassword(): "";
174 String appName = (type == SystemType.APPLICATION) ? externalApp.getName(): "";
175 String decreptedAppPwd = "";
178 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP);
179 if (appBaseUri != null && appBaseUri.contains("https")) {
180 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS);
182 MDC.put(EPCommonSystemProperties.FULL_URL, appBaseUri + restPath);
183 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, appName);
184 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, restPath);
187 decreptedAppPwd = CipherUtil.decrypt(encriptedPwd,
188 SystemProperties.getProperty(SystemProperties.Decryption_Key));
189 } catch (Exception e) {
190 logger.error(EELFLoggerDelegate.errorLogger, "createClientFor failed to decrypt", e);
193 WebClient client = createClientForPath(appBaseUri, restPath);
195 // support basic authentication for some partners
196 String encoding = Base64.getEncoder().encodeToString((username + ":" + decreptedAppPwd).getBytes());
197 String encodingStr = "Basic " + encoding;
198 client.header(BASIC_AUTHENTICATION_HEADER, encodingStr);
200 // But still keep code downward compatible for non compliant apps
201 client.header(APP_USERNAME_HEADER, username);
202 client.header(PASSWORD_HEADER, decreptedAppPwd);
204 client.header(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID));
205 client.header(SystemProperties.USERAGENT_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
207 logger.debug(EELFLoggerDelegate.debugLogger,
208 String.format("App %d found, baseUri=[%s], Headers: [%s=%s, %s=%s, %s=%s]", appSystemId, appBaseUri,
209 APP_USERNAME_HEADER, username, PASSWORD_HEADER, encriptedPwd, BASIC_AUTHENTICATION_HEADER, encodingStr));
217 public <T> T get(Class<T> clazz, long appId, String restPath) throws HTTPException {
219 Response response = getResponse(appId, restPath);
221 if (response != null) {
222 verifyResponse(response);
223 String str = response.readEntity(String.class);
224 EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET result =", str);
226 t = gson.fromJson(str, clazz);
227 } catch (Exception e) {
228 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
236 public String getIncomingJsonString(long appId, String restPath) throws HTTPException {
237 Response response = getResponse(appId, restPath);
239 if (response != null) {
240 verifyResponse(response);
241 String incomingJson = response.readEntity(String.class);
253 * org.openecomp.portalapp.portal.service.ApplicationsRestClientService#get(
254 * java.lang.Class, long, java.lang.String, boolean)
257 public <T> T get(Class<T> clazz, long appId, String restPath, boolean useJacksonMapper) throws HTTPException {
259 if (!useJacksonMapper)
260 return get(clazz, appId, restPath);
263 Response response = getResponse(appId, restPath);
265 if (response != null) {
266 verifyResponse(response);
267 String str = response.readEntity(String.class);
268 EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET result =", str);
271 t = mapper.readValue(str, clazz);
272 } catch (Exception e) {
274 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
281 protected Response getResponse(long appId, String restPath) {
282 WebClient webClient = null;
283 Response response = null;
285 webClient = createClientForApp(appId, restPath);
286 EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET request =", "no-payload");
289 if (webClient != null) {
290 response = webClient.get();
292 logger.error(EELFLoggerDelegate.errorLogger,
293 "Unable to create the Webclient to make the '" + restPath + "' API call.");
295 } catch (Exception e) {
296 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,
297 Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
298 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e);
299 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the GET REST API call", e);
306 public <T> T post(Class<T> clazz, long appId, Object payload, String restPath, SystemType type) throws HTTPException {
307 WebClient client = null;
308 Response response = null;
311 client = createClientFor(appId, restPath, type);
312 EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST request =", payload);
315 if (client != null) {
316 response = client.post(payload);
318 logger.error(EELFLoggerDelegate.errorLogger,
319 "Unable to create the Webclient to make the '" + restPath + "' API call.");
321 } catch (Exception e) {
322 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,
323 Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
324 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e);
325 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the POST REST API call", e);
328 if (response != null) {
329 verifyResponse(response);
331 // String contentType = response.getHeaderString("Content-Type");
333 String str = response.readEntity(String.class);
334 EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST result =", str);
336 t = gson.fromJson(str, clazz);
337 } catch (Exception e) {
338 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
346 public <T> T post(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException {
347 return post( clazz, appId, payload, restPath, SystemType.APPLICATION);
351 public <T> T postForClass(Class<T> clazz, long appId, Object payload, String restPath, Class<T> forClass) throws HTTPException {
352 WebClient client = null;
353 Response response = null;
356 client = createClientForApp(appId, restPath);
357 EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST request =", payload);
360 if (client != null) {
361 response = client.post(payload);
363 logger.error(EELFLoggerDelegate.errorLogger,
364 "Unable to create the Webclient to make the '" + restPath + "' API call.");
366 } catch (Exception e) {
367 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,
368 Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
369 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e);
370 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the POST REST API call", e);
373 if (response != null) {
374 verifyResponse(response);
376 // String contentType = response.getHeaderString("Content-Type");
378 String str = response.readEntity(String.class);
379 EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST result =", str);
381 t = gson.fromJson(str, clazz);
382 } catch (Exception e) {
383 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
392 public <T> T put(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException {
393 WebClient client = null;
394 Response response = null;
397 client = createClientForApp(appId, restPath);
398 EcompPortalUtils.logAndSerializeObject(logger, restPath, "PUT request =", payload);
401 if (client != null) {
402 response = client.put(payload);
404 logger.error(EELFLoggerDelegate.errorLogger,
405 "Unable to create the Webclient to make the '" + restPath + "' API call.");
407 } catch (Exception e) {
408 MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,
409 Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
410 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e);
411 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the PUT REST API call", e);
414 if (response != null) {
415 verifyResponse(response);
416 String str = response.readEntity(String.class);
417 EcompPortalUtils.logAndSerializeObject(logger, restPath, "PUT result =", str);
419 t = gson.fromJson(str, clazz);
420 } catch (Exception e) {
421 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);