Portal Spring Boot Development
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / service / sessionmgt / TimeoutHandler.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.util.Hashtable;
41 import java.util.List;
42 import java.util.Map;
43
44 import javax.servlet.http.HttpSession;
45
46 import org.quartz.DisallowConcurrentExecution;
47 import org.quartz.JobExecutionContext;
48 import org.quartz.JobExecutionException;
49 import org.quartz.PersistJobDataAfterExecution;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.context.ApplicationContext;
52 import org.springframework.context.annotation.EnableAspectJAutoProxy;
53 import org.springframework.scheduling.quartz.QuartzJobBean;
54 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
55 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
56 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
57 import org.onap.portalapp.portal.service.EPAppService;
58 import org.onap.portalapp.portal.transport.OnboardingApp;
59 import org.onap.portalapp.portal.utils.EcompPortalUtils;
60 import org.onap.portalsdk.core.domain.sessionmgt.TimeoutVO;
61 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
62 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
63
64 import com.fasterxml.jackson.core.JsonParseException;
65 import com.fasterxml.jackson.core.JsonProcessingException;
66 import com.fasterxml.jackson.core.type.TypeReference;
67 import com.fasterxml.jackson.databind.JsonMappingException;
68 import com.fasterxml.jackson.databind.ObjectMapper;
69
70 /**
71  * Executed periodically by Quartz to discover remote application sessions and
72  * update timeouts suitably.
73  */
74 @PersistJobDataAfterExecution
75 @DisallowConcurrentExecution
76 @org.springframework.context.annotation.Configuration
77 @EnableAspectJAutoProxy
78 @EPMetricsLog
79 public class TimeoutHandler extends QuartzJobBean {
80         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TimeoutHandler.class);
81         
82         private ObjectMapper mapper = new ObjectMapper();
83
84         /**
85          * Supports static call {@link #timeoutSessions(HttpSession)}
86          */
87         private static List<OnboardingApp> onboardedAppList = null;
88         
89         @Autowired
90         private SessionCommunication sessionCommunication;
91         
92         @Override
93         protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
94                 try {
95                         //Create a request id if there is none available,
96                         //and which will internally be used when making
97                         //session extended timeout calls to the partner applications.
98                         if (getSessionCommunication()!=null) {
99                                 getSessionCommunication().setRequestId();
100                         }
101                         logger.info(EELFLoggerDelegate.debugLogger, "Quartz Cronjob for Session Management begins");
102                         
103                         ManageService manageService = (ManageService) applicationContext.getBean("manageService");
104                         EPAppService appService = (EPAppService) applicationContext.getBean("epAppService");
105
106                         List<OnboardingApp> appList = appService.getEnabledNonOpenOnboardingApps();
107                         onboardedAppList = appList;
108                         TypeReference<Hashtable<String, TimeoutVO>> typeRef = new TypeReference<Hashtable<String, TimeoutVO>>() {
109                         };
110                         String portalJsonSessionStr;
111                         Map<String, TimeoutVO> portalSessionTimeoutMap = null;
112
113                         portalJsonSessionStr = manageService.gatherSessionExtenstions();
114                         if (portalJsonSessionStr == null || portalJsonSessionStr == "") {
115                                 logger.error(EELFLoggerDelegate.errorLogger, "Session Management: Portal session information is empty.");
116                                 return;
117                         }
118                         
119                         try {
120                                 portalSessionTimeoutMap = mapper.readValue(portalJsonSessionStr, typeRef);
121                         } catch (JsonMappingException | JsonParseException je) {
122                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, je);
123                                 logger.error(EELFLoggerDelegate.errorLogger, "Session Management: JSON Mapping Exception occurred while gathering the Session", je);
124                                 return;
125                         } catch (Exception e) {
126                                 logger.error(EELFLoggerDelegate.errorLogger, "Session Management: Error while gather Session from portal", e);
127                                 return;
128                         }
129                         
130                         Map<Long, Map<String, TimeoutVO>> appSessionTimeOutMap = new Hashtable<Long, Map<String, TimeoutVO>>();
131                         // determine the Max TimeOut Time for each of the managed sessions
132                         for (OnboardingApp app : appList) {
133                                 if (app.restUrl == null) {
134                                         logger.info(EELFLoggerDelegate.debugLogger, "Session Management: null restUrl, not fetching from app " + app.name);
135                                         continue;
136                                 }
137                                 logger.info(EELFLoggerDelegate.debugLogger, "Session Management: Calling App " + app.name + " at URL " + app.restUrl);
138                                 String jsonSessionStr = fetchAppSessions(app);
139                                 logger.info(EELFLoggerDelegate.debugLogger, "Session Management: App " + app.name + " returned  " + jsonSessionStr);
140                                 if (jsonSessionStr == null || jsonSessionStr.isEmpty())
141                                         continue;
142
143                                 try {
144                                         Map<String, TimeoutVO> sessionTimeoutMap = mapper.readValue(jsonSessionStr, typeRef);
145                                         appSessionTimeOutMap.put(app.id, sessionTimeoutMap);
146                                         for (String portalJSessionId : sessionTimeoutMap.keySet()) {
147                                                 final TimeoutVO maxTimeoutVO = portalSessionTimeoutMap.get(portalJSessionId);
148                                                 final TimeoutVO compareTimeoutVO = sessionTimeoutMap.get(portalJSessionId);
149                                                 if (maxTimeoutVO != null && compareTimeoutVO != null) {
150                                                         if (maxTimeoutVO.compareTo(compareTimeoutVO) < 0)
151                                                                 portalSessionTimeoutMap.get(portalJSessionId)
152                                                                                 .setSessionTimOutMilliSec(compareTimeoutVO.getSessionTimOutMilliSec());
153                                                 }
154                                         }
155                                 } catch (JsonParseException | JsonMappingException e) {
156                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
157                                         logger.error(EELFLoggerDelegate.errorLogger, 
158                                                         "JSON Mapping/Processing Exception occurred while mapping/parsing the jsonSessionStr", e);
159                                         continue;
160                                 } catch (Exception e) {
161                                         logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while mapping/parsing the jsonSessionStr", e);
162                                         continue;
163                                 }
164
165                         }
166
167                         // post the updated session timeouts back to the Apps
168                         for (OnboardingApp app : appList) {
169                                 if (app.restUrl == null) {
170                                         logger.warn(EELFLoggerDelegate.errorLogger, "Session Management: null restUrl, not posting back to app " + app.name);
171                                         continue;
172                                 }
173
174                                 Map<String, TimeoutVO> sessionTimeoutMap = appSessionTimeOutMap.get(app.id);
175                                 if (sessionTimeoutMap == null || sessionTimeoutMap.isEmpty())
176                                         continue;
177
178                                 for (String portalJSessionId : sessionTimeoutMap.keySet()) {
179                                         try {
180                                                 final TimeoutVO maxTimeoutVO = portalSessionTimeoutMap.get(portalJSessionId);
181                                                 final TimeoutVO setTimeoutVO = sessionTimeoutMap.get(portalJSessionId);
182                                                 if (maxTimeoutVO == null || setTimeoutVO == null) {
183                                                         String message = String.format(
184                                                                         "Session Management: Failed to update the session timeouts for the app: %s and the sessionId: %s.",
185                                                                         app.name, portalJSessionId);
186                                                         logger.warn(EELFLoggerDelegate.errorLogger, message);
187                                                         continue;
188                                                 }
189                                                 setTimeoutVO.setSessionTimOutMilliSec(maxTimeoutVO.getSessionTimOutMilliSec());
190                                         } catch (Exception e) {
191                                                 logger.error(EELFLoggerDelegate.errorLogger, "Session Management:  error while updating the session timeout map", e);
192                                                 continue;
193                                         }
194                                 }
195                                 logger.info(EELFLoggerDelegate.debugLogger, "Session Management: Updating App " + app.restUrl);
196                                 String sessionTimeoutMapStr = "";
197                                 try {
198                                         sessionTimeoutMapStr = mapper.writeValueAsString(sessionTimeoutMap);
199                                 } catch (JsonProcessingException je) {
200                                         logger.error(EELFLoggerDelegate.errorLogger, "executeInternal failed while processing sessionTimeOutMap object to a String", je);
201                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, je);
202                                 }
203                                 pingAppSessions(app, sessionTimeoutMapStr);
204                         }
205                         String portalSessionTimeoutMapStr = "";
206                         try {
207                                 portalSessionTimeoutMapStr = mapper.writeValueAsString(portalSessionTimeoutMap);
208                         } catch (JsonProcessingException je) {
209                                 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while processing portalSessionTimeOutMap object to a String", je);
210                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, je);
211                         }
212                         manageService.updateSessionExtensions(portalSessionTimeoutMapStr);
213                 } catch (Exception e) {
214                         logger.error(EELFLoggerDelegate.errorLogger, "************************ Session Management:  error in managing session timeouts", e);
215                 } finally {
216                         getSessionCommunication().clear(true);
217                 }
218         }
219
220         private String fetchAppSessions(OnboardingApp app) throws Exception {
221                 String jsonSessionValue = getSessionCommunication().sendGet(app);
222                 getSessionCommunication().clear(false);
223                 return jsonSessionValue;
224         }
225
226         private void pingAppSessions(OnboardingApp app, String sessionTimeoutMapStr) throws Exception {
227                 getSessionCommunication().pingSession(app, sessionTimeoutMapStr);
228                 getSessionCommunication().clear(false);
229         }
230
231         public void timeoutSessions(HttpSession session) throws Exception {
232                 String portalJSessionId = portalJSessionId(session);
233                 if (onboardedAppList == null)
234                         return;
235
236                 for (OnboardingApp app : onboardedAppList) {
237                         getSessionCommunication().timeoutSession(app, portalJSessionId);
238                         getSessionCommunication().clear(false);
239                 }
240         }
241
242         protected static String portalJSessionId(HttpSession session) {
243                 final Object attribute = session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID);
244                 if (attribute == null)
245                         return "";
246                 String jSessionKey = (String) attribute;
247                 return jSessionKey.split("-")[0];
248                 //return jSessionKey;
249         }
250
251         private static ApplicationContext applicationContext;
252
253         public static void setApplicationContext(ApplicationContext _applicationContext) {
254                 applicationContext = _applicationContext;
255         }
256
257         public SessionCommunication getSessionCommunication() {
258                 if(sessionCommunication == null){
259                         if (applicationContext != null)                         
260                                 sessionCommunication = (SessionCommunication)applicationContext.getBean("sessionCommunication");
261                 }
262                 
263                 return sessionCommunication;
264         }
265
266         public void setSessionCommunication(SessionCommunication sessionCommunication) {
267                 this.sessionCommunication = sessionCommunication;
268         }
269
270 }