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