[PORTAL-7] Rebase
[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                 
58                 try {
59                         if (app != null && app.name != null && app.name != "") {
60                                 appName = app.name;
61                         }
62                         String url = app.restUrl + "/sessionTimeOuts";
63                         String encriptedPwdDB = app.appPassword;
64                         String appUserName = app.username;
65
66                         setLocalMDCContext(app, "/sessionTimeOuts", url);
67
68                         URL obj = new URL(url);
69
70                         HttpURLConnection con = (HttpURLConnection) obj.openConnection();
71
72                         // optional default is GET
73                         con.setRequestMethod("GET");
74                         con.setConnectTimeout(3000);
75                         con.setReadTimeout(8000);
76                         // add request header
77                         con.setRequestProperty("username", appUserName);
78                         con.setRequestProperty("password", encriptedPwdDB);
79
80                         // con.set
81                         responseCode = con.getResponseCode();
82                         logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
83                                                 
84                         BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
85                         String inputLine;
86                         StringBuffer response = new StringBuffer();
87
88                         while ((inputLine = in.readLine()) != null) {
89                                 response.append(inputLine);
90                         }
91
92                         in.close();
93                         appResponse = response.toString();
94                 } catch (UrlAccessRestrictedException e) {
95                         responseCode = HttpServletResponse.SC_UNAUTHORIZED;
96                         logger.error(EELFLoggerDelegate.errorLogger, String.format("SessionCommunication.sendGet received an un-authorized exception. AppName: %s", appName));
97                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
98                 } catch (Exception e) {
99                         responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
100                         String message = String.format(
101                                         "SessionCommunication.sendGet encountered an Exception. AppName: %s, Details: %s", appName,
102                                         EcompPortalUtils.getStackTrace(e));
103                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
104                         logger.error(EELFLoggerDelegate.errorLogger, message);
105                 } finally {
106                         EcompPortalUtils.setExternalAppResponseCode(responseCode);
107                 }
108                 return appResponse;
109         }
110
111         @EPAuditLog
112         public Boolean pingSession(OnboardingApp app, String sessionTimeoutMap) throws Exception {
113                 String appName = "Unknwon";
114                 int responseCode = 0;
115                 try {
116                         if (app != null && app.name != null && app.name != "") {
117                                 appName = app.name;
118                         }
119                         
120                         String url = app.restUrl + "/updateSessionTimeOuts";
121                         String encriptedPwdDB = app.appPassword;
122                         String appUserName = app.username;
123                         // String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB,
124                         // SystemProperties.getProperty(SystemProperties.Decryption_Key));
125
126                         setLocalMDCContext(app, "/updateSessionTimeOuts", url);
127
128                         URL obj = new URL(url);
129
130                         HttpURLConnection con = (HttpURLConnection) obj.openConnection();
131
132                         // optional default is GET
133                         con.setRequestMethod("POST");
134                         con.setConnectTimeout(3000);
135                         con.setReadTimeout(15000);
136
137                         // add request header
138                         con.setRequestProperty("username", appUserName);
139                         con.setRequestProperty("password", encriptedPwdDB);
140
141                         con.setRequestProperty("sessionMap", sessionTimeoutMap);
142                         con.setDoInput(true);
143                         con.setDoOutput(true);
144                         con.getOutputStream().write(sessionTimeoutMap.getBytes());
145                         con.getOutputStream().flush();
146                         con.getOutputStream().close();
147
148                         responseCode = con.getResponseCode();
149                         logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
150                 } catch (UrlAccessRestrictedException e) {
151                         responseCode = HttpServletResponse.SC_UNAUTHORIZED;
152                         String message = String.format(
153                                         "SessionCommunication.pingSession received an un-authorized exception. AppName: %s", appName);
154                         logger.error(EELFLoggerDelegate.errorLogger, message);
155                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
156                 } catch (Exception e) {
157                         responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
158                         String message = String.format(
159                                         "SessionCommunication.pingSession encountered an Exception. AppName: %s, Details: %s", appName,
160                                         EcompPortalUtils.getStackTrace(e));
161                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e);
162                         logger.error(EELFLoggerDelegate.errorLogger, message);
163                 } finally {
164                         EcompPortalUtils.setExternalAppResponseCode(responseCode);
165                 }
166                 
167                 return true;
168         }
169
170         @EPAuditLog
171         public Boolean timeoutSession(OnboardingApp app, String portalJSessionId) throws Exception {
172                 String appName = "Unknwon";
173                 int responseCode = 0;
174                 try {
175                         if (app != null && app.name != null && app.name != "") {
176                                 appName = app.name;
177                         }
178                         
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                 return true;
225         }
226
227         @EPMetricsLog
228         private void setLocalMDCContext(OnboardingApp app, String restPath, String url) {
229                 setRequestId();
230                 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP);
231                 if (url!=null && url.contains("https")) {
232                         MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS);
233                 }
234                 MDC.put(EPCommonSystemProperties.FULL_URL, url);
235                 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, app.myLoginsAppName);
236                 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, restPath);
237         }
238         
239         /**
240          * Generates request id, service name fields and loads them
241          * into MDC, as these values could be empty as these
242          * session timeout requests are generated at 
243          * scheduled intervals using quartz scheduler.
244          */
245         @EPMetricsLog
246         public void setRequestId() {
247                 String requestId = MDC.get(Configuration.MDC_KEY_REQUEST_ID);
248                 if (StringUtils.isEmpty(requestId)) {
249                         MDC.put(Configuration.MDC_KEY_REQUEST_ID, UUID.randomUUID().toString());
250                 }
251                 
252                 MDC.put(Configuration.MDC_SERVICE_NAME, "/quartz/keepSessionAlive");
253                 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
254         }
255         
256         /**
257          * Remove the values from MDC as these requests are 
258          * executed at regular intervals based on quartz rather
259          * incoming REST API requests.
260          * @param bAll
261          */
262         @EPMetricsLog
263         public void clear(Boolean bAll) {
264                 MDC.remove(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
265                 if (bAll) {
266                         MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
267                         MDC.remove(Configuration.MDC_SERVICE_NAME);
268                         MDC.remove(EPCommonSystemProperties.PARTNER_NAME);
269                 }
270         }
271 }