nexus site path corrected
[portal.git] / ecomp-portal-BE / 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.openecomp.portalapp.portal.logging.aop.EPAuditLog;
31 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
32 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
33 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
34 import org.openecomp.portalapp.portal.transport.OnboardingApp;
35 import org.openecomp.portalapp.portal.utils.EPSystemProperties;
36 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
37 import org.openecomp.portalsdk.core.exception.UrlAccessRestrictedException;
38 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
39 import org.slf4j.MDC;
40 import org.springframework.context.annotation.EnableAspectJAutoProxy;
41 import org.springframework.stereotype.Service;
42 import org.springframework.util.StringUtils;
43
44 import com.att.eelf.configuration.Configuration;
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                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
98                         EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiAuthenticationError);
99                 } catch (Exception e) {
100                         responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
101                         String message = String.format(
102                                         "SessionCommunication.sendGet encountered an Exception. AppName: %s, Details: %s", appName,
103                                         EcompPortalUtils.getStackTrace(e));
104                         EPLogUtil.logEcompError(EPAppMessagesEnum.BeHttpConnectionError, e.getMessage());
105                         logger.error(EELFLoggerDelegate.errorLogger, message);
106                 } finally {
107                         EcompPortalUtils.setExternalAppResponseCode(responseCode);
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 && app.name != null && app.name != "") {
118                                 appName = app.name;
119                         }
120                         
121                         String url = app.restUrl + "/updateSessionTimeOuts";
122                         String encriptedPwdDB = app.appPassword;
123                         String appUserName = app.username;
124                         // String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB,
125                         // SystemProperties.getProperty(SystemProperties.Decryption_Key));
126
127                         setLocalMDCContext(app, "/updateSessionTimeOuts", url);
128
129                         URL obj = new URL(url);
130
131                         HttpURLConnection con = (HttpURLConnection) obj.openConnection();
132
133                         // optional default is GET
134                         con.setRequestMethod("POST");
135                         con.setConnectTimeout(3000);
136                         con.setReadTimeout(15000);
137
138                         // add request header
139                         con.setRequestProperty("username", appUserName);
140                         con.setRequestProperty("password", encriptedPwdDB);
141
142                         con.setRequestProperty("sessionMap", sessionTimeoutMap);
143                         con.setDoInput(true);
144                         con.setDoOutput(true);
145                         con.getOutputStream().write(sessionTimeoutMap.getBytes());
146                         con.getOutputStream().flush();
147                         con.getOutputStream().close();
148
149                         responseCode = con.getResponseCode();
150                         logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
151                 } catch (UrlAccessRestrictedException e) {
152                         responseCode = HttpServletResponse.SC_UNAUTHORIZED;
153                         String message = String.format(
154                                         "SessionCommunication.pingSession received an un-authorized exception. AppName: %s", appName);
155                         logger.error(EELFLoggerDelegate.errorLogger, message);
156                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
157                         EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiAuthenticationError);
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(EPAppMessagesEnum.BeHttpConnectionError, e.getMessage());
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                 try {
177                         if (app != null && app.name != null && app.name != "") {
178                                 appName = app.name;
179                         }
180                         
181                         String url = app.restUrl + "/timeoutSession" + "?portalJSessionId=" + portalJSessionId;
182
183                         String encriptedPwdDB = app.appPassword;
184                         String appUserName = app.username;
185                         // String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB,
186                         // SystemProperties.getProperty(SystemProperties.Decryption_Key));
187
188                         setLocalMDCContext(app, "/timeoutSession", url);
189
190                         URL obj = new URL(url);
191                         HttpURLConnection con = (HttpURLConnection) obj.openConnection();
192
193                         // optional default is GET
194                         con.setRequestMethod("POST");
195                         con.setConnectTimeout(3000);
196                         con.setReadTimeout(15000);
197
198                         // add request header
199                         con.setRequestProperty("username", appUserName);
200                         con.setRequestProperty("password", encriptedPwdDB);
201
202                         // con.setRequestProperty("portalJSessionId", portalJSessionId);
203                         con.setDoInput(true);
204                         con.setDoOutput(true);
205                         con.getOutputStream().flush();
206                         con.getOutputStream().close();
207
208                         responseCode = con.getResponseCode();
209                         logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
210                 } catch (UrlAccessRestrictedException e) {
211                         responseCode = HttpServletResponse.SC_UNAUTHORIZED;
212                         String message = String.format(
213                                         "SessionCommunication.timeoutSession received an un-authorized exception. AppName: %s", appName);
214                         logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
215                         logger.error(EELFLoggerDelegate.errorLogger, message);
216                         EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiAuthenticationError);
217                 } catch (Exception e) {
218                         responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
219                         String message = String.format(
220                                         "SessionCommunication.timeoutSession encountered an Exception. AppName: %s, Details: %s", appName,
221                                         EcompPortalUtils.getStackTrace(e));
222                         EPLogUtil.logEcompError(EPAppMessagesEnum.BeHttpConnectionError, e.getMessage());
223                         logger.error(EELFLoggerDelegate.errorLogger, message);
224                 } finally {
225                         EcompPortalUtils.setExternalAppResponseCode(responseCode);
226                 }
227                 return true;
228         }
229
230         @EPMetricsLog
231         private void setLocalMDCContext(OnboardingApp app, String restPath, String url) {
232                 setRequestId();
233                 MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTP);
234                 if (url!=null && url.contains("https")) {
235                         MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTPS);
236                 }
237                 MDC.put(EPSystemProperties.FULL_URL, url);
238                 MDC.put(EPSystemProperties.TARGET_ENTITY, app.name);
239                 MDC.put(EPSystemProperties.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(EPSystemProperties.PARTNER_NAME, EPSystemProperties.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(EPSystemProperties.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(EPSystemProperties.PARTNER_NAME);
272                 }
273         }
274 }