Portal Spring Boot Development
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / service / sessionmgt / SessionCommunication.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
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
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
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
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
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.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.service.sessionmgt;
39
40 import java.io.BufferedReader;
41 import java.io.InputStreamReader;
42 import java.net.HttpURLConnection;
43 import java.net.URL;
44 import java.util.UUID;
45
46 import javax.servlet.http.HttpServletResponse;
47
48 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
49 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
50 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
51 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
52 import org.onap.portalapp.portal.transport.OnboardingApp;
53 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
54 import org.onap.portalapp.portal.utils.EcompPortalUtils;
55 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
56 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
57 import org.slf4j.MDC;
58 import org.springframework.context.annotation.EnableAspectJAutoProxy;
59 import org.springframework.stereotype.Service;
60 import org.springframework.util.StringUtils;
61
62 import com.att.eelf.configuration.Configuration;
63
64 @Service("sessionCommunication")
65 @org.springframework.context.annotation.Configuration
66 @EnableAspectJAutoProxy
67 public class SessionCommunication {
68         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionCommunication.class);
69
70         @EPAuditLog
71         public String sendGet(OnboardingApp app) throws Exception {
72                 String appResponse = "";
73                 String appName = "";
74                 int responseCode = 0;
75                 if (app != null && app.name != null && app.name != "") {
76                         try {
77                                 appName = app.name;
78                                 String url = app.restUrl + "/sessionTimeOuts";
79                                 String encriptedPwdDB = app.appPassword;
80                                 String appUserName = app.username;
81
82                                 setLocalMDCContext(app, "/sessionTimeOuts", url);
83
84                                 URL obj = new URL(url);
85
86                                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
87
88                                 // optional default is GET
89                                 con.setRequestMethod("GET");
90                                 con.setConnectTimeout(3000);
91                                 con.setReadTimeout(8000);
92                                 // add request header
93                                 con.setRequestProperty("username", appUserName);
94                                 con.setRequestProperty("password", encriptedPwdDB);
95
96                                 // con.set
97                                 responseCode = con.getResponseCode();
98                                 logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
99
100                                 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
101                                 String inputLine;
102                                 StringBuffer response = new StringBuffer();
103
104                                 while ((inputLine = in.readLine()) != null) {
105                                         response.append(inputLine);
106                                 }
107
108                                 in.close();
109                                 appResponse = response.toString();
110                         } catch (UrlAccessRestrictedException e) {
111                                 responseCode = HttpServletResponse.SC_UNAUTHORIZED;
112                                 logger.error(EELFLoggerDelegate.errorLogger, String.format(
113                                                 "SessionCommunication.sendGet received an un-authorized exception. AppName: %s", appName));
114                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
115                         } catch (Exception e) {
116                                 responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
117                                 String message = String.format(
118                                                 "SessionCommunication.sendGet encountered an Exception. AppName: %s, Details: %s", appName,
119                                                 e.toString());
120                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
121                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
122                         } finally {
123                                 EcompPortalUtils.setExternalAppResponseCode(responseCode);
124                         }
125                 } else {
126                         logger.error(EELFLoggerDelegate.errorLogger, "SessionCommunication sendGet: app is null");
127                 }
128                 return appResponse;
129         }
130
131         @EPAuditLog
132         public Boolean pingSession(OnboardingApp app, String sessionTimeoutMap) throws Exception {
133                 String appName = "";
134                 int responseCode = 0;
135                 try {
136                         if (app == null)
137                                 throw new Exception("SessionCommunication.pingSession: app is null");
138                         if (app != null && app.name != null && app.name != "") {
139                                 appName = app.name;
140                         }
141                         String url = app.restUrl + "/updateSessionTimeOuts";
142                         String encriptedPwdDB = app.appPassword;
143                         String appUserName = app.username;
144
145                         setLocalMDCContext(app, "/updateSessionTimeOuts", url);
146
147                         URL obj = new URL(url);
148
149                         HttpURLConnection con = (HttpURLConnection) obj.openConnection();
150
151                         // optional default is GET
152                         con.setRequestMethod("POST");
153                         con.setConnectTimeout(3000);
154                         con.setReadTimeout(15000);
155
156                         // add request header
157                         con.setRequestProperty("username", appUserName);
158                         con.setRequestProperty("password", encriptedPwdDB);
159
160                         con.setRequestProperty("sessionMap", sessionTimeoutMap);
161                         con.setDoInput(true);
162                         con.setDoOutput(true);
163                         con.getOutputStream().write(sessionTimeoutMap.getBytes());
164                         con.getOutputStream().flush();
165                         con.getOutputStream().close();
166
167                         responseCode = con.getResponseCode();
168                         logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
169                 } catch (UrlAccessRestrictedException e) {
170                         responseCode = HttpServletResponse.SC_UNAUTHORIZED;
171                         String message = String.format(
172                                         "SessionCommunication.pingSession received an un-authorized exception. AppName: %s", appName);
173                         logger.error(EELFLoggerDelegate.errorLogger, message);
174                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
175                 } catch (Exception e) {
176                         responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
177                         String message = String.format(
178                                         "SessionCommunication.pingSession encountered an Exception. AppName: %s, Details: %s", appName, e.toString());
179                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
180                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
181                 } finally {
182                         EcompPortalUtils.setExternalAppResponseCode(responseCode);
183                 }
184
185                 return true;
186         }
187
188         @EPAuditLog
189         public Boolean timeoutSession(OnboardingApp app, String portalJSessionId) throws Exception {
190                 String appName = "Unknwon";
191                 int responseCode = 0;
192                 if (app != null && app.name != null && app.name != "") {
193                         try {
194                                 appName = app.name;
195                                 String url = app.restUrl + "/timeoutSession" + "?portalJSessionId=" + portalJSessionId;
196
197                                 String encriptedPwdDB = app.appPassword;
198                                 String appUserName = app.username;
199                                 // String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB,
200                                 // SystemProperties.getProperty(SystemProperties.Decryption_Key));
201
202                                 setLocalMDCContext(app, "/timeoutSession", url);
203
204                                 URL obj = new URL(url);
205                                 HttpURLConnection con = (HttpURLConnection) obj.openConnection();
206
207                                 // optional default is GET
208                                 con.setRequestMethod("POST");
209                                 con.setConnectTimeout(3000);
210                                 con.setReadTimeout(15000);
211
212                                 // add request header
213                                 con.setRequestProperty("username", appUserName);
214                                 con.setRequestProperty("password", encriptedPwdDB);
215
216                                 // con.setRequestProperty("portalJSessionId", portalJSessionId);
217                                 con.setDoInput(true);
218                                 con.setDoOutput(true);
219                                 con.getOutputStream().flush();
220                                 con.getOutputStream().close();
221
222                                 responseCode = con.getResponseCode();
223                                 logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
224                         } catch (UrlAccessRestrictedException e) {
225                                 responseCode = HttpServletResponse.SC_UNAUTHORIZED;
226                                 String message = String.format(
227                                                 "SessionCommunication.timeoutSession received an un-authorized exception. AppName: %s",
228                                                 appName);
229                                 logger.error(EELFLoggerDelegate.errorLogger, message);
230                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
231                         } catch (Exception e) {
232                                 responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
233                                 String message = String.format(
234                                                 "SessionCommunication.timeoutSession encountered an Exception. AppName: %s, Details: %s", 
235                                                 appName, e.toString());
236                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
237                                 logger.error(EELFLoggerDelegate.errorLogger, message, e);
238                         } finally {
239                                 EcompPortalUtils.setExternalAppResponseCode(responseCode);
240                         }
241                 } else {
242                         logger.error(EELFLoggerDelegate.errorLogger, "SessionCommunication pingSession: app is null");
243                 }
244                 return true;
245         }
246
247         @EPMetricsLog
248         private void setLocalMDCContext(OnboardingApp app, String restPath, String url) {
249                 setRequestId();
250                 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP);
251                 if (url != null && url.contains("https")) {
252                         MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS);
253                 }
254                 MDC.put(EPCommonSystemProperties.FULL_URL, url);
255                 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, app.myLoginsAppName);
256                 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, restPath);
257         }
258
259         /**
260          * Generates request id, service name fields and loads them into MDC, as these
261          * values could be empty as these session timeout requests are generated at
262          * scheduled intervals using quartz scheduler.
263          */
264         @EPMetricsLog
265         public void setRequestId() {
266                 String requestId = MDC.get(Configuration.MDC_KEY_REQUEST_ID);
267                 if (StringUtils.isEmpty(requestId)) {
268                         MDC.put(Configuration.MDC_KEY_REQUEST_ID, UUID.randomUUID().toString());
269                 }
270
271                 MDC.put(Configuration.MDC_SERVICE_NAME, "/quartz/keepSessionAlive");
272                 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
273         }
274
275         /**
276          * Remove the values from MDC as these requests are executed at regular
277          * intervals based on quartz rather incoming REST API requests.
278          * 
279          * @param bAll
280          */
281         @EPMetricsLog
282         public void clear(Boolean bAll) {
283                 MDC.remove(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
284                 if (bAll) {
285                         MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
286                         MDC.remove(Configuration.MDC_SERVICE_NAME);
287                         MDC.remove(EPCommonSystemProperties.PARTNER_NAME);
288                 }
289         }
290 }