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