Example usage for javax.servlet.http HttpSession getMaxInactiveInterval

List of usage examples for javax.servlet.http HttpSession getMaxInactiveInterval

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession getMaxInactiveInterval.

Prototype

public int getMaxInactiveInterval();

Source Link

Document

Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.

Usage

From source file:net.lightbody.bmp.proxy.jetty.servlet.SessionDump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    Page page = new Page();

    HttpSession session = request.getSession(getURI(request).indexOf("new") > 0);

    page.title("Session Dump Servlet: ");

    TableForm tf = new TableForm(response.encodeURL(getURI(request)));
    tf.method("POST");

    if (session == null) {
        page.add("<H1>No Session</H1>");
        tf.addButton("Action", "New Session");
    } else {/*from w w  w  . j  a v  a 2s  . com*/
        try {
            tf.addText("ID", session.getId());
            tf.addText("State", session.isNew() ? "NEW" : "Valid");
            tf.addText("Creation", new Date(session.getCreationTime()).toString());
            tf.addText("Last Access", new Date(session.getLastAccessedTime()).toString());
            tf.addText("Max Inactive", "" + session.getMaxInactiveInterval());

            tf.addText("Context", "" + session.getServletContext());

            Enumeration keys = session.getAttributeNames();
            while (keys.hasMoreElements()) {
                String name = (String) keys.nextElement();
                String value = session.getAttribute(name).toString();
                tf.addText(name, value);
            }

            tf.addTextField("Name", "Property Name", 20, "name");
            tf.addTextField("Value", "Property Value", 20, "value");
            tf.addTextField("MaxAge", "MaxAge(s)", 5, "");
            tf.addButtonArea();
            tf.addButton("Action", "Set");
            tf.addButton("Action", "Remove");
            tf.addButton("Action", "Invalidate");

            page.add(tf);
            tf = null;
            if (request.isRequestedSessionIdFromCookie())
                page.add("<P>Turn off cookies in your browser to try url encoding<BR>");

            if (request.isRequestedSessionIdFromURL())
                page.add("<P>Turn on cookies in your browser to try cookie encoding<BR>");

        } catch (IllegalStateException e) {
            log.debug(LogSupport.EXCEPTION, e);
            page.add("<H1>INVALID Session</H1>");
            tf = new TableForm(getURI(request));
            tf.addButton("Action", "New Session");
        }
    }

    if (tf != null)
        page.add(tf);

    Writer writer = response.getWriter();
    page.write(writer);
    writer.flush();
}

From source file:nl.armatiek.xslweb.serializer.RequestSerializer.java

@SuppressWarnings("rawtypes")
private void serializeSession() throws Exception {
    HttpSession session = req.getSession();
    if (session == null) {
        return;//from  ww w  .j  a v a  2s .  co m
    }
    xsw.writeStartElement(URI, "session");
    dataElement(xsw, URI, "creation-time", getXsDateTimeString(new Date(session.getCreationTime())));
    dataElement(xsw, URI, "id", session.getId());
    dataElement(xsw, URI, "last-accessed-time", getXsDateTimeString(new Date(session.getLastAccessedTime())));
    dataElement(xsw, URI, "max-inactive-interval", Integer.toString(session.getMaxInactiveInterval()));
    dataElement(xsw, URI, "is-new", Boolean.toString(session.isNew()));
    Enumeration attrNames = session.getAttributeNames();
    if (attrNames.hasMoreElements()) {
        xsw.writeStartElement(URI, "attributes");
        while (attrNames.hasMoreElements()) {
            String attrName = (String) attrNames.nextElement();
            xsw.writeStartElement(URI, "attribute");
            xsw.writeAttribute("name", attrName);
            Object attr = session.getAttribute(attrName);
            if (attr instanceof Collection) {
                @SuppressWarnings("unchecked")
                Collection<Attribute> attrs = (Collection<Attribute>) attr;
                for (Attribute a : attrs) {
                    xsw.writeStartElement(URI, "item");
                    if (a.isSerialized()) {
                        xsw.writeAttribute("type", a.getType());
                        getFilteredXMLReader().parse(new InputSource(new StringReader(a.getSerializedValue())));
                    } else {
                        xsw.writeAttribute("type", a.getType());
                        xsw.writeCharacters(a.getValue().toString());
                    }
                    xsw.writeEndElement();
                }
            } else {
                xsw.writeCharacters(attr.toString());
            }
            xsw.writeEndElement();
        }
        xsw.writeEndElement();
    }
    xsw.writeEndElement();
}

From source file:com.jredrain.session.HttpSessionFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    String requestURL = request.getRequestURL().toString();
    String requestName = requestURL.substring(requestURL.lastIndexOf("/") + 1);
    requestName = requestName.toLowerCase();

    //???//from  w w w.  j  ava 2  s. c o m
    if (requestName.matches(".*\\.js$") || requestName.matches(".*\\.css$") || requestName.matches(".*\\.swf$")
            || requestName.matches(".*\\.jpg$") || requestName.matches(".*\\.png$")
            || requestName.matches(".*\\.jpeg$") || requestName.matches(".*\\.html$")
            || requestName.matches(".*\\.htm$") || requestName.matches(".*\\.xml$")
            || requestName.matches(".*\\.txt$") || requestName.matches(".*\\.ico$")) {
        chain.doFilter(request, response);
        return;
    }

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=utf-8");
    Cookie sessionIdCookie = getOrGenerateSessionId(request, response);
    String sessionId = sessionIdCookie.getValue();

    HttpSession rawSession = request.getSession();

    Map sessionData = loadSessionData(sessionId, rawSession);
    try {
        HttpSession sessionWrapper = new HttpSessionStoreWrapper(rawSession, sessionStore, sessionId,
                sessionData);
        chain.doFilter(new HttpServletRequestSessionWrapper(request, sessionWrapper), response);
    } finally {
        try {
            String token = (String) sessionData.get("token");
            if (token != null) {
                //token
                sessionId = token;
                logger.info("login token=" + token);
                sessionData.remove("token");
            }

            sessionStore.saveSession(sessionId, sessionData, rawSession.getMaxInactiveInterval());
        } catch (Exception e) {
            logger.warn("save session data error,cause:" + e, e);
        }
    }
}

From source file:org.opencms.main.CmsSessionManager.java

/**
 * Updates the the OpenCms session data used for quick authentication of users.<p>
 *
 * This is required if the user data (current group or project) was changed in
 * the requested document.<p>//from w ww .  ja  va  2  s. c o  m
 *
 * The user data is only updated if the user was authenticated to the system.
 *
 * @param cms the current OpenCms user context
 * @param req the current request
 */
protected void updateSessionInfo(CmsObject cms, HttpServletRequest req) {

    if (!cms.getRequestContext().isUpdateSessionEnabled()) {
        // this request must not update the user session info
        // this is true for long running "thread" requests, e.g. during project publish
        return;
    }

    if (cms.getRequestContext().getUri().equals(CmsToolManager.VIEW_JSPPAGE_LOCATION)) {
        // this request must not update the user session info
        // if not the switch user feature would not work 
        return;
    }

    if (!cms.getRequestContext().getCurrentUser().isGuestUser()) {
        // Guest user requests don't need to update the OpenCms user session information

        // get the session info object for the user
        CmsSessionInfo sessionInfo = getSessionInfo(req);
        if (sessionInfo != null) {
            // update the users session information
            sessionInfo.update(cms.getRequestContext());
            addSessionInfo(sessionInfo);
        } else {
            HttpSession session = req.getSession(false);
            // only create session info if a session is already available 
            if (session != null) {
                // create a new session info for the user
                sessionInfo = new CmsSessionInfo(cms.getRequestContext(), new CmsUUID(),
                        session.getMaxInactiveInterval());
                // append the session info to the http session
                session.setAttribute(CmsSessionInfo.ATTRIBUTE_SESSION_ID, sessionInfo.getSessionId().clone());
                // update the session info user data
                addSessionInfo(sessionInfo);
            }
        }
    }
}

From source file:org.geonetwork.http.SessionTimeoutCookieFilter.java

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletResponse httpResp = (HttpServletResponse) resp;
    HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpSession session = httpReq.getSession(false);

    //If we are not being accessed by a bot/crawler
    if (session != null) {
        long currTime = System.currentTimeMillis();

        Cookie cookie = new Cookie("serverTime", "" + currTime);
        cookie.setPath("/");
        cookie.setSecure(req.getServletContext().getSessionCookieConfig().isSecure());
        httpResp.addCookie(cookie);/*from  w w  w .jav a  2 s. co  m*/

        UserSession userSession = null;
        if (session != null) {
            Object tmp = session.getAttribute(JeevesServlet.USER_SESSION_ATTRIBUTE_KEY);
            if (tmp instanceof UserSession) {
                userSession = (UserSession) tmp;
            }
        }
        // If user is authenticated, then set expiration time
        if (userSession != null && StringUtils.isNotEmpty(userSession.getName())) {
            long expiryTime = currTime + session.getMaxInactiveInterval() * 1000;
            cookie = new Cookie("sessionExpiry", "" + expiryTime);
        } else {
            cookie = new Cookie("sessionExpiry", "" + currTime);
        }
        cookie.setPath("/");
        cookie.setSecure(req.getServletContext().getSessionCookieConfig().isSecure());
        httpResp.addCookie(cookie);
    }

    filterChain.doFilter(req, resp);
}

From source file:org.codehaus.wadi.web.TestHttpSession.java

public void testMaxInactiveInterval(Manager manager) {
    HttpSession session = ((WADIHttpSession) manager.create(null)).getWrapper();
    {//from www  .  j a  va2  s .  c  om
        int interval = 60 * 60;
        session.setMaxInactiveInterval(interval);
        assertTrue(session.getMaxInactiveInterval() == interval);
    }
    {
        int interval = -1;
        session.setMaxInactiveInterval(interval);
        assertTrue(session.getMaxInactiveInterval() == interval);
    }
}

From source file:SessionSnoop.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    HttpSession session = req.getSession();

    Integer count = (Integer) session.getAttribute("count");
    if (count == null)
        count = new Integer(1);
    else//  w  w w . j  a  v  a2 s  .  c o  m
        count = new Integer(count.intValue() + 1);
    session.setAttribute("count", count);

    out.println("<HTML><HEAD><TITLE>Session Count</TITLE></HEAD>");
    out.println("<BODY><H1>Session Count</H1>");

    out.println("You've visited this page " + count + ((count == 1) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.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>");
}

From source file:MyServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    HttpSession session = req.getSession();

    Integer count = (Integer) session.getAttribute("snoop.count");
    if (count == null)
        count = new Integer(1);
    else/*from  w  w w  .j a  v  a 2 s . c o  m*/
        count = new Integer(count.intValue() + 1);
    session.setAttribute("snoop.count", count);

    out.println("<HTML><HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
    out.println("<BODY><H1>Session Snoop</H1>");

    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 e = session.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.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>");
}

From source file:SessionExpirationFilter.java

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest hReq = (HttpServletRequest) req;

    HttpSession session = hReq.getSession(false);
    if (null != session) {
        Date expirationDate = (Date) session.getAttribute("expirationDate");

        if (expirationDate == null)
            expirationDate = new Date(System.currentTimeMillis() + 1000000); // only
        // for//  ww w  .jav a  2s  . c om
        // make
        // false
        // "expirationDate.before(new Date())"
        // in
        // the
        // first
        // execution

        if (expirationDate.before(new Date())) {
            session.invalidate();
            session = null;
        } else {
            // ignore requests marked as both ajaxCall and ignoreForSessionTimeout
            String isAjaxCall = hReq.getParameter("IsAjaxCall");
            String ignoreForSessionTimeout = hReq.getParameter("ignoreForSessionTimeout");
            boolean ignoreForTimeout = "1".equals(isAjaxCall) && ("1".equals(ignoreForSessionTimeout));
            if (ignoreForTimeout) {
                // Do nothing; don't update the session timestamp
            } else {
                session.setAttribute("expirationDate",
                        new Date(System.currentTimeMillis() + session.getMaxInactiveInterval() * 1000));
            }
        }
    }
    chain.doFilter(req, resp);
}

From source file:com.aurel.track.prop.LoginBL.java

private static StringBuilder assembleJSONPart2(StringBuilder sb, Locale locale, boolean firstTimeEver,
        TPersonBean personBean, HttpSession httpSession, String redirectURL, Integer mobileApplicationVersionNo,
        TMotdBean motd) {/*w  w w . j av  a  2  s  .c o  m*/
    String licURL = "";
    if (ApplicationBean.getInstance().getLicenseManager() != null) {
        licURL = ApplicationBean.getInstance().getLicenseManager().getLicenseUrl(locale);
    }

    JSONUtility.appendStringValue(sb, "licURL", licURL, false);
    JSONUtility.appendBooleanValue(sb, "ftever", firstTimeEver, false);

    boolean isld = true;

    JSONUtility.appendBooleanValue(sb, "isLicenseDerfined", isld, false);

    JSONUtility.appendStringValue(sb, "jsonURL", redirectURL, false);
    if (httpSession.getAttribute(ISMOBILEAPP) != null) {
        if ((Boolean) httpSession.getAttribute(ISMOBILEAPP)) {
            // This property is added for mobile client,
            if (personBean != null && personBean.getLocale() != null) {
                JSONUtility.appendStringValue(sb, "locale", personBean.getLocale().toString());
                JSONUtility.appendStringValue(sb, "datePattern", getLocaleDatePattern(personBean.getLocale()));
                JSONUtility.appendIntegerValue(sb, "userLevel", personBean.getUserLevel());
                JSONUtility.appendIntegerValue(sb, "sessionTimeoutMinutes",
                        httpSession.getMaxInactiveInterval() / 60);
                JSONUtility.appendJSONValue(sb, "userSettingsProperties", getUserProperties(personBean));
                JSONUtility.appendIntegerValue(sb, "userObjectID", personBean.getObjectID());
                JSONUtility.appendStringValue(sb, "serverVersion", ApplicationBean.getInstance().getVersion());
                JSONUtility.appendIntegerValue(sb, "serverVersionNo",
                        ApplicationBean.getInstance().getVersionNo());
                JSONUtility.appendIntegerValue(sb, "clientCompatibility",
                        MobileBL.checkClientCompatibility(mobileApplicationVersionNo, true));
                JSONUtility.appendStringValue(sb, "sessionId", httpSession.getId());

                Integer iconKey = Integer.valueOf(-1);
                try {
                    byte[] oneAvatar = AvatarBL.getAvatarInByteArray(personBean.getObjectID(), iconKey);
                    MessageDigest md = MessageDigest.getInstance("MD5");
                    byte[] thedigest = md.digest(oneAvatar);
                    String checksum = DatatypeConverter.printBase64Binary(thedigest);
                    JSONUtility.appendStringValue(sb, "checkSum", checksum);
                } catch (Exception ex) {
                }
            }
        }
    }
    String motdMsg = motd.getTheMessage();
    if (motdMsg == null) {
        motdMsg = "&nbsp;";
    }
    try {
        JSONUtility.appendStringValue(sb, "teaserText",
                Html2Text.getNewInstance().convert(motd.getTeaserText()));
    } catch (Exception ex) {
    }
    JSONUtility.appendStringValue(sb, "motd", motdMsg, true);

    sb.append("}");
    sb.append("}");
    return sb;
}