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.service.sessionmgt;
40 import java.io.BufferedReader;
41 import java.io.InputStreamReader;
42 import java.net.HttpURLConnection;
44 import java.util.Base64;
45 import java.util.HashMap;
47 import java.util.UUID;
49 import javax.servlet.http.HttpServletResponse;
51 import org.onap.portalapp.portal.domain.EPApp;
52 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
53 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
54 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
55 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
56 import org.onap.portalapp.portal.service.AppsCacheService;
57 import org.onap.portalapp.portal.transport.OnboardingApp;
58 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
59 import org.onap.portalapp.portal.utils.EcompPortalUtils;
60 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
61 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
62 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
63 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
64 import org.onap.portalsdk.core.onboarding.util.KeyConstants;
65 import org.onap.portalsdk.core.onboarding.util.KeyProperties;
66 import org.onap.portalsdk.core.util.SystemProperties;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.context.annotation.EnableAspectJAutoProxy;
70 import org.springframework.stereotype.Service;
71 import org.apache.commons.lang.StringUtils;
73 import com.att.eelf.configuration.Configuration;
75 @Service("sessionCommunication")
76 @org.springframework.context.annotation.Configuration
77 @EnableAspectJAutoProxy
78 public class SessionCommunication {
79 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionCommunication.class);
81 private AppsCacheService appsCacheService;
83 private static final String BASIC_AUTHENTICATION_HEADER = "Authorization";
86 public String sendGet(OnboardingApp app) throws Exception {
87 String appResponse = "";
90 if (app != null && app.getAppName() != null && app.getAppName() != "") {
92 appName = app.getAppName();
93 String url = app.getRestUrl() + "/sessionTimeOuts";
94 String encriptedPwdDB = app.getAppBasicAuthPassword();
95 String appUserName = app.getAppBasicAuthUsername();
97 setLocalMDCContext(app, "/sessionTimeOuts", url);
99 URL obj = new URL(url);
101 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
103 // optional default is GET
104 con.setRequestMethod("GET");
105 con.setConnectTimeout(3000);
106 con.setReadTimeout(8000);
107 // add request header
108 Map<String,String> headers = getHeaders(app);
109 appUserName =headers.get("username");
110 encriptedPwdDB = headers.get("password");
112 con.setRequestProperty("username", appUserName);
113 con.setRequestProperty("password", encriptedPwdDB);
116 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + encriptedPwdDB).getBytes());
117 String encodingStr = "Basic " + encoding;
118 con.setRequestProperty(BASIC_AUTHENTICATION_HEADER, encodingStr);
121 responseCode = con.getResponseCode();
122 logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
124 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
126 StringBuffer response = new StringBuffer();
128 while ((inputLine = in.readLine()) != null) {
129 response.append(inputLine);
133 appResponse = response.toString();
134 } catch (UrlAccessRestrictedException e) {
135 responseCode = HttpServletResponse.SC_UNAUTHORIZED;
136 logger.error(EELFLoggerDelegate.errorLogger, String.format(
137 "SessionCommunication.sendGet received an un-authorized exception. AppName: %s", appName));
138 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
139 } catch (Exception e) {
140 responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
141 String message = String.format(
142 "SessionCommunication.sendGet encountered an Exception. AppName: %s, Details: %s", appName,
144 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
145 logger.error(EELFLoggerDelegate.errorLogger, message, e);
147 EcompPortalUtils.setExternalAppResponseCode(responseCode);
150 logger.error(EELFLoggerDelegate.errorLogger, "SessionCommunication sendGet: app is null");
156 public Boolean pingSession(OnboardingApp app, String sessionTimeoutMap) throws Exception {
158 int responseCode = 0;
161 throw new Exception("SessionCommunication.pingSession: app is null");
162 if (app != null && app.getAppName() != null && app.getAppName() != "") {
163 appName = app.getAppName();
165 String url = app.getRestUrl() + "/updateSessionTimeOuts";
166 String encriptedPwdDB = app.getAppBasicAuthPassword();
167 String appUserName = app.getAppBasicAuthUsername();
169 setLocalMDCContext(app, "/updateSessionTimeOuts", url);
171 URL obj = new URL(url);
173 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
175 // optional default is GET
176 con.setRequestMethod("POST");
177 con.setConnectTimeout(3000);
178 con.setReadTimeout(15000);
180 Map<String,String> headers = getHeaders(app);
181 appUserName =headers.get("username");
182 encriptedPwdDB = headers.get("password");
184 con.setRequestProperty("username", appUserName);
185 con.setRequestProperty("password", encriptedPwdDB);
187 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + encriptedPwdDB).getBytes());
188 String encodingStr = "Basic " + encoding;
189 con.setRequestProperty(BASIC_AUTHENTICATION_HEADER, encodingStr);
191 con.setRequestProperty("sessionMap", sessionTimeoutMap);
192 con.setDoInput(true);
193 con.setDoOutput(true);
194 con.getOutputStream().write(sessionTimeoutMap.getBytes());
195 con.getOutputStream().flush();
196 con.getOutputStream().close();
198 responseCode = con.getResponseCode();
199 logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
200 } catch (UrlAccessRestrictedException e) {
201 responseCode = HttpServletResponse.SC_UNAUTHORIZED;
202 String message = String.format(
203 "SessionCommunication.pingSession received an un-authorized exception. AppName: %s", appName);
204 logger.error(EELFLoggerDelegate.errorLogger, message);
205 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
206 } catch (Exception e) {
207 responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
208 String message = String.format(
209 "SessionCommunication.pingSession encountered an Exception. AppName: %s, Details: %s", appName, e.toString());
210 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
211 logger.error(EELFLoggerDelegate.errorLogger, message, e);
213 EcompPortalUtils.setExternalAppResponseCode(responseCode);
220 public Boolean timeoutSession(OnboardingApp app, String portalJSessionId) throws Exception {
221 String appName = "Unknwon";
222 int responseCode = 0;
223 if (app != null && app.getAppName() != null && app.getAppName() != "") {
225 appName = app.getAppName();
226 String url = app.getRestUrl() + "/timeoutSession" + "?portalJSessionId=" + portalJSessionId;
228 String encriptedPwdDB = app.getAppBasicAuthPassword();
229 String appUserName = app.getAppBasicAuthUsername();
230 // String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB,
231 // SystemProperties.getProperty(SystemProperties.Decryption_Key));
233 setLocalMDCContext(app, "/timeoutSession", url);
235 URL obj = new URL(url);
236 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
238 // optional default is GET
239 con.setRequestMethod("POST");
240 con.setConnectTimeout(3000);
241 con.setReadTimeout(15000);
243 Map<String,String> headers = getHeaders(app);
244 appUserName =headers.get("username");
245 encriptedPwdDB = headers.get("password");
247 con.setRequestProperty("username", appUserName);
248 con.setRequestProperty("password", encriptedPwdDB);
250 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + encriptedPwdDB).getBytes());
251 String encodingStr = "Basic " + encoding;
252 con.setRequestProperty(BASIC_AUTHENTICATION_HEADER, encodingStr);
254 con.setDoInput(true);
255 con.setDoOutput(true);
256 con.getOutputStream().flush();
257 con.getOutputStream().close();
259 responseCode = con.getResponseCode();
260 logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
261 } catch (UrlAccessRestrictedException e) {
262 responseCode = HttpServletResponse.SC_UNAUTHORIZED;
263 String message = String.format(
264 "SessionCommunication.timeoutSession received an un-authorized exception. AppName: %s",
266 logger.error(EELFLoggerDelegate.errorLogger, message);
267 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
268 } catch (Exception e) {
269 responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
270 String message = String.format(
271 "SessionCommunication.timeoutSession encountered an Exception. AppName: %s, Details: %s",
272 appName, e.toString());
273 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
274 logger.error(EELFLoggerDelegate.errorLogger, message, e);
276 EcompPortalUtils.setExternalAppResponseCode(responseCode);
279 logger.error(EELFLoggerDelegate.errorLogger, "SessionCommunication pingSession: app is null");
285 private void setLocalMDCContext(OnboardingApp app, String restPath, String url) {
287 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP);
288 if (url != null && url.contains("https")) {
289 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS);
291 MDC.put(EPCommonSystemProperties.FULL_URL, url);
292 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, app.getMyLoginsAppName());
293 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, restPath);
297 * Generates request id, service name fields and loads them into MDC, as these
298 * values could be empty as these session timeout requests are generated at
299 * scheduled intervals using quartz scheduler.
302 public void setRequestId() {
303 String requestId = MDC.get(Configuration.MDC_KEY_REQUEST_ID);
304 if (StringUtils.isEmpty(requestId)) {
305 MDC.put(Configuration.MDC_KEY_REQUEST_ID, UUID.randomUUID().toString());
308 MDC.put(Configuration.MDC_SERVICE_NAME, "/quartz/keepSessionAlive");
309 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
313 * Remove the values from MDC as these requests are executed at regular
314 * intervals based on quartz rather incoming REST API requests.
319 public void clear(Boolean bAll) {
320 MDC.remove(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
322 MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
323 MDC.remove(Configuration.MDC_SERVICE_NAME);
324 MDC.remove(EPCommonSystemProperties.PARTNER_NAME);
328 public Map<String,String> getHeaders(OnboardingApp app)
330 String encriptedPwdDB = "";
331 String appUserName = "";
334 Map<String,String> headersMap = new HashMap<>();
335 EPApp externalApp = null;
337 if(app.getAppBasicAuthPassword().isEmpty() || app.getAppBasicAuthPassword()==null){
338 logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the externalApp get app password contains null : {}");
339 externalApp = appsCacheService.getApp(1L);
340 logger.debug(EELFLoggerDelegate.debugLogger, "external App Information : {}",externalApp);
342 String mechidUsername=externalApp.getAppBasicAuthUsername();
343 logger.debug(EELFLoggerDelegate.debugLogger, "external App mechidUsername Information : {}",mechidUsername);
345 String password=externalApp.getAppBasicAuthPassword();
346 String decreptedexternalAppPwd = StringUtils.EMPTY;
348 decreptedexternalAppPwd = CipherUtil.decryptPKC(password,
349 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
350 } catch (CipherUtilException e) {
351 logger.error(EELFLoggerDelegate.errorLogger, "failed to decreptedexternalAppPwd when external app pwd is null", e);
354 appUserName =mechidUsername;
355 encriptedPwdDB = decreptedexternalAppPwd;
358 appUserName = app.getAppBasicAuthUsername();
359 encriptedPwdDB = app.getAppBasicAuthPassword();
362 headersMap.put("username", appUserName);
363 headersMap.put("password", encriptedPwdDB);