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