summaryrefslogtreecommitdiffstats
path: root/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java
blob: 73003659c6dcd47d5f5b21e60ebb0b1d5667efd6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/*-
 * ============LICENSE_START==========================================
 * ONAP Portal
 * ===================================================================
 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 *  Modifications Copyright (c) 2019 Samsung
 * ===================================================================
 *
 * Unless otherwise specified, all software contained herein is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this software except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Unless otherwise specified, all documentation contained herein is licensed
 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 * you may not use this documentation except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             https://creativecommons.org/licenses/by/4.0/
 *
 * Unless required by applicable law or agreed to in writing, documentation
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ============LICENSE_END============================================
 *
 * 
 */
package org.onap.portalapp.portal.service;

import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;

import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.impl.ResponseImpl;
import org.apache.cxf.transport.http.HTTPException;
import org.onap.portalapp.portal.domain.EPApp;
import org.onap.portalapp.portal.logging.aop.EPAuditLog;
import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
import org.onap.portalapp.portal.logging.logic.EPLogUtil;
import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalapp.util.SystemType;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
import org.onap.portalsdk.core.onboarding.util.CipherUtil;
import org.onap.portalsdk.core.onboarding.util.KeyConstants;
import org.onap.portalsdk.core.onboarding.util.KeyProperties;
import org.onap.portalsdk.core.util.SystemProperties;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

@Service("applicationsRestClientService")
@org.springframework.context.annotation.Configuration
@EnableAspectJAutoProxy
@EPAuditLog
public class ApplicationsRestClientServiceImpl implements ApplicationsRestClientService {

	private static final String PASSWORD_HEADER = "password";

	private static final String APP_USERNAME_HEADER = "username";

	private static final String BASIC_AUTHENTICATION_HEADER = "Authorization";

	private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ApplicationsRestClientServiceImpl.class);

	@Autowired
	private AppsCacheService appsCacheService;

	Gson gson = null;

	private final ObjectMapper mapper = new ObjectMapper();

	@PostConstruct
	private void init() {
		logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
		GsonBuilder builder = new GsonBuilder();

		// Register an adapter to manage the date types as long values
		builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
			public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
					throws JsonParseException {
				return new Date(json.getAsJsonPrimitive().getAsLong());
			}
		});

		gson = builder.create();
	}

	// TODO: do we need to do additional logging for remote API calls?
	private static WebClient createClientForPath(String baseUri, String path) {
		logger.info(EELFLoggerDelegate.debugLogger, "Creating web client for " + baseUri + "   +   " + path);
		WebClient client = WebClient.create(baseUri);
		client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
		client.path(path);
		return client;
	}

	@EPMetricsLog
	private void verifyResponse(Response response,String restPath) throws HTTPException {
		int status = response.getStatus();
		logger.debug(EELFLoggerDelegate.debugLogger, "http response status=" + status);
		MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(status));
		if (!isHttpSuccess(status)) {
			String errMsg = "Failed. Status=" + status + restPath +"; [" + ((ResponseImpl)response).getStatusInfo().getReasonPhrase()
					+ "]";
			URL url = null;
			try {
				// must not be null to avoid NPE in HTTPException constructor
				url = new URL("http://null");
				if (((ResponseImpl)response).getLocation() != null)
					url = ((ResponseImpl)response).getLocation().toURL();
			} catch (MalformedURLException e) {
				// never mind. it is only for the debug message.
				logger.warn(EELFLoggerDelegate.errorLogger, "Failed to build URL", e);
			}
			logger.error(EELFLoggerDelegate.errorLogger, "http response failed. " + restPath + errMsg + "; url=" + url);
			EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeIncorrectHttpStatusError);
			throw new HTTPException(status, errMsg, url);
		}
	}

	private static boolean isHttpSuccess(int status) {
		return status / 100 == 2;
	}
	
	
	private WebClient createClientForApp(long appId, String restPath) {
		return createClientFor(appId, restPath, SystemType.APPLICATION);
	}

	
	
	//TODO Need to implement the mylogins once the endpoint is confirmed
	@EPMetricsLog
	private WebClient createClientFor(long appSystemId, String restPath, SystemType type) {
		logger.debug(EELFLoggerDelegate.debugLogger, "creating client for appId=" + appSystemId + "; restPath=" + restPath);
		EPApp externalApp = null;
		
		if(type == SystemType.APPLICATION){
		externalApp = appsCacheService.getApp(appSystemId);
		}else{
			// TO DO 
		}
		
		if (externalApp != null) {
			String appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : "";
			String username = (type == SystemType.APPLICATION) ? externalApp.getAppBasicAuthUsername(): "";
			String encriptedPwd = (type == SystemType.APPLICATION) ? externalApp.getAppBasicAuthPassword(): "";

			String appName = (type == SystemType.APPLICATION) ? externalApp.getName(): "";
			String decreptedAppPwd = StringUtils.EMPTY;

			// Set local context
			MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP);
			if (appBaseUri != null && appBaseUri.contains("https")) {
				MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS);
			}
			MDC.put(EPCommonSystemProperties.FULL_URL, appBaseUri + restPath);
			MDC.put(EPCommonSystemProperties.TARGET_ENTITY, appName);
			MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, restPath);

			if(!encriptedPwd.isEmpty() || encriptedPwd != null || StringUtils.isEmpty(encriptedPwd)){
			try {
				decreptedAppPwd = CipherUtil.decryptPKC(encriptedPwd,
						KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
			} catch (Exception e) {
				logger.error(EELFLoggerDelegate.errorLogger, "createClientFor failed to decrypt", e.getMessage());
			}
			}
			WebClient client = createClientForPath(appBaseUri, restPath);
			
			
			if(externalApp.getAppBasicAuthPassword().isEmpty() || externalApp.getAppBasicAuthPassword()==null){
				logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the externalApp get app password contains null : {}");

				externalApp = appsCacheService.getApp(1L);
				logger.debug(EELFLoggerDelegate.debugLogger, "external App Information : {}",externalApp);

				String mechidUsername=externalApp.getAppBasicAuthUsername();
				logger.debug(EELFLoggerDelegate.debugLogger, "external App mechidUsername Information : {}",mechidUsername);

				String password=externalApp.getAppBasicAuthPassword();
				String decreptedexternalAppPwd = StringUtils.EMPTY;
				try {
					decreptedexternalAppPwd = CipherUtil.decryptPKC(password,
							KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
				} catch (CipherUtilException e) {
					logger.error(EELFLoggerDelegate.errorLogger, "failed to decreptedexternalAppPwd when external app pwd is null", e);
				}
				
				username =mechidUsername;
				decreptedAppPwd = decreptedexternalAppPwd;
			
			}else{
				logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the externalApp get app password  is not null : {}" );

			// support basic authentication for some partners
			String encoding = Base64.getEncoder().encodeToString((username + ":" + decreptedAppPwd).getBytes());
			String encodingStr = "Basic " + encoding;
			client.header(BASIC_AUTHENTICATION_HEADER, encodingStr);
			}
			
			// But still keep code downward compatible for non compliant apps
			client.header(APP_USERNAME_HEADER, username);
			client.header(PASSWORD_HEADER, decreptedAppPwd);

			String encoding = Base64.getEncoder().encodeToString((username + ":" + decreptedAppPwd).getBytes());
			String encodingStr = "Basic " + encoding;
			client.header(BASIC_AUTHENTICATION_HEADER, encodingStr);
			client.header(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID));
			client.header(SystemProperties.USERAGENT_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
			logger.debug(EELFLoggerDelegate.debugLogger,
					String.format("check the partner application URL App %d found, baseUri=[%s], Headers: [%s=%s]", appSystemId, appBaseUri,
							APP_USERNAME_HEADER, username));
			return client;
		}
		return null;
	}

	@Override
	public <T> T get(Class<T> clazz, long appId, String restPath) throws HTTPException {
		T t = null;
		Response response = getResponse(appId, restPath);

		if (response != null) {
			verifyResponse(response,restPath);
			/* It is not recommendable to use the implementation class org.apache.cxf.jaxrs.impl.ResponseImpl in the code, 
			but had to force this in-order to prevent conflict with the ResponseImpl class of Jersey Client which 
			doesn't work as expected. Created Portal-253 for tracking */
			String str = ((ResponseImpl)response).readEntity(String.class);
			
			EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET result =", str);
			try {
				t = gson.fromJson(str, clazz);
			} catch (Exception e) {
				EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
			}
		}

		return t;
	}
	
	@Override
	public String getIncomingJsonString(long appId, String restPath) throws HTTPException {
		Response response = getResponse(appId, restPath);

		if (response != null) {
			verifyResponse(response,restPath);
			/* It is not recommendable to use the implementation class org.apache.cxf.jaxrs.impl.ResponseImpl in the code, 
			but had to force this in-order to prevent conflict with the ResponseImpl class of Jersey Client which 
			doesn't work as expected. Created Portal-253 for tracking  */
			return ((ResponseImpl)response).readEntity(String.class);
		}
		
		return "";
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.onap.portalapp.portal.service.ApplicationsRestClientService#get(
	 * java.lang.Class, long, java.lang.String, boolean)
	 */
	@Override
	public <T> T get(Class<T> clazz, long appId, String restPath, boolean useJacksonMapper) throws HTTPException {

		if (!useJacksonMapper)
			return get(clazz, appId, restPath);

		T t = null;
		Response response = getResponse(appId, restPath);

		if (response != null) {
			verifyResponse(response,restPath);
			String str = ((ResponseImpl)response).readEntity(String.class);
			EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET result =", str);

			try {
				t = mapper.readValue(str, clazz);
			} catch (Exception e) {
				EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
			}
		}

		return t;
	}

	protected Response getResponse(long appId, String restPath) {
		WebClient webClient = null;
		Response response = null;

		webClient = createClientForApp(appId, restPath);
		EcompPortalUtils.logAndSerializeObject(logger, restPath, "GET request =", "no-payload");

		try {
			if (webClient != null) {
				response = webClient.get();
			} else {
				logger.error(EELFLoggerDelegate.errorLogger,
						"Unable to create the Webclient to make the '" + restPath + "' API call.");
			}
		} catch (Exception e) {
			MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,
					Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
			EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e);
			logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the GET REST API call", e.getMessage());
		}
		return response;
	}
	
	
	@SuppressWarnings({ "unchecked", "null" })
	@Override
	public <T> T post(Class<T> clazz, long appId, Object payload, String restPath, SystemType type) throws HTTPException {
		WebClient client = null;
		Response response = null;
		T t = null;

		client = createClientFor(appId, restPath, type);
		EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST request =", payload);

		try {
			if (client != null) {
				response = client.post(payload);
			} else {
				logger.error(EELFLoggerDelegate.errorLogger,
						"Unable to create the Webclient to make the '" + restPath + "' API call.");
			}
		} catch (Exception e) {
			MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,
					Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
			EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e);
			logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the POST REST API call", e.getMessage());
		}

		if (response != null) {
			verifyResponse(response,restPath);
			if (clazz != null) {
				String str = ((ResponseImpl)response).readEntity(String.class);
				EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST result =", str);
				try {
					t = (T) gson.fromJson(str, clazz);
				} catch (Exception e) {
					EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
				}
			}
		}
		return t;
	}

	@Override
	public <T> T post(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException {
		return post( clazz, appId, payload, restPath, SystemType.APPLICATION);
	}

	
	@Override
	public <T> T put(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException {
		WebClient client = null;
		Response response = null;
		T t = null;

		logger.debug(EELFLoggerDelegate.debugLogger, "Entering to createClientForApp method for payload: {} and restPath: {} and appId: {}", payload.toString(), restPath, appId);

		client = createClientForApp(appId, restPath);
		EcompPortalUtils.logAndSerializeObject(logger, restPath, "PUT request =", payload);
		
		logger.debug(EELFLoggerDelegate.debugLogger, "Finished createClientForApp method for payload: {} and restPath: {} and appId: {}", payload.toString(), restPath, appId);

		try {
			if (client != null) {
				logger.debug(EELFLoggerDelegate.debugLogger, "Entering to PUT for payload: {} and restPath: {} and appId: {}", payload.toString(), restPath, appId);

				response = client.put(payload);
				
				logger.debug(EELFLoggerDelegate.debugLogger, "Finished to PUT for payload: {} and restPath: {} and appId: {}", payload.toString(), restPath, appId);

			} else {
				logger.error(EELFLoggerDelegate.errorLogger,
						"Unable to create the Webclient to make the '" + restPath + "' API call.");
			}
		} catch (Exception e) {
			MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE,
					Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
			EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiGeneralError, e);
			logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the PUT REST API call", e.getMessage());
		}

		if (response != null) {
			verifyResponse(response,restPath);
			String str = ((ResponseImpl)response).readEntity(String.class);
			EcompPortalUtils.logAndSerializeObject(logger, restPath, "PUT result =", str);
			try {
				t = gson.fromJson(str, clazz);
			} catch (Exception e) {
				EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
			}
		}
		return t;
	}
}