summaryrefslogtreecommitdiffstats
path: root/ecomp-sdk/thirdparty/src/main/java/org/openecomp/portalsdk/core/onboarding/crossapi/PortalTimeoutHandler.java
blob: 091667949d2e6ea637923aaa29c5199184d24de2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*-
 * ================================================================================
 * eCOMP Portal SDK
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ================================================================================
 */
package org.openecomp.portalsdk.core.onboarding.crossapi;

import java.util.Calendar;
import java.util.Hashtable;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Invoked by listeners (UserContextListener and UserSessionListener) to track
 * user sessions.
 */
public class PortalTimeoutHandler {

	protected static final SessionCommInf sessionComm = new SessionComm();
	
	

	public interface SessionCommInf {
		public Integer fetchSessionSlotCheckInterval(String... params) throws Exception;

		public void extendSessionTimeOuts(String... sessionMap) throws Exception;
	}

	public static class SessionComm implements SessionCommInf {
		public Integer fetchSessionSlotCheckInterval(String... params) throws Exception {

			String ecompRestURL = params[0];
			String userName = params[1];
			String pwd = params[2];
			String uebKey = params[3];

			String sessionSlot = SessionCommunication.getSessionSlotCheckInterval(ecompRestURL, userName, pwd, uebKey);
			if(sessionSlot == null)
				return null;
			return Integer.parseInt(sessionSlot);
		}

		public void extendSessionTimeOuts(String... params) throws Exception {

			String ecompRestURL = params[0];
			String userName = params[1];
			String pwd = params[2];
			String uebKey = params[3];
			String sessionTimeoutMap = params[4];

			SessionCommunication.requestPortalSessionTimeoutExtension(ecompRestURL, userName, pwd, uebKey, sessionTimeoutMap);
		}
	}

	

	public static final Map<String, HttpSession> sessionMap = new Hashtable<String, HttpSession>();
	public static final Integer repeatInterval = 15 * 60; // 15 minutes
	protected static final Log logger = LogFactory.getLog(PortalTimeoutHandler.class);
	static ObjectMapper mapper = new ObjectMapper();
	private static PortalTimeoutHandler timeoutHandler;

	public static PortalTimeoutHandler getInstance() {
		if (timeoutHandler == null)
			timeoutHandler = new PortalTimeoutHandler();

		return timeoutHandler;
	}

	/**
	 * TODO: remove static
	 * 
	 * @param portalJSessionId
	 * @param jSessionId
	 * @param session
	 */
	public static void sessionCreated(String portalJSessionId, String jSessionId, HttpSession session) {

		storeMaxInactiveTime(session);

		// this key is a combination of portal jsession id and app session id
		String jSessionKey = jSessionKey(jSessionId, portalJSessionId);
		Object jSessionKeySessionVal = session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID);
		
		// do not reset the attributes if the same values have already been set 
		// because that will cause PortalTimeoutBindingListener to unbound the value from map
		if(jSessionKeySessionVal != null && jSessionKeySessionVal.equals(jSessionKey)) {
			logger.debug(" Session Values already exist in te map for sessionKey " + jSessionKey);
			return;
		}
		
		session.setAttribute(PortalApiConstants.PORTAL_JSESSION_ID, jSessionKey);

		// session binding listener will add this value to the static map
		// and with session replication the listener will fire in all tomcat
		// instances
		session.setAttribute(PortalApiConstants.PORTAL_JSESSION_BIND, new PortalTimeoutBindingListener());
		// sessionMap.put((String)session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID),
		// session);

	}

	/**
	 * TODO: remove static
	 * 
	 * @param session
	 */
	protected static void storeMaxInactiveTime(HttpSession session) {
		if (session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME) == null)
			session.setAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME, session.getMaxInactiveInterval());
	}

	/**
	 * TODO: remove static
	 * 
	 * @param session
	 */
	public static void sessionDestroyed(HttpSession session) {
		try {
			logger.info(" Session getting destroyed - id: " + session.getId());
			session.removeAttribute(PortalApiConstants.PORTAL_JSESSION_BIND);
			// sessionMap.remove((String)session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID));
		} catch (Exception e) {
			logger.error("Error while destroy user session" + e.getMessage());
		}
	}

	/***
	 * TODO: remove static
	 * 
	 * @param portalJSessionId
	 * @return true on success, false if the session cannot be found, etc.
	 */
	public static boolean invalidateSession(String portalJSessionId) {
		boolean result = false;
		logger.debug("Session Management: request from Portal to invalidate the session: " + portalJSessionId);
		for (String jSessionKey : sessionMap.keySet()) {
			try {
				HttpSession session = sessionMap.get(jSessionKey);
				if (portalJSessionId(jSessionKey).equals(portalJSessionId)) {
					session.invalidate();
					result = true;
				}
			} catch (Exception e) {
				logger.error("Session Management: Error when invalidating session", e);
			}
		}
		return result;
	}

	/**
	 * TODO: remove static
	 * 
	 * @return json version of the timeout map: session ID -> timeout object
	 */
	public static String gatherSessionExtensions() {
		logger.debug("Session Management: gatherSessionExtensions");

		Map<String, PortalTimeoutVO> sessionTimeoutMap = new Hashtable<String, PortalTimeoutVO>();
		String jsonMap = "";

		for (String jSessionKey : sessionMap.keySet()) {

			try {
				// get the expirytime in seconds
				HttpSession session = sessionMap.get(jSessionKey);

				Long lastAccessedTimeMilliSec = session.getLastAccessedTime();
				Long maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000L;
				// Long currentTimeMilliSec =
				// Calendar.getInstance().getTimeInMillis() ;
				// (maxIntervalMilliSec - (currentTimeMilliSec -
				// lastAccessedTimeMilliSec) + ;
				Calendar instance = Calendar.getInstance();
				instance.setTimeInMillis(session.getLastAccessedTime());
				logger.debug("Session Management: Last Accessed time for " + jSessionKey + ": " + instance.getTime());

				Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec;

				sessionTimeoutMap.put(portalJSessionId(jSessionKey),
						getSingleSessionTimeoutObj(jSessionKey, sessionTimOutMilliSec));
				logger.debug("Session Management: putting session in map " + jSessionKey + " sessionTimoutSec"
						+ (int) (sessionTimOutMilliSec / 1000));

				jsonMap = mapper.writeValueAsString(sessionTimeoutMap);

			} catch (Exception e) {
				logger.error("Session Management: Error during JsonSessionTimout conversion", e);
			}

		}

		return jsonMap;

	}

	/**
	 * TODO: remove static
	 * 
	 * @param sessionTimeoutMapStr
	 * @return true on success, false otherwise
	 * @throws Exception
	 */
	public static boolean updateSessionExtensions(String sessionTimeoutMapStr) throws Exception {
		logger.debug("Session Management: updateSessionExtensions");
		// Map<String,Object> sessionTimeoutMap =
		// mapper.readValue(sessionTimeoutMapStr, Map.class);
		Map<String, PortalTimeoutVO> sessionTimeoutMap = null;

		try {
			TypeReference<Hashtable<String, PortalTimeoutVO>> typeRef = new TypeReference<Hashtable<String, PortalTimeoutVO>>() {
			};
			sessionTimeoutMap = mapper.readValue(sessionTimeoutMapStr, typeRef);
		} catch (Exception e) {
			logger.error("Session Management:error when try to parse the sessionTimeoutMap from portal");
			return false;
		}

		boolean result = true;
		for (String jPortalSessionId : sessionTimeoutMap.keySet()) {
			try {
				PortalTimeoutVO extendedTimeoutVO = mapper.readValue(
						mapper.writeValueAsString(sessionTimeoutMap.get(jPortalSessionId)), PortalTimeoutVO.class);
				HttpSession session = sessionMap.get(jSessionKey(extendedTimeoutVO.getjSessionId(), jPortalSessionId));

				if (session == null) {
					continue;
				}

				Long lastAccessedTimeMilliSec = session.getLastAccessedTime();
				Long maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000L;
				Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec;

				Long maxTimeoutTimeMilliSec = extendedTimeoutVO.getSessionTimOutMilliSec();
				if (maxTimeoutTimeMilliSec > sessionTimOutMilliSec) {
					session.setMaxInactiveInterval((int) (maxTimeoutTimeMilliSec - lastAccessedTimeMilliSec) / 1000);
					logger.debug("Session Management: extended session for :" + session.getId() + " to :"
							+ (int) (maxTimeoutTimeMilliSec / 1000));
					// System.out.println("!!!!!!!!!extended session for :" +
					// session.getId() + " to :" +
					// (int)(maxTimeoutTimeMilliSec/1000));
				}
			} catch (Exception e) {
				logger.error("Session Management: error while updating the sessionTimeout" + e.getMessage());
				// Signal a problem if any one of them fails
				result = false;
			}

		}
		return result;
	}

	/**
	 * TODO: Remove static
	 * 
	 * @param request
	 * @param userName
	 * @param pwd
	 * @param ecompRestURL
	 * @param _sessionComm
	 */
	public static void handleSessionUpdatesNative(HttpServletRequest request, String userName, String pwd, String uebKey,
			String ecompRestURL, SessionCommInf _sessionComm) {

		if (_sessionComm == null) {
			_sessionComm = sessionComm;
		}
		try {
			synchronizeSessionForLastMinuteRequests(request, ecompRestURL, userName, pwd, uebKey, _sessionComm);
		} catch (Exception e) {
			logger.error(e);
		}
		resetSessionMaxIdleTimeOut(request);
	}

	/**
	 * TODO: remove Static
	 * 
	 * @param request
	 * @param ecompRestURL
	 * @param userName
	 * @param pwd
	 * @param _sessionComm
	 * @throws JsonProcessingException
	 * @throws Exception
	 */
	public static void synchronizeSessionForLastMinuteRequests(HttpServletRequest request, String ecompRestURL,
			String userName, String pwd, String uebKey, SessionCommInf _sessionComm) throws JsonProcessingException, Exception {

		HttpSession session = request.getSession(false);
		if (session == null)
			return;

		Object portalSessionSlotCheckObj = session.getServletContext()
				.getAttribute(PortalApiConstants.PORTAL_SESSION_SLOT_CHECK);
		Integer portalSessionSlotCheckinMilliSec = 5 * 60 * 1000; // (5 minutes)
		if (portalSessionSlotCheckObj != null) {
			portalSessionSlotCheckinMilliSec = Integer.valueOf(portalSessionSlotCheckObj.toString());
		} else {
			portalSessionSlotCheckObj = _sessionComm
					.fetchSessionSlotCheckInterval(new String[] { ecompRestURL, userName, pwd, uebKey });
			logger.debug("Fetching Portal Session Slot Object: " + portalSessionSlotCheckObj);
			if (portalSessionSlotCheckObj != null) {
				portalSessionSlotCheckinMilliSec = Integer.valueOf(portalSessionSlotCheckObj.toString());
				session.getServletContext().setAttribute(PortalApiConstants.PORTAL_SESSION_SLOT_CHECK,
						portalSessionSlotCheckinMilliSec);
			}
		}

		Object previousToLastAccessTimeObj = session.getAttribute(PortalApiConstants.SESSION_PREVIOUS_ACCESS_TIME);
		final long lastAccessedTimeMilliSec = session.getLastAccessedTime();
		if (previousToLastAccessTimeObj == null) {
			previousToLastAccessTimeObj = lastAccessedTimeMilliSec;
			session.setAttribute(PortalApiConstants.SESSION_PREVIOUS_ACCESS_TIME, previousToLastAccessTimeObj);
		} else {
			Long previousToLastAccessTime = (Long) previousToLastAccessTimeObj;
			final int maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000;
			if (maxIntervalMilliSec
					- (lastAccessedTimeMilliSec - previousToLastAccessTime) <= portalSessionSlotCheckinMilliSec) {

				String jSessionKey = (String) session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID);
				Map<String, PortalTimeoutVO> sessionTimeoutMap = new Hashtable<String, PortalTimeoutVO>();
				Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec;

				sessionTimeoutMap.put(PortalTimeoutHandler.portalJSessionId(jSessionKey),
						PortalTimeoutHandler.getSingleSessionTimeoutObj(jSessionKey, sessionTimOutMilliSec));
				String jsonMap = mapper.writeValueAsString(sessionTimeoutMap);
				logger.debug("Extension requested for all the Apps and Portal;  JessionKey: " + jSessionKey
						+ "; SessionMap: " + sessionTimeoutMap);
				_sessionComm.extendSessionTimeOuts(new String[] { ecompRestURL, userName, pwd, uebKey, jsonMap });
			}

		}
	}

	/**
	 * TODO: remove static
	 * 
	 * @param request
	 */
	public static void resetSessionMaxIdleTimeOut(HttpServletRequest request) {
		try {
			HttpSession session = request.getSession(false);
			if (session == null)
				return;

			final Object maxIdleAttribute = session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME);
			if (maxIdleAttribute != null) {
				session.setMaxInactiveInterval(Integer.parseInt(maxIdleAttribute.toString()));
			}

		} catch (Exception e) {
			logger.error("Could not reset the session timeout", e);
		}

	}

	/**
	 * 
	 * @param jSessionKey
	 * @param sessionTimOutMilliSec
	 * @return
	 */
	private static PortalTimeoutVO getSingleSessionTimeoutObj(String jSessionKey, Long sessionTimOutMilliSec) {
		return new PortalTimeoutVO(jSessionId(jSessionKey), sessionTimOutMilliSec);
	}

	/**
	 * 
	 * @param jSessionId
	 * @param portalJSessionId
	 * @return
	 */
	private static String jSessionKey(String jSessionId, String portalJSessionId) {
		return portalJSessionId + "-" + jSessionId;
	}

	/**
	 * 
	 * @param jSessionKey
	 * @return
	 */
	private static String portalJSessionId(String jSessionKey) {
		return jSessionKey.split("-")[0];
	}

	/**
	 * 
	 * @param jSessionKey
	 * @return
	 */
	private static String jSessionId(String jSessionKey) {
		return jSessionKey.split("-")[1];
	}

}