public static void showSession(HttpServletRequest req, PrintStream out) { // res.setContentType("text/html"); // Get the current session object, create one if necessary HttpSession session = req.getSession(); out.println("Session id: " + session.getId()); out.println(" session.isNew(): " + session.isNew()); out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval() + " secs"); out.println( " session.getCreationTime(): " + session.getCreationTime() + " (" + new Date(session.getCreationTime()) + ")"); out.println( " session.getLastAccessedTime(): " + session.getLastAccessedTime() + " (" + new Date(session.getLastAccessedTime()) + ")"); out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie()); out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL()); out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid()); out.println("Saved session Attributes:"); Enumeration atts = session.getAttributeNames(); while (atts.hasMoreElements()) { String name = (String) atts.nextElement(); out.println(" " + name + ": " + session.getAttribute(name) + "<BR>"); } }
public static void showSession(HttpServletRequest req, HttpServletResponse res, PrintStream out) { // res.setContentType("text/html"); // Get the current session object, create one if necessary HttpSession session = req.getSession(); // Increment the hit count for this page. The value is saved // in this client's session under the name "snoop.count". Integer count = (Integer) session.getAttribute("snoop.count"); if (count == null) { count = 1; } else count = count + 1; session.setAttribute("snoop.count", count); out.println(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag()); out.println("<HEAD><TITLE>SessionSnoop</TITLE></HEAD>"); out.println("<BODY><H1>Session Snoop</H1>"); // Display the hit count for this page out.println( "You've visited this page " + count + ((!(count.intValue() != 1)) ? " time." : " times.")); out.println("<P>"); out.println("<H3>Here is your saved session data:</H3>"); Enumeration atts = session.getAttributeNames(); while (atts.hasMoreElements()) { String name = (String) atts.nextElement(); out.println(name + ": " + session.getAttribute(name) + "<BR>"); } out.println("<H3>Here are some vital stats on your session:</H3>"); out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>"); out.println("New session: " + session.isNew() + "<BR>"); out.println("Timeout: " + session.getMaxInactiveInterval()); out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>"); out.println("Creation time: " + session.getCreationTime()); out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>"); out.println("Last access time: " + session.getLastAccessedTime()); out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>"); out.println( "Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>"); out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>"); out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>"); out.println("<H3>Test URL Rewriting</H3>"); out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>"); out.println("to test that session tracking works via URL"); out.println("rewriting even when cookies aren't supported."); out.println("</BODY></HTML>"); }
/** * Creates an HttpSubSession. * * @param backing the backing HTTP session. * @param subsessionId the subsession's id. */ public HttpSubSession(final HttpSession backing, final int subsessionId) { maxInactiveInterval = backing.getMaxInactiveInterval(); creationTime = System.currentTimeMillis(); lastAccessedTime = creationTime; this.sessionId = subsessionId; this.backing = backing; }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json"); final PrintWriter out = resp.getWriter(); HttpSession session = req.getSession(false); if (session != null) { Subject subject = (Subject) session.getAttribute("subject"); if (subject == null) { LOG.warn("No security subject stored in existing session, invalidating"); session.invalidate(); Helpers.doForbidden(resp); return; } sendResponse(session, subject, out); return; } AccessControlContext acc = AccessController.getContext(); Subject subject = Subject.getSubject(acc); if (subject == null) { Helpers.doForbidden(resp); return; } Set<Principal> principals = subject.getPrincipals(); String username = null; if (principals != null) { for (Principal principal : principals) { if (principal.getClass().getSimpleName().equals("UserPrincipal")) { username = principal.getName(); LOG.debug("Authorizing user {}", username); } } } session = req.getSession(true); session.setAttribute("subject", subject); session.setAttribute("user", username); session.setAttribute("org.osgi.service.http.authentication.remote.user", username); session.setAttribute( "org.osgi.service.http.authentication.type", HttpServletRequest.BASIC_AUTH); session.setAttribute("loginTime", GregorianCalendar.getInstance().getTimeInMillis()); if (timeout != null) { session.setMaxInactiveInterval(timeout); } if (LOG.isDebugEnabled()) { LOG.debug( "Http session timeout for user {} is {} sec.", username, session.getMaxInactiveInterval()); } sendResponse(session, subject, out); }
/** * 初始化 * * @param session HttpSession对象 * @param key sessionkey * @date 2015年12月12日 上午11:22:30 * @author yxl */ public RedisSession( HttpSession session, HttpServletRequest request, HttpServletResponse response) { this.httpSession = session; this.request = request; this.response = response; this.key = getSessionKey(); timeout = session.getMaxInactiveInterval() / 60; if (servletContext == null) servletContext = RedisServletContext.getInstance(request.getServletContext()); }
private Map loadSessionData(String sessionId, HttpSession rawSession) { Map sessionData = null; try { sessionData = sessionStore.getSession(sessionId, rawSession.getMaxInactiveInterval()); } catch (Exception e) { sessionData = new HashMap(); log.warn("load session data error,cause:" + e, e); } return sessionData; }
long getKeepAliveScheduleTime() throws IllegalStateException { int maxInactiveInterval = httpSession.getMaxInactiveInterval(); if (maxInactiveInterval < 0) { return Long.MAX_VALUE; } long lastAccessedTime = Math.max(this.lastAccessedTime, httpSession.getLastAccessedTime()); return (maxInactiveInterval * 1000) - (System.currentTimeMillis() - lastAccessedTime) - SESSION_KEEP_ALIVE_BUFFER; }
@Test public void testWhenTheyHaveALowDefaultSessionTimeout() { httpServletRequest.setRemoteUser("bill"); HttpSession session = httpServletRequest.getSession(true); // make a session session.setMaxInactiveInterval(5); botKiller.processRequest(httpServletRequest); assertEquals(5, session.getMaxInactiveInterval()); assertNull(session.getAttribute(BotKiller.class.getName())); }
@Test public void testRequestHasUserGetsDifferentTimeout() throws Exception { httpServletRequest.setRemoteUser("bill"); HttpSession session = httpServletRequest.getSession(true); // make a session session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL); botKiller.processRequest(httpServletRequest); assertEquals(USER_LOW_INACTIVE_TIMEOUT, session.getMaxInactiveInterval()); assertEquals(MAX_INACTIVE_INTERVAL, session.getAttribute(BotKiller.class.getName())); }
void removeSession(String id) { if (!isManagementOfSessionsTurnedOn()) { return; } HttpSession session = sessions.remove(id); long lastAccessedTime = session == null ? 0 : session.getLastAccessedTime(); int maxInactiveInterval = session == null ? 0 : session.getMaxInactiveInterval(); getContext() .publishEvent(new HttpSessionDestroyed(this, id, lastAccessedTime, maxInactiveInterval)); }
@Test public void testNeverSeenThisSessionSoItsLowered() throws Exception { HttpSession session = httpServletRequest.getSession(true); // make a session session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL); botKiller.processRequest(httpServletRequest); assertEquals(LOW_INACTIVE_TIMEOUT, session.getMaxInactiveInterval()); assertEquals(MAX_INACTIVE_INTERVAL, session.getAttribute(BotKiller.class.getName())); // now have a second request botKiller.processRequest(httpServletRequest); assertEquals(MAX_INACTIVE_INTERVAL, Integer.valueOf(session.getMaxInactiveInterval())); assertEquals(MAX_INACTIVE_INTERVAL, session.getAttribute(BotKiller.class.getName())); // any future requests is still the same timeout on the session for (int i = 0; i < 10; i++) { botKiller.processRequest(httpServletRequest); assertEquals(MAX_INACTIVE_INTERVAL, Integer.valueOf(session.getMaxInactiveInterval())); assertEquals(MAX_INACTIVE_INTERVAL, session.getAttribute(BotKiller.class.getName())); } }
private void joinChat() { String userColor; sessionService.addOnSessionDestroyedListener(callback); defaultSessionTimeout = httpSession.getMaxInactiveInterval(); httpSession.setMaxInactiveInterval(0); lastActivityTime = System.currentTimeMillis(); String username = ((User) authToken.getPrincipal()).getUsername(); LOG.debug("joinChat() user: "******"USER", username); int userNb = usersLoggedIn.incrementAndGet(); // If a user is active more than once, give him the same color: if (userColorMap.containsKey(username)) { userColor = userColorMap.get(username); } else { userColor = PEER_COLORS[userNb % PEER_COLOR_NB]; userColorMap.put(username, userColor); } thisSession.getUserProperties().put("COLOR", userColor); Message joinMsg = new Message(); joinMsg.TYPE = "JOIN"; joinMsg.SUBTYPE = "JOIN"; joinMsg.USER_LIST = buildUserList(true); joinMsg.STATS_MSG = userNb + " User" + (userNb > 1 ? "s " : " ") + "online!"; sendMessage(joinMsg); Message infoMsg = new Message(); infoMsg.TYPE = "INFO"; infoMsg.SUBTYPE = "JOIN"; infoMsg.INFO_MSG = username + " has entered the building"; infoMsg.STATS_MSG = userNb + " User" + (userNb > 1 ? "s " : " ") + "online!"; infoMsg.USER_LIST = buildUserList(true); broadcastMessage(infoMsg, false); }
@Test public void testErrorWhenCheckingUsernameDoesNotKillBotKiller() { botKiller = new BotKiller( new MockUserManager(null) { @Override public String getRemoteUsername(HttpServletRequest request) { throw new RuntimeException("a most unexpected error"); } }); httpServletRequest.setRemoteUser("bill"); HttpSession session = httpServletRequest.getSession(true); // make a session session.setMaxInactiveInterval(MAX_INACTIVE_INTERVAL); botKiller.processRequest(httpServletRequest); assertEquals(LOW_INACTIVE_TIMEOUT, session.getMaxInactiveInterval()); assertEquals(MAX_INACTIVE_INTERVAL, session.getAttribute(BotKiller.class.getName())); }
public void logStats(HttpSession session, GenericValue visit) { if (Debug.verboseOn() || session.getAttribute("org.ofbiz.log.session.stats") != null) { Debug.log("<===================================================================>", module); Debug.log("Session ID : " + session.getId(), module); Debug.log("Created Time : " + session.getCreationTime(), module); Debug.log("Last Access : " + session.getLastAccessedTime(), module); Debug.log("Max Inactive : " + session.getMaxInactiveInterval(), module); Debug.log("--------------------------------------------------------------------", module); Debug.log("Total Sessions : " + ControlEventListener.getTotalActiveSessions(), module); Debug.log("Total Active : " + ControlEventListener.getTotalActiveSessions(), module); Debug.log("Total Passive : " + ControlEventListener.getTotalPassiveSessions(), module); Debug.log("** note : this session has been counted as destroyed.", module); Debug.log("--------------------------------------------------------------------", module); Debug.log("Visit ID : " + visit.getString("visitId"), module); Debug.log("Party ID : " + visit.getString("partyId"), module); Debug.log("Client IP : " + visit.getString("clientIpAddress"), module); Debug.log("Client Host : " + visit.getString("clientHostName"), module); Debug.log("Client User : "******"clientUser"), module); Debug.log("WebApp : " + visit.getString("webappName"), module); Debug.log("Locale : " + visit.getString("initialLocale"), module); Debug.log("UserAgent : " + visit.getString("initialUserAgent"), module); Debug.log("Referrer : " + visit.getString("initialReferrer"), module); Debug.log("Initial Req : " + visit.getString("initialRequest"), module); Debug.log("Visit From : " + visit.getString("fromDate"), module); Debug.log("Visit Thru : " + visit.getString("thruDate"), module); Debug.log("--------------------------------------------------------------------", module); Debug.log("--- Start Session Attributes: ---", module); Enumeration<String> sesNames = null; try { sesNames = UtilGenerics.cast(session.getAttributeNames()); } catch (IllegalStateException e) { Debug.log("Cannot get session attributes : " + e.getMessage(), module); } while (sesNames != null && sesNames.hasMoreElements()) { String attName = sesNames.nextElement(); Debug.log(attName + ":" + session.getAttribute(attName), module); } Debug.log("--- End Session Attributes ---", module); Debug.log("<===================================================================>", module); } }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); String action = request.getParameter("action"); if ("set".equals(action)) { if (session == null) session = request.getSession(true); int value = Integer.parseInt(request.getParameter("value")); session.setAttribute("value", value); PrintWriter writer = response.getWriter(); writer.println(value); writer.flush(); } else if ("get".equals(action)) { int value = (Integer) session.getAttribute("value"); int x = session.getMaxInactiveInterval(); assertTrue(x > 0); PrintWriter writer = response.getWriter(); writer.println(value); writer.flush(); } }
@Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { Cookie sessionIdCookie = getOrGenerateSessionId(request, response); String sessionId = sessionIdCookie.getValue(); HttpSession rawSession = request.getSession(); Map sessionData = loadSessionData(sessionId, rawSession); try { HttpSession sessionWrapper = new HttpSessionSessionStoreWrapper(rawSession, sessionStore, sessionId, sessionData); chain.doFilter(new HttpServletRequestSessionWrapper(request, sessionWrapper), response); } finally { try { sessionStore.saveSession(sessionId, sessionData, rawSession.getMaxInactiveInterval()); } catch (Exception e) { log.warn("save session data error,cause:" + e, e); } } }
@SuppressWarnings("rawtypes") private String getLoginSuccessResponse(HttpSession session, String responseType) { StringBuffer sb = new StringBuffer(); int inactiveInterval = session.getMaxInactiveInterval(); if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { sb.append("{ \"loginresponse\" : { "); Enumeration attrNames = session.getAttributeNames(); if (attrNames != null) { sb.append("\"timeout\" : \"" + inactiveInterval + "\""); while (attrNames.hasMoreElements()) { String attrName = (String) attrNames.nextElement(); Object attrObj = session.getAttribute(attrName); if ((attrObj instanceof String) || (attrObj instanceof Long)) { sb.append(", \"" + attrName + "\" : \"" + attrObj.toString() + "\""); } } } sb.append(" } }"); } else { sb.append("<loginresponse>"); sb.append("<timeout>" + inactiveInterval + "</timeout>"); Enumeration attrNames = session.getAttributeNames(); if (attrNames != null) { while (attrNames.hasMoreElements()) { String attrName = (String) attrNames.nextElement(); Object attrObj = session.getAttribute(attrName); if (attrObj instanceof String || attrObj instanceof Long || attrObj instanceof Short) { sb.append("<" + attrName + ">" + attrObj.toString() + "</" + attrName + ">"); } } } sb.append("</loginresponse>"); } return sb.toString(); }
public LiferayLocalSession(HttpSession httpSession) { super(); setWrapped(httpSession); setMaxInactiveInterval(httpSession.getMaxInactiveInterval()); }
/** * Returns HTML tags to include all JavaScript files and codes that are required when loading a * ZUML page (never null). * * <p>FUTURE CONSIDERATION: we might generate the inclusion on demand instead of all at once. * * @param exec the execution (never null) * @param wapp the Web application. If null, exec.getDesktop().getWebApp() is used. So you have to * specify it if the execution is not associated with desktop (a fake execution, such as * JSP/DSP). * @param deviceType the device type, such as ajax. If null, exec.getDesktop().getDeviceType() is * used. So you have to specify it if the execution is not associated with desktop (a fake * execution). */ public static final String outLangJavaScripts(Execution exec, WebApp wapp, String deviceType) { if (exec.isAsyncUpdate(null) || exec.getAttribute(ATTR_LANG_JS_GENED) != null) return ""; // nothing to generate exec.setAttribute(ATTR_LANG_JS_GENED, Boolean.TRUE); final Desktop desktop = exec.getDesktop(); if (wapp == null) wapp = desktop.getWebApp(); if (deviceType == null) deviceType = desktop != null ? desktop.getDeviceType() : "ajax"; final StringBuffer sb = new StringBuffer(1536); final Set<JavaScript> jses = new LinkedHashSet<JavaScript>(32); for (LanguageDefinition langdef : LanguageDefinition.getByDeviceType(deviceType)) jses.addAll(langdef.getJavaScripts()); for (JavaScript js : jses) append(sb, js); sb.append("\n<!-- ZK ").append(wapp.getVersion()); if (WebApps.getFeature("ee")) sb.append(" EE"); else if (WebApps.getFeature("pe")) sb.append(" PE"); sb.append(' ').append(wapp.getBuild()); Object o = wapp.getAttribute("org.zkoss.zk.ui.notice"); if (o != null) sb.append(o); sb.append(" -->\n"); int tmout = 0; final Boolean autoTimeout = getAutomaticTimeout(desktop); if (autoTimeout != null ? autoTimeout.booleanValue() : wapp.getConfiguration().isAutomaticTimeout(deviceType)) { if (desktop != null) { tmout = desktop.getSession().getMaxInactiveInterval(); } else { Object req = exec.getNativeRequest(); if (req instanceof HttpServletRequest) { final HttpSession hsess = ((HttpServletRequest) req).getSession(false); if (hsess != null) { final Session sess = SessionsCtrl.getSession(wapp, hsess); if (sess != null) { tmout = sess.getMaxInactiveInterval(); } else { // try configuration first since HttpSession's timeout is set // when ZK Session is created (so it is not set yet) // Note: no need to setMaxInactiveInternval here since it will // be set later or not useful at the end tmout = wapp.getConfiguration().getSessionMaxInactiveInterval(); if (tmout <= 0) // system default tmout = hsess.getMaxInactiveInterval(); } } else tmout = wapp.getConfiguration().getSessionMaxInactiveInterval(); } } if (tmout > 0) { // unit: seconds int extra = tmout / 8; tmout += extra > 60 ? 60 : extra < 5 ? 5 : extra; // Add extra seconds to ensure it is really timeout } } final boolean keepDesktop = exec.getAttribute(Attributes.NO_CACHE) == null && !"page".equals(ExecutionsCtrl.getPageRedrawControl(exec)), groupingAllowed = isGroupingAllowed(desktop); final String progressboxPos = org.zkoss.lang.Library.getProperty("org.zkoss.zul.progressbox.position", ""); if (tmout > 0 || keepDesktop || progressboxPos.length() > 0 || !groupingAllowed) { sb.append("<script class=\"z-runonce\" type=\"text/javascript\">\nzkopt({"); if (keepDesktop) sb.append("kd:1,"); if (!groupingAllowed) sb.append("gd:1,"); if (tmout > 0) sb.append("to:").append(tmout).append(','); if (progressboxPos.length() > 0) sb.append("ppos:'").append(progressboxPos).append('\''); if (sb.charAt(sb.length() - 1) == ',') sb.setLength(sb.length() - 1); sb.append("});\n</script>"); } final Device device = Devices.getDevice(deviceType); String s = device.getEmbedded(); if (s != null) sb.append(s).append('\n'); return sb.toString(); }
@Override public int getMaxInactiveInterval() { return httpSession.getMaxInactiveInterval(); }
/** * Return the sessions' time-to-live. * * @return the timeout value for this session. */ public int getTimeout() { ensureSession(); return rep.getMaxInactiveInterval(); }
@Override public int getMaxInactiveInterval() { return sess.getMaxInactiveInterval(); }
/** * Invoke the {@link AtmosphereHandler#onRequest} method. * * @param req the {@link AtmosphereRequest} * @param res the {@link AtmosphereResponse} * @return action the Action operation. * @throws java.io.IOException * @throws javax.servlet.ServletException */ Action action(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException { boolean webSocketEnabled = false; if (req.getHeaders("Connection") != null && req.getHeaders("Connection").hasMoreElements()) { String[] e = req.getHeaders("Connection").nextElement().toString().split(","); for (String upgrade : e) { if (upgrade.equalsIgnoreCase("Upgrade")) { webSocketEnabled = true; break; } } } if (webSocketEnabled && !supportWebSocket()) { res.setStatus(501); res.addHeader(X_ATMOSPHERE_ERROR, "Websocket protocol not supported"); res.flushBuffer(); return new Action(); } if (config.handlers().isEmpty()) { logger.error( "No AtmosphereHandler found. Make sure you define it inside META-INF/atmosphere.xml"); throw new AtmosphereMappingException( "No AtmosphereHandler found. Make sure you define it insides META-INF/atmosphere.xml"); } if (supportSession()) { // Create the session needed to support the Resume // operation from disparate requests. HttpSession session = req.getSession(true); // Do not allow times out. if (session.getMaxInactiveInterval() == DEFAULT_SESSION_TIMEOUT) { session.setMaxInactiveInterval(-1); } } req.setAttribute(FrameworkConfig.SUPPORT_SESSION, supportSession()); AtmosphereHandlerWrapper handlerWrapper = map(req); // Check Broadcaster state. If destroyed, replace it. Broadcaster b = handlerWrapper.broadcaster; if (b.isDestroyed()) { synchronized (handlerWrapper) { config.getBroadcasterFactory().remove(b, b.getID()); handlerWrapper.broadcaster = config.getBroadcasterFactory().get(b.getID()); } } AtmosphereResourceImpl resource = new AtmosphereResourceImpl( config, handlerWrapper.broadcaster, req, res, this, handlerWrapper.atmosphereHandler); req.setAttribute(FrameworkConfig.ATMOSPHERE_RESOURCE, resource); req.setAttribute(FrameworkConfig.ATMOSPHERE_HANDLER, handlerWrapper.atmosphereHandler); try { handlerWrapper.atmosphereHandler.onRequest(resource); } catch (IOException t) { resource.onThrowable(t); throw t; } if (trackActiveRequest && resource.getAtmosphereResourceEvent().isSuspended() && req.getAttribute(FrameworkConfig.CANCEL_SUSPEND_OPERATION) == null) { req.setAttribute(MAX_INACTIVE, System.currentTimeMillis()); aliveRequests.put(req, resource); } return resource.action(); }