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.util.SystemProperties;
66 import org.springframework.beans.factory.annotation.Autowired;
67 import org.springframework.context.annotation.EnableAspectJAutoProxy;
68 import org.springframework.stereotype.Service;
69 import org.apache.commons.lang.StringUtils;
71 import com.att.eelf.configuration.Configuration;
73 @Service("sessionCommunication")
74 @org.springframework.context.annotation.Configuration
75 @EnableAspectJAutoProxy
76 public class SessionCommunication {
77 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionCommunication.class);
79 private AppsCacheService appsCacheService;
81 private static final String BASIC_AUTHENTICATION_HEADER = "Authorization";
84 public String sendGet(OnboardingApp app) throws Exception {
85 String appResponse = "";
88 if (app != null && app.getAppName() != null && app.getAppName() != "") {
90 appName = app.getAppName();
91 String url = app.getRestUrl() + "/sessionTimeOuts";
92 String encriptedPwdDB = app.getAppBasicAuthPassword();
93 String appUserName = app.getAppBasicAuthUsername();
95 setLocalMDCContext(app, "/sessionTimeOuts", url);
97 URL obj = new URL(url);
99 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
101 // optional default is GET
102 con.setRequestMethod("GET");
103 con.setConnectTimeout(3000);
104 con.setReadTimeout(8000);
105 // add request header
106 Map<String,String> headers = getHeaders(app);
107 appUserName =headers.get("username");
108 encriptedPwdDB = headers.get("password");
110 con.setRequestProperty("username", appUserName);
111 con.setRequestProperty("password", encriptedPwdDB);
114 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + encriptedPwdDB).getBytes());
115 String encodingStr = "Basic " + encoding;
116 con.setRequestProperty(BASIC_AUTHENTICATION_HEADER, encodingStr);
119 responseCode = con.getResponseCode();
120 logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
122 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
124 StringBuffer response = new StringBuffer();
126 while ((inputLine = in.readLine()) != null) {
127 response.append(inputLine);
131 appResponse = response.toString();
132 } catch (UrlAccessRestrictedException e) {
133 responseCode = HttpServletResponse.SC_UNAUTHORIZED;
134 logger.error(EELFLoggerDelegate.errorLogger, String.format(
135 "SessionCommunication.sendGet received an un-authorized exception. AppName: %s", appName));
136 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
137 } catch (Exception e) {
138 responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
139 String message = String.format(
140 "SessionCommunication.sendGet encountered an Exception. AppName: %s, Details: %s", appName,
142 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
143 logger.error(EELFLoggerDelegate.errorLogger, message, e);
145 EcompPortalUtils.setExternalAppResponseCode(responseCode);
148 logger.error(EELFLoggerDelegate.errorLogger, "SessionCommunication sendGet: app is null");
154 public Boolean pingSession(OnboardingApp app, String sessionTimeoutMap) throws Exception {
156 int responseCode = 0;
159 throw new Exception("SessionCommunication.pingSession: app is null");
160 if (app != null && app.getAppName() != null && app.getAppName() != "") {
161 appName = app.getAppName();
163 String url = app.getRestUrl() + "/updateSessionTimeOuts";
164 String encriptedPwdDB = app.getAppBasicAuthPassword();
165 String appUserName = app.getAppBasicAuthUsername();
167 setLocalMDCContext(app, "/updateSessionTimeOuts", url);
169 URL obj = new URL(url);
171 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
173 // optional default is GET
174 con.setRequestMethod("POST");
175 con.setConnectTimeout(3000);
176 con.setReadTimeout(15000);
178 Map<String,String> headers = getHeaders(app);
179 appUserName =headers.get("username");
180 encriptedPwdDB = headers.get("password");
182 con.setRequestProperty("username", appUserName);
183 con.setRequestProperty("password", encriptedPwdDB);
185 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + encriptedPwdDB).getBytes());
186 String encodingStr = "Basic " + encoding;
187 con.setRequestProperty(BASIC_AUTHENTICATION_HEADER, encodingStr);
189 con.setRequestProperty("sessionMap", sessionTimeoutMap);
190 con.setDoInput(true);
191 con.setDoOutput(true);
192 con.getOutputStream().write(sessionTimeoutMap.getBytes());
193 con.getOutputStream().flush();
194 con.getOutputStream().close();
196 responseCode = con.getResponseCode();
197 logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
198 } catch (UrlAccessRestrictedException e) {
199 responseCode = HttpServletResponse.SC_UNAUTHORIZED;
200 String message = String.format(
201 "SessionCommunication.pingSession received an un-authorized exception. AppName: %s", appName);
202 logger.error(EELFLoggerDelegate.errorLogger, message);
203 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
204 } catch (Exception e) {
205 responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
206 String message = String.format(
207 "SessionCommunication.pingSession encountered an Exception. AppName: %s, Details: %s", appName, e.toString());
208 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
209 logger.error(EELFLoggerDelegate.errorLogger, message, e);
211 EcompPortalUtils.setExternalAppResponseCode(responseCode);
218 public Boolean timeoutSession(OnboardingApp app, String portalJSessionId) throws Exception {
219 String appName = "Unknwon";
220 int responseCode = 0;
221 if (app != null && app.getAppName() != null && app.getAppName() != "") {
223 appName = app.getAppName();
224 String url = app.getRestUrl() + "/timeoutSession" + "?portalJSessionId=" + portalJSessionId;
226 String encriptedPwdDB = app.getAppBasicAuthPassword();
227 String appUserName = app.getAppBasicAuthUsername();
228 // String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB,
229 // SystemProperties.getProperty(SystemProperties.Decryption_Key));
231 setLocalMDCContext(app, "/timeoutSession", url);
233 URL obj = new URL(url);
234 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
236 // optional default is GET
237 con.setRequestMethod("POST");
238 con.setConnectTimeout(3000);
239 con.setReadTimeout(15000);
241 Map<String,String> headers = getHeaders(app);
242 appUserName =headers.get("username");
243 encriptedPwdDB = headers.get("password");
245 con.setRequestProperty("username", appUserName);
246 con.setRequestProperty("password", encriptedPwdDB);
248 String encoding = Base64.getEncoder().encodeToString((appUserName + ":" + encriptedPwdDB).getBytes());
249 String encodingStr = "Basic " + encoding;
250 con.setRequestProperty(BASIC_AUTHENTICATION_HEADER, encodingStr);
252 con.setDoInput(true);
253 con.setDoOutput(true);
254 con.getOutputStream().flush();
255 con.getOutputStream().close();
257 responseCode = con.getResponseCode();
258 logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
259 } catch (UrlAccessRestrictedException e) {
260 responseCode = HttpServletResponse.SC_UNAUTHORIZED;
261 String message = String.format(
262 "SessionCommunication.timeoutSession received an un-authorized exception. AppName: %s",
264 logger.error(EELFLoggerDelegate.errorLogger, message);
265 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
266 } catch (Exception e) {
267 responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
268 String message = String.format(
269 "SessionCommunication.timeoutSession encountered an Exception. AppName: %s, Details: %s",
270 appName, e.toString());
271 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
272 logger.error(EELFLoggerDelegate.errorLogger, message, e);
274 EcompPortalUtils.setExternalAppResponseCode(responseCode);
277 logger.error(EELFLoggerDelegate.errorLogger, "SessionCommunication pingSession: app is null");
283 private void setLocalMDCContext(OnboardingApp app, String restPath, String url) {
285 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP);
286 if (url != null && url.contains("https")) {
287 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS);
289 MDC.put(EPCommonSystemProperties.FULL_URL, url);
290 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, app.getMyLoginsAppName());
291 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, restPath);
295 * Generates request id, service name fields and loads them into MDC, as these
296 * values could be empty as these session timeout requests are generated at
297 * scheduled intervals using quartz scheduler.
300 public void setRequestId() {
301 String requestId = MDC.get(Configuration.MDC_KEY_REQUEST_ID);
302 if (StringUtils.isEmpty(requestId)) {
303 MDC.put(Configuration.MDC_KEY_REQUEST_ID, UUID.randomUUID().toString());
306 MDC.put(Configuration.MDC_SERVICE_NAME, "/quartz/keepSessionAlive");
307 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
311 * Remove the values from MDC as these requests are executed at regular
312 * intervals based on quartz rather incoming REST API requests.
317 public void clear(Boolean bAll) {
318 MDC.remove(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
320 MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
321 MDC.remove(Configuration.MDC_SERVICE_NAME);
322 MDC.remove(EPCommonSystemProperties.PARTNER_NAME);
326 public Map<String,String> getHeaders(OnboardingApp app)
328 String encriptedPwdDB = "";
329 String appUserName = "";
332 Map<String,String> headersMap = new HashMap<>();
333 EPApp externalApp = null;
335 if(app.getAppBasicAuthPassword().isEmpty() || app.getAppBasicAuthPassword()==null){
336 logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the externalApp get app password contains null : {}");
337 externalApp = appsCacheService.getApp(1L);
338 logger.debug(EELFLoggerDelegate.debugLogger, "external App Information : {}",externalApp);
340 String mechidUsername=externalApp.getAppBasicAuthUsername();
341 logger.debug(EELFLoggerDelegate.debugLogger, "external App mechidUsername Information : {}",mechidUsername);
343 String password=externalApp.getAppBasicAuthPassword();
344 String decreptedexternalAppPwd = StringUtils.EMPTY;
346 decreptedexternalAppPwd = CipherUtil.decryptPKC(password,
347 SystemProperties.getProperty(SystemProperties.Decryption_Key));
348 } catch (CipherUtilException e) {
349 logger.error(EELFLoggerDelegate.errorLogger, "failed to decreptedexternalAppPwd when external app pwd is null", e);
352 appUserName =mechidUsername;
353 encriptedPwdDB = decreptedexternalAppPwd;
356 appUserName = app.getAppBasicAuthUsername();
357 encriptedPwdDB = app.getAppBasicAuthPassword();
360 headersMap.put("username", appUserName);
361 headersMap.put("password", encriptedPwdDB);